Connecting to SSL WebService - java

I want to connect to a web service in a SSL connection. I connect to it and I get Service and Port but when I send Requests, it just returns null.
I searched the web but I could not understand what is the problem. may be because it is SSL, I need to connect it different as an Http connection, is it true?
I used auto code generators, they return null too, WireShark says that SSL Packages transmitted correctly but I cannot read the SOAP from these packages because they are SSL.
I test the web service with some applications and the tools and got correct answers from them.
Question:
is it possible that the null value is because SSL connection?
what mistakes could make this null returning?
How can I see the SOAP messeges I send and I get?
Here is My Java Code:
public class WS_TheServeice
{
private static QName qname;
private static URL url;
private static Service service;
private static ImplementationServicePortType sender;
static
{
qname = new QName("http://wservice.com/", "ImplementationService");
try
{
url = new URL("https://to-service?wsdl");
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
service = Service.create(url, qname);
sender = service.getPort(ImplementationServicePortType.class);
}
public static boolean PayToAcceptor(int AcceptorID, int Kipa) throws Exception
{
getUserInfo req = new getUserInfo();
req.zpID = AcceptorID;
req.kipa = Kipa;
getUserInfoResponse user_info = new getUserInfoResponse();//user_info is not NULL here
user_info = sender.getUserInfo(req);//But web server makes it NULL
if (user_info!=null) //// ---- HERE, IT Always return NULL
{
System.out.println("YouWon");
return true;
}
else
{
System.out.println("YouLoose");
return false;
}
}
public static void main(String Args[]) throws Exception
{
PayToAcceptor(12345, 1);
}
}
thanks.

Did you figure out how to do this? I've had similar problems in the past..
Did you try this: SSL Connection for consuming web services ?

Related

Angular 8 socket.io-client 2.2.0 and Java netty-socket.io message not being received?

I am using netty-socket.io and I implemented the server like the demo.
I receive onConnect event both on server and client, but when I sent a message {message: message} I don't get anything on the server event though I see the message being sent in the network tab.
Configuration config = new Configuration();
config.setHostname("localhost");
config.setPort(9092);
final SocketIOServer server = new SocketIOServer(config);
server.addConnectListener(socketIOClient -> System.out.println("Connection test"));
server.addEventListener("messageevent", MessageEventObject.class, new DataListener<MessageEventObject>() {
#Override
public void onData(SocketIOClient socketIOClient, MessageEventObject messageEventObject, AckRequest ackRequest) throws Exception {
System.out.println("message received!");
}
});
server.start();
My MessageEventObject has String message property, constructor getters and setters, looking the same as client-sided.
And this is my websocket service client-sided:
export class WebsocketService {
private socket;
private subject = new Subject < any > ();
constructor() {
console.log('test!');
}
public connect(host: string, port: number) {
this.socket = io(`http://${host}:${port}`, {
'reconnection': false
});
this.socket.on('connect', this.onConnected);
this.socket.on('connect_error', this.onConnectionFailure);
}
public getConnectionStateUpdate(): Observable < any > {
return this.subject.asObservable();
}
public sendMessage(message: string) {
console.log('test');
this.socket.emit('messageevent', {
message: message
});
}
private onConnected = () => {
this.subject.next({
connected: true
});
}
private onConnectionFailure = () => {
this.subject.next({
connected: false
});
}
}
Is there anything that I did wrong?
I would love to answer my own question after tons of debugging and breaking my head, my laziness to use Engine IO with tomcat or jetty, and just wanting to use that awesome netty package which does not require any servlets, I tried to fix it and figure out.
At first I thought it was the client's protocol version, so I used the exact same client as the demo shows on their github page here but that didn't work so the problem is server-sided.
It appears that your object (MessageEventObject) must have a default empty constructor aswell in addition to your other constructors, probably because netty tries to build an empty object and it fails which causes an exception that you don't see.

NullPointerException while connecting to Mqtt on-line broker

I'm trying to connect to the on-line broker https://test.mosquitto.org/ using the code below and the Paho library in Java:
private final String brokerURI = "test.mosquitto.org:1883"; //should be changed to 8883 with SSL
try { //tentativo di creazione del client
client = new MqttClient(brokerURI, idClient); <--NullPointerException here
client.setCallback(new ClientCallback(codaTopic, codaMessaggi, finestra)); //set delle callback
setConnectionOptions(); //set delle opzioni connessione
client.connect(opzioni); //connessione al server
} catch (MqttException e) {
System.err.println(e.getMessage());
System.err.println("Connessione fallita Client, riavviare il sistema.");
}
Connection options are set here:
private void setConnectionOptions() {
opzioni = new MqttConnectOptions();
opzioni.setAutomaticReconnect(true);
opzioni.setCleanSession(false);
opzioni.setConnectionTimeout(30);
opzioni.setKeepAliveInterval(60);
}
but it continues to show a NullPointerException while creating the MqttClient. In particular the console displays:
Exception in thread "Thread-3" java.lang.NullPointerException
at org.eclipse.paho.client.mqttv3.MqttConnectOptions.validateURI(MqttConnectOptions.java:489)
at org.eclipse.paho.client.mqttv3.MqttAsyncClient.<init>(MqttAsyncClient.java:291)
at org.eclipse.paho.client.mqttv3.MqttAsyncClient.<init>(MqttAsyncClient.java:185)
at org.eclipse.paho.client.mqttv3.MqttClient.<init>(MqttClient.java:226)
at org.eclipse.paho.client.mqttv3.MqttClient.<init>(MqttClient.java:138)
at client.Client.run(Client.java:78)
How can i manage to connect and use SSL?
Surfing the net none of the tutorial or guides were useful, I already downloaded the mosquitto.org.crtfile for SSL connection, but i don't know where to use it and I found no tutorials.
EDIT
Changing the BrokerUri to
private final String brokerURI = "tcp://test.mosquitto.org:1883"; //indirizzo broker
the console shows the error
Client non connesso (32104)
at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:31)
at org.eclipse.paho.client.mqttv3.internal.ClientComms.sendNoWait(ClientComms.java:166)
at org.eclipse.paho.client.mqttv3.MqttAsyncClient.subscribe(MqttAsyncClient.java:835)
at org.eclipse.paho.client.mqttv3.MqttClient.subscribe(MqttClient.java:322)
at org.eclipse.paho.client.mqttv3.MqttClient.subscribe(MqttClient.java:315)
at client.Client.subscribe(Client.java:214)
at client.Client.run(Client.java:89)
while trying to subscribe to a Topic with the instruction
client.subscribe(topic, 1);
The topic argument is a String that contains the topic name.
Mosquitto's URI needs the protocol. Taking a look at its source code, this is where your exception is being thrown, class MqttConnectOpts.java :
protected static int validateURI(String srvURI) {
try {
URI vURI = new URI(srvURI);
if (!vURI.getPath().equals("")) {
throw new IllegalArgumentException(srvURI);
}
if (vURI.getScheme().equals("tcp")) {
return URI_TYPE_TCP;
}
else if (vURI.getScheme().equals("ssl")) {
return URI_TYPE_SSL;
}
else if (vURI.getScheme().equals("local")) {
return URI_TYPE_LOCAL;
}
else {
throw new IllegalArgumentException(srvURI);
}
} catch (URISyntaxException ex) {
throw new IllegalArgumentException(srvURI);
}
}
So, it accepts 3 types of protocol prefixes: tcp, ssl, local. Regarding your example, you could try it this way:
TCP
private final String brokerURI = "tcp://test.mosquitto.org:1883";
SSL
private final String brokerURI = "ssl://test.mosquitto.org:8883";

How to capture the server used to fulfill a request when incoming traffic is using Load Balancer URL?

I have a Spring Boot Java REST application with many APIs exposed to our clients and UI. I was tasked with implementing a Transaction logging framework that will capture the incoming transactions along with the response we send.
I have this working with Spring AOP and an Around inspect and I'm currently utilizing the HttpServletRequest and HttpServletResponse objects to obtain a lot of the data I need.
From my local system I am not having any issues capturing the server used since I'm connecting to my system directly. However, once I deployed my code I saw that the load balancer URL was being captured instead of the actual server name.
I am also using Eureka to discover the API by name as it's only a single application running on HAProxy.
Imagine this flow:
/*
UI -> https://my-lb-url/service-sidecar/createUser
HAProxy directs traffic to -> my-lb-url/service-sidecar/ to one of below:
my-server-1:12345
my-server-2:12345
my-server-3:12345
Goal : http://my-server-1:1235/createUser
Actual: https://my-lb-url/createUser
Here is the code I am using to get the incoming URL.
String url = httpRequest.getRequestURL().toString();
if(httpRequest.getQueryString() != null){
transaction.setApi(url + "?" + httpRequest.getQueryString());
} else {
transaction.setApi(url);
}
Note:
I am not as familiar with HAProxy/Eurkea/etc. as I would like to be. If something stated above seems off or wrong then I apologize. Our system admin configured those and locked the developers out.
UPDATE
This is the new code I am using to construct the Request URL, but I am still seeing the output the same.
// Utility Class
public static String constructRequestURL(HttpServletRequest httpRequest) {
StringBuilder url = new StringBuilder(httpRequest.getScheme());
url.append("://").append(httpRequest.getServerName());
int port = httpRequest.getServerPort();
if(port != 80 && port != 443) {
url.append(":").append(port);
}
url.append(httpRequest.getContextPath()).append(httpRequest.getServletPath());
if(httpRequest.getPathInfo() != null) {
url.append(httpRequest.getPathInfo());
}
if(httpRequest.getQueryString() != null) {
url.append("?").append(httpRequest.getQueryString());
}
return url.toString();
}
// Service Class
transaction.setApi(CommonUtil.constructRequestURL(httpRequest));
I found a solution to this issue, but it's not the cleanest route and I would gladly take another suggestion if possible.
I am autowiring the port number from my application.yml.
I am running the "hostname" command on the Linux server that is hosting the application to determine the server fulfilling the request.
Now the URL stored in the Transaction Logs is accurate.
--
#Autowired
private int serverPort;
/*
* ...
*/
private String constructRequestURL(HttpServletRequest httpRequest) {
StringBuilder url = new StringBuilder(httpRequest.getScheme())
.append("://").append(findHostnameFromServer()).append(":").append(serverPort)
.append(httpRequest.getContextPath()).append(httpRequest.getServletPath());
if(httpRequest.getPathInfo() != null) {
url.append(httpRequest.getPathInfo());
}
if(httpRequest.getQueryString() != null) {
url.append("?").append(httpRequest.getQueryString());
}
return url.toString();
}
private String findHostnameFromServer(){
String hostname = null;
LOGGER.info("Attempting to Find Hostname from Server...");
try {
Process process = Runtime.getRuntime().exec(new String[]{"hostname"});
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
hostname = reader.readLine();
}
} catch (IOException e) {
LOGGER.error(CommonUtil.ERROR, e);
}
LOGGER.info("Found Hostname: {}", hostname);
return hostname;
}

When to disconnect bosh connection establish from app server to use prebinding in strophe?

This question is Extension of my previous question on this SO question "How to connect XMPP bosh server using java smack library?"
I am using Java as server side language. I have successfully implement xmpp BOSH connection using smach-jbosh thanks to #Deuteu for helping me to achieve this, so far I have modify jbosh's BOSHClient.java file and added two getter method for extracting RID and SID.
Now I have RID and SID on my app server (I am using Apache Tomcat). I need to pass this credential to Strophe (web client) so that it can attach to connection.
Here I have some doubt.
When to disconnect bosh Connection establish from the app server? before passing sid, rid and jid to strophe or after passing sid, rid and jid to strophe?
As per my observation during implementation for the same, I have observed that once bosh connection from the app server has been disconnected, session is expired and SID and RID is no longer useful!!!
I have implemented this logic (Establishing bosh connection and Extracting sid and rid) on a Servlet, here once response has been send from Servlet, Thread will get expired and end BOSH connection will get terminated, so I am not able perform `Attach()` on strophe as session is expired.
Can somebody help me with that problem?
I believe #fpsColton's answer is correct - I'm just added extra info for clarity. As requested on linked thread here is the code changes I made on this - note: I only added the parts where I've labelled "DH"
In BOSHConnection:
// DH: function to preserve current api
public void login(String username, String password, String resource)
throws XMPPException {
login(username, password, resource, false);
}
// DH: Most of this is existing login function, but added prebind parameter
// to allow leaving function after all required pre-bind steps done and before
// presence stanza gets sent (sent from attach in XMPP client)
public void login(String username, String password, String resource, boolean preBind)
throws XMPPException {
if (!isConnected()) {
throw new IllegalStateException("Not connected to server.");
}
if (authenticated) {
throw new IllegalStateException("Already logged in to server.");
}
// Do partial version of nameprep on the username.
username = username.toLowerCase().trim();
String response;
if (config.isSASLAuthenticationEnabled()
&& saslAuthentication.hasNonAnonymousAuthentication()) {
// Authenticate using SASL
if (password != null) {
response = saslAuthentication.authenticate(username, password, resource);
} else {
response = saslAuthentication.authenticate(username, resource, config.getCallbackHandler());
}
} else {
// Authenticate using Non-SASL
response = new NonSASLAuthentication(this).authenticate(username, password, resource);
}
// Indicate that we're now authenticated.
authenticated = true;
anonymous = false;
// DH: Prebind only requires connect and authenticate
if (preBind) {
return;
}
// Set the user.
if (response != null) {
this.user = response;
// Update the serviceName with the one returned by the server
config.setServiceName(StringUtils.parseServer(response));
} else {
this.user = username + "#" + getServiceName();
if (resource != null) {
this.user += "/" + resource;
}
}
// Create the roster if it is not a reconnection.
if (this.roster == null) {
this.roster = new Roster(this);
}
if (config.isRosterLoadedAtLogin()) {
this.roster.reload();
}
// Set presence to online.
if (config.isSendPresence()) {
sendPacket(new Presence(Presence.Type.available));
}
// Stores the autentication for future reconnection
config.setLoginInfo(username, password, resource);
// If debugging is enabled, change the the debug window title to include
// the
// name we are now logged-in as.l
if (config.isDebuggerEnabled() && debugger != null) {
debugger.userHasLogged(user);
}
}
and
// DH
#Override
public void disconnect() {
client.close();
}
then my Client-side (Web Server) wrapper class - for connecting from within JSP is:
Note: This is proving code rather than production - so there's some stuff in here you may not want.
public class SmackBoshConnector {
private String sessionID = null;
private String authID = null;
private Long requestID = 0L;
private String packetID = null;
private boolean connected = false;
public boolean connect(String userName, String password, String host, int port, final String xmppService) {
boolean success = false;
try {
Enumeration<SaslClientFactory> saslFacts = Sasl.getSaslClientFactories();
if (!saslFacts.hasMoreElements()) {
System.out.println("Sasl Provider not pre-loaded");
int added = Security.addProvider(new com.sun.security.sasl.Provider());
if (added == -1) {
System.out.println("Sasl Provider could not be loaded");
System.exit(added);
}
else {
System.out.println("Sasl Provider added");
}
}
BOSHConfiguration config = new BOSHConfiguration(false, host, port, "/http-bind/", xmppService);
BOSHConnection connection = new BOSHConnection(config);
PacketListener sndListener = new PacketListener() {
#Override
public void processPacket(Packet packet) {
SmackBoshConnector.this.packetID = packet.getPacketID();
System.out.println("Send PacketId["+packetID+"] to["+packet.toXML()+"]");
}
};
PacketListener rcvListener = new PacketListener() {
#Override
public void processPacket(Packet packet) {
SmackBoshConnector.this.packetID = packet.getPacketID();
System.out.println("Rcvd PacketId["+packetID+"] to["+packet.toXML()+"]");
}
};
PacketFilter packetFilter = new PacketFilter() {
#Override
public boolean accept(Packet packet) {
return true;
}
};
connection.addPacketSendingListener(sndListener, packetFilter);
connection.addPacketListener(rcvListener, packetFilter);
connection.connect();
// login with pre-bind only
connection.login(userName, password, "", true);
authID = connection.getConnectionID();
BOSHClient client = connection.getClient();
sessionID = client.getSid();
requestID = client.getRid();
System.out.println("Connected ["+authID+"] sid["+sessionID+"] rid["+requestID+"]");
success = true;
connected = true;
try {
Thread.yield();
Thread.sleep(500);
}
catch (InterruptedException e) {
// Ignore
}
finally {
connection.disconnect();
}
} catch (XMPPException ex) {
Logger.getLogger(SmackBoshConnector.class.getName()).log(Level.SEVERE, null, ex);
}
return success;
}
public boolean isConnected() {
return connected;
}
public String getSessionID() {
return sessionID;
}
public String getAuthID() {
return authID;
}
public String getRequestIDAsString() {
return Long.toString(requestID);
}
public String getNextRequestIDAsString() {
return Long.toString(requestID+1);
}
public static void main(String[] args) {
SmackBoshConnector bc = new SmackBoshConnector();
bc.connect("dazed", "i3ji44mj7k2qt14djct0t5o709", "192.168.2.15", 5280, "my.xmppservice.com");
}
}
I confess that I'm don't fully remember why I put the Thread.yield and Thread.sleep(1/2 sec) in here - I think - as you can see with added PacketListener - the lower level functions return after sending data and before getting a response back from the server - and if you disconnect before the server has sent it's response then it (also) causes it to clean up the session and things won't work. However it may be that, as #fpsColton says, this dicsonnect() isn't actually required.
Edit: I now remember a bit more about whay I included sleep() and yield(). I noticed that Smack library includes sleep() in several places, including XMPPConnection.shutdown() as per source. Plus in terms of yield() I had problems in my environment (Java in Oracle Database - probably untypical) when it wasn't included - as per Smack Forum Thread.
Good luck.
After you have created a BOSH session with smack and have extracted the SID+RID values, you need to pass them to Strophe's attach() and from here on out you need to let strophe deal with this connection. Once Strophe has attached, you do not want your server to be doing anything to the connection at all.
If your server side code sends any messages at all to the connection manager after strophe has attached, it's likely that it will send a invalid RID which will cause your session to terminate.
Again, once the session has been established and is usable by strophe, do not attempt to continue using it from the server side. After your server side bosh client completes authentication and you've passed the SID+RID to the page, just destroy the server side connection object, don't attempt to disconnect or anything as this will end your session.
The thing you need to remember is, unlike traditional XMPP connections over TCP, BOSH clients do NOT maintain a persistent connection to the server (this is why we use BOSH in web applications). So there is nothing to disconnect. The persistent connection is actually between the XMPP server and the BOSH connection manager, it's not something you need to deal with. So when you call disconnect from your server side BOSH client, you're telling the connection manager to end the session and close it's connection to the XMPP server, which completely defeats the purpose of creating the session in the first place.

[Californium/CoAP/LWM2M]: Reusing message send endpoint for server not possible?

I am building a tool that can send CoAP messages to another peer (different implementation), but I am having difficulties. I am using the CoAP library called "Californium" and am developing the tool in java/eclipse. Here's the deal: I send a message over californium's "default endpoint", which allows the system to make up a source-port for the UDP "connection". I want to listen on this same source-port using californium's Server object, but I am getting the following error:
SEVERE: Could not start endpoint
java.net.BindException: Address already in use
So my question is: how do I first send a CoAP message and start listening for other CoAP messages on the same socket using Californium?
Below is the java code for the client. What it does is "register" using a certain protocol layered on top of CoAP. After registering I want it to re-use the UDP socket for listening for subsequent messages of the entity I registered with earlier.
NOTE: The server part of the client works when I explicitly tell it to listen to a certain port (e.g. 5683), leave out the register part and test it with the Firefox Addon "Copper" (i.e. Copper can get to the /1 /1/1 /1/1/0 resources).
package com.example.l2mwm.client;
import java.net.InetSocketAddress;
import ch.ethz.inf.vs.californium.coap.CoAP.Code;
import ch.ethz.inf.vs.californium.coap.CoAP.ResponseCode;
import ch.ethz.inf.vs.californium.coap.CoAP;
import ch.ethz.inf.vs.californium.coap.Request;
import ch.ethz.inf.vs.californium.coap.Response;
import ch.ethz.inf.vs.californium.network.Endpoint;
import ch.ethz.inf.vs.californium.network.EndpointManager;
import ch.ethz.inf.vs.californium.server.Server;
import ch.ethz.inf.vs.californium.server.resources.CoapExchange;
import ch.ethz.inf.vs.californium.server.resources.Resource;
import ch.ethz.inf.vs.californium.server.resources.ResourceBase;
public class Main {
public static void main(String[] args) {
Endpoint endpoint;
if ((endpoint = register()) != null) {
listen(endpoint);
} else {
System.out.println("Couldn't register!");
}
}
private static void listen(Endpoint endpoint) {
InetSocketAddress sockAddress = endpoint.getAddress();
int port = sockAddress.getPort();
Server server = new Server(port);
Resource topResource = new ResourceBase("1") {
#Override
public void handleGET(CoapExchange exchange) {
exchange.respond(ResponseCode.CONTENT, "this is /1's value!");
}
#Override
public String getPath() {
return "/";
}
};
Resource instanceResource = new ResourceBase("1") {
#Override
public void handleGET(CoapExchange exchange) {
exchange.respond(ResponseCode.CONTENT, "this is /1/1's value!");
}
#Override
public String getPath() {
return "/1/";
}
};
topResource.add(instanceResource);
instanceResource.add(new ResourceBase("0") {
#Override
public void handleGET(CoapExchange exchange) {
exchange.respond(ResponseCode.CONTENT, "this is /1/1/0's value!");
}
#Override
public String getPath() {
return "/1/1/";
}
});
server.add(topResource);
server.start();
}
private static Endpoint register() {
Request request = new Request(Code.POST);
request.setURI("localhost:5684/rd?ep=coapclient&lt=86400&b=U");
request.setPayload("</1/1/0>");
Endpoint endpoint = EndpointManager.getEndpointManager().getDefaultEndpoint();
request.send(endpoint);
Response response;
ResponseCode responseCode = null;
try {
response = request.waitForResponse();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
return null;
}
responseCode = response.getCode();
if (responseCode != CoAP.ResponseCode.CREATED) {
return null;
}
return endpoint;
}
}
You need to first bind your UDP socket and then start your LWM2M register.
Because what you do: create CoAP Endpoint (bind a udp server) and than you bind again in your listen method.
// list to the UDP post 5555
coapServer = new Server();
Endpoint endpoint = new CoAPEndpoint(new InetSocketAddress("localhost",5555);
coapServer.addEndpoint(endpoint);
// send a message to a LWM2M server:
request request = new Request(Code.POST);
request.setURI("iot.eclipse.org:5683/rd?ep=coapclient&lt=86400&b=U");
request.setPayload("</1/1/0>");
Endpoint endpoint = EndpointManager.getEndpointManager().getDefaultEndpoint();
request.send(endpoint);
You can still access to your client using copper on coap://localhost:5555

Categories