I am developing a Web Service solution that is hosted inside a JBoss 4.2.3 sever (as the following) and my code connect to Remote JMS queue hat is hosted on another server(192.168.35.25)
public static Context getInitialContext () throws JMSException,NamingException
{
Properties prop = new Properties();
prop.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
prop.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming");
prop.setProperty("java.naming.provider.url", "192.168.35.20:1099");
Context context = new InitialContext(prop);
return context;
}
public String SendMessages(String msg) throws ServletException, IOException, URISyntaxException {
String body="";
try
{
Context init =ClsSat.getInitialContext();
javax.jms.Queue destination = (javax.jms.Queue) init.lookup("Queue/RemoteQueue");
ConnectionFactory connectionFactory = (ConnectionFactory) init.lookup("ConnectionFactory");
Connection connection = connectionFactory.createConnection("un","pwd");//
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
;
MessageProducer producer = session.createProducer(destination);
TextMessage message = session.createTextMessage();
message.setText(msg);
connection.start();
producer.send(message);
body = message.getText();
session.close();
connection.close();
}
catch (Exception e)
{
return(e.toString());
}
return body ;
}
But I got an error ... RemoteQueue not bound
so any one have an idea or help about connect to remote queus throw web service
or any documents about connect to Remote queue on remote machine from web service hosted on local machine
Can it be because of the wrong IP address in your getInitialContext(), please check if not you can provide some more detail.
Related
Hey there we want to use Django just to execute python code and use channels for the results. Implemented everything the websockets are not working as they should. If I try to send something from our Angular frontend to Django it works fine. And otherwise our Spring Boot StompSession Websockets work fine with other Spring Boot Applications and Angular.
But Django 3.1.3 and Spring Boot 2.3.3 do not.
Additionally channels 3.0.2, channels-redis 3.2.0 and a docker container of redis 6 are used.
What I can see from the Django server logs:
WebSocket HANDSHAKING /ws/card-detection/ [127.0.0.1:53209]
i'm in connect method
WebSocket CONNECT /ws/card-detection/ [127.0.0.1:53209]
i'm in receive method
text_data: CONNECT
This gets executed as soon as the websocket request comes in.
The django consumer (without the prints that are logged above):
class MyConsumer(WebsocketConsumer):
groups = ["broadcast"]
def connect(self):
self.accept()
def receive(self, text_data=None, bytes_data=None):
self.send(text_data="Hello world!")
def disconnect(self, close_code):
pass
From Spring Boot we send an base64 encoded image. But also everything else does not work. As you can see the text_data is just CONNECT.
Spring Boot:
StompSessionHandler sessionHandler =
new CardDetectionStompSessionHandler(request, user, webSocketMessagingService);
createStompClient().connect(djangoServiceWSPath, sessionHandler);
}
private WebSocketStompClient createStompClient() {
WebSocketClient client = new StandardWebSocketClient();
WebSocketStompClient stompClient = new WebSocketStompClient(client);
stompClient.setMessageConverter(new MappingJackson2MessageConverter());
return stompClient;
}
The stomp session handler to give you an idea how it looks. It should go in the afterConnected() method but it will never go in any of this methods:
public class CardDetectionStompSessionHandler extends StompSessionHandlerAdapter {
private final ImageClassificationRequest request;
private final String username;
private final String destination = "/card-detection/";
private final WebSocketMessagingService webSocketMessagingService;
private StompSession session;
public CardDetectionStompSessionHandler(
ImageClassificationRequest request,
String username,
WebSocketMessagingService webSocketMessagingService) {
this.request = request;
this.username = username;
this.webSocketMessagingService = webSocketMessagingService;
}
#Override
public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
log.info("Client: New session established: {}", session.getSessionId());
this.session = session;
session.subscribe("/user/queue/response", this);
log.info("Client: Subscribed to \"/user/queue/response\"");
session.send("/app" + destination, request);
log.info("Client: Message sent to {}", session.getSessionId());
}
#Override
public Type getPayloadType(StompHeaders headers) {
return ImageClassificationResponse.class;
}
#Override
public void handleFrame(StompHeaders headers, Object payload) {
log.info("Client: Message received");
ImageClassificationResponse response = (ImageClassificationResponse) payload;
webSocketMessagingService.sendToUser(username, response);
if (response.isDone()) {
session.disconnect();
log.info("Client: Disconnected.");
}
}
#Override
public void handleTransportError(StompSession session, Throwable exception) {
log.info("Client: Django is not available");
WebSocketResponse response = new WebSocketResponse();
response.setDisconnect(true);
webSocketMessagingService.sendToUser(username, response);
}
}
We tried to change it to an async websocket in Django but that didn't changed a thing. The self.accept in Djangos connect() method does not seem to send a response or the response Spring Boot needs to go on.
I want to add Authorization header for basic Authorization to my jetty-client request.
I am running two instances on same browser one is server one is client ,Java-8 is being used as a technology, No DB No Spring etc. using org.eclipse.jetty,jetty-websocket,version-8.1.15.v20140411.
I had a websocketEndPointManager class which contains the initialization method for both Server(dedicated class is CSWebsocket) and client(Cpwebsocket).
How can I achieve basic auth in my scenario where server maintains username and password is to matched in current session after its instance is ready, currently my setup able to perform upgrade to websocket but not basic
Snippet of client websocket start method where handshake occur :
private void startCPWebSocket() throws Exception{
String uri ="";
try {
HandlerRegistry.register(this);
WebSocketClientFactory factory = new WebSocketClientFactory();
Configuration configuration = TestSession.getConfiguration();
uri = configuration.getSystemUnderTestEndpoint();
TestSession.getConfiguration().setToolURL("NA");
TestSession.getConfiguration().setSystemUnderTestEndpoint(uri);
factory.start();
WebSocketClient client = factory.newWebSocketClient();
client.setMaxIdleTime(24*60*60*1000);
client.open(new URI(uri.trim()),new CPWebSocket()).get(24*60*60,
TimeUnit.SECONDS);
LogUtils.logInfo("WebSocket URL : "+uri,true);
}
catch (ExecutionException e) {
LogUtils.logError(e.getMessage(), e,false);
LogUtils.logWarn("Could not establish websocket connection.",true);
//System.exit(0);
TestSession.setTerminated(true);
throw e;
I have searched other posts and set required things in my gmail account(https://myaccount.google.com/lesssecureapps)
but somehow it still throws exception with the message "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at"
[HttpPost]
public ActionResult SaveAppointment(Appointment mdl)
{
try
{
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
smtpClient.Credentials = new System.Net.NetworkCredential("username", "mypass");
smtpClient.UseDefaultCredentials = false;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
MailMessage mail = new MailMessage();
//Setting From , To and CC
mail.From = new MailAddress("username#gmail.com", "MyWeb Site");
mail.To.Add(new MailAddress("username#gmail.com"));
smtpClient.Send(mail);
return View();
}
catch(Exception ex)
{
return null;
}
}
What should it be I missing?
Check your web.config, msdn and code (because there could be no matching EnableSsl in the configuration file.
You may also need to enable access for "less secure apps" in your gmail settings page. here
This is necessary if you are getting the exception "`The server response was: 5.5.1 Authentication Required. Then below code should works.
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("username", "password"),
EnableSsl = true
};
client.Send("username#gmail.com", "username#gmail.com", "subject", "body");
i tried to connect REST web servie from windows phone 8 application.
it was working proberly for weeks but after no change in it I get this generic error :
System.Net.WebException: The remote server returned an error:
NotFound.
i tried to test it by online REST Clients and services works properly
i tried to handle Exception and parse it as webException by this code :
var we = ex.InnerException as WebException;
if (we != null)
{
var resp = we.Response as HttpWebResponse;
response.StatusCode = resp.StatusCode;
and i get no more information and final response code is : "NotFound"
any one have any idea about what may cause this error?
there is already a trusted Certificate implemented on the server . the one who has the server suggested to have a DNS entry for the server, this entry should be at the customer DNS or in the phone hosts file .that what i done and worked for awhile but now it doesn't work however i checked that there is no thing changed
this is sample for Get Request it works proberly on Windwos Store apps :
async Task<object> GetHttps(string uri, string parRequest, Type returnType, params string[] parameters)
{
try
{
string strRequest = ConstructRequest(parRequest, parameters);
string encodedRequest = HttpUtility.UrlEncode(strRequest);
string requestURL = BackEndURL + uri + encodedRequest;
HttpWebRequest request = HttpWebRequest.Create(new Uri(requestURL, UriKind.Absolute)) as HttpWebRequest;
request.Headers["applicationName"] = AppName;
request.Headers["applicationPassword"] = AppPassword;
if (AppVersion > 1)
request.Headers["applicationVersion"] = AppVersion.ToString();
request.Method = "GET";
request.CookieContainer = cookieContainer;
var factory = new TaskFactory();
var getResponseTask = factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
HttpWebResponse response = await getResponseTask as HttpWebResponse;
// string s = response.GetResponseStream().ToString();
if (response.StatusCode == HttpStatusCode.OK)
{
XmlSerializer serializer = new XmlSerializer(returnType);
object obj = serializer.Deserialize(response.GetResponseStream());
return obj;
}
else
{
var Instance = Activator.CreateInstance(returnType);
(Instance as ResponseBase).NetworkError = true;
(Instance as ResponseBase).StatusCode = response.StatusCode;
return Instance;
}
}
catch (Exception ex)
{
return HandleException(ex, returnType);
}
}
i tried to monitor connections from Emulator and i found this error in connection :
**
Authentication failed because the remote party has closed the
transport stream.
**
You saw the client implement a server side certificate in the service. Did you have that certificate installed on the phone? That can be the cause of the NotFound error. Please, can you try to navigate to the service in the phone or emulator internet explorer prior to testing the app? If you do that, you can see the service working in the emulator/phone internet explorer? Maybe at that point internet explorer ask you about installing the certificate and then you can open your app, and it works.
Also remember if you are testing this in the emulator, every time you close it, the state is lost so you need to repeat the operation of installing the certificate again.
Hope this helps.
If you plan to use SSL in production in general public application (not company-distribution app), you need to ensure your certificate has one of the following root authorities:
SSL root certificates for Windows Phone OS 7.1.
When we had same issue, we purchased SSL certificate from one of those providers and after installing it on server we were able to make HTTPS requests to our services with no problem.
If you have company-distribution app, you can use any certificate from company's Root CA.
I am trying to pull a list of vendors from my local instance of Great Plains.
When I visit
http://localhost:48620/DynamicsGPWebServices/DynamicsGPService.asmx
I am asked to login. I enter my windows credentials, then I see endpoint not found.
I know that the web service exists.
I know that my windows credentials are correct because they are the admin account.
I have the sample company installed.
Here is my code:
DynamicsGP g = new DynamicsGP();
g.Credentials = new NetworkCredential("username", "password", "domain");
// Create an instance of the web service want to do this
//asynchronously.
// Be sure the default credentials are used
//g.UseDefaultCredentials = true;
// Create a context with which to call the web service
Context context = new Context();
// Specify which company to use (sample company)
var companyKey = new CompanyKey();
companyKey.Id = (-1);
// Set up the context object
context.OrganizationKey = (OrganizationKey)companyKey;
context.CultureName = "en-US";
//error occurs after this line
VendorSummary[] vs = g.GetVendorList(new VendorCriteria(), context);
I receive this error:
{System.Net.WebException: Unable to connect to the remote server ---> > System.Net.Sockets.SocketException: No connection could be made because the target machine actively > refused it 127.0.0.1:48260
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, > Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 > timeout, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at PMInvoices.DynamicsGPService.DynamicsGP.GetVendorList(VendorCriteria criteria, Context Context) in >c:\Users\joe_a84\Downloads\DeveloperToolkitSampleApps\PMInvoices\PMInvoices\PMInvoices\Web References\DynamicsGPService\Reference.cs:line 4069
I see the URL is this:
http://machinename:48620/DynamicsGPWebServices
where machinename is localhost.