Connection refused exception when using HttpURLConnection in Play framework - java

I'm using play 2.0.4, I need to connect to an url to see whether it's alive or not to make redirect decision.
public boolean checkServer(String strUrl){
try {
URL url = new URL(strUrl);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.connect();
if(HttpURLConnection.HTTP_OK == urlConn.getResponseCode()){
urlConn.disconnect();
return true;
}else{
urlConn.disconnect();
return false;
}
} catch (IOException e) {
System.err.println("Error creating HTTP connection:" + e.getMessage());
return false;
}
}
In this case, the url that i use is localhost:9001, which is another play application. But then I received this error : Connection refused
Stack trace:
Error creating HTTP connection:Connection refused
java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:378)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:473)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:203)
at sun.net.www.http.HttpClient.New(HttpClient.java:290)
at sun.net.www.http.HttpClient.New(HttpClient.java:306)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:995)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:931)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:849)
at models.Backend.checkServer(Backend.java:19)
at controllers.Application.index(Application.java:22)
at Routes$$anonfun$routes$1$$anonfun$apply$1$$anonfun$apply$2.apply(routes_routing.scala:32)
at Routes$$anonfun$routes$1$$anonfun$apply$1$$anonfun$apply$2.apply(routes_routing.scala:32)
at play.core.Router$HandlerInvoker$$anon$5$$anon$1.invocation(Router.scala:1090)
at play.core.j.JavaAction$$anon$1.call(JavaAction.scala:33)
at play.core.j.JavaAction$class.apply(JavaAction.scala:74)
at play.core.Router$HandlerInvoker$$anon$5$$anon$1.apply(Router.scala:1089)
at play.core.ActionInvoker$$anonfun$receive$1$$anonfun$6.apply(Invoker.scala:126)
at play.core.ActionInvoker$$anonfun$receive$1$$anonfun$6.apply(Invoker.scala:126)
at play.utils.Threads$.withContextClassLoader(Threads.scala:17)
at play.core.ActionInvoker$$anonfun$receive$1.apply(Invoker.scala:125)
at play.core.ActionInvoker$$anonfun$receive$1.apply(Invoker.scala:115)
at akka.actor.Actor$class.apply(Actor.scala:318)
at play.core.ActionInvoker.apply(Invoker.scala:113)
at akka.actor.ActorCell.invoke(ActorCell.scala:626)
at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:197)
at akka.dispatch.Mailbox.run(Mailbox.scala:179)
at akka.dispatch.ForkJoinExecutorConfigurator$MailboxExecutionTask.exec(AbstractDispatcher.scala:516)
at akka.jsr166y.ForkJoinTask.doExec(ForkJoinTask.java:259)
at akka.jsr166y.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:975)
at akka.jsr166y.ForkJoinPool.runWorker(ForkJoinPool.java:1479)
at akka.jsr166y.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:104)
Can somebody please show me what was wrong here?
Thank you very much.

Related

How to detect "Connection refused" when using MqttAsyncClient with no automatic reconnect?

I am using Eclipse Paho Java Client to connect. Here is my extended callback:
protected IMqttAsyncClient mClient;
private final MqttCallbackExtended mCallback = new MqttCallbackExtended() {
#Override
public void connectComplete(boolean reconnect, String brokerAddress) {
Log.d(LOG_TAG, "connectComplete " + brokerAddress);
}
#Override
public void connectionLost(Throwable ex) {
Log.d(LOG_TAG, "connectionLost", ex);
}
#Override
public void deliveryComplete(IMqttDeliveryToken deliveryToken) {
Log.d(LOG_TAG, "deliveryComplete " + deliveryToken);
}
#Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
Log.d(LOG_TAG, "messageArrived " + topic);
}
};
And here the connecting code:
protected void connect() throws MqttException {
Log.d(LOG_TAG, "connect");
MqttConnectOptions connectOptions = new MqttConnectOptions();
connectOptions.setCleanSession(true);
connectOptions.setAutomaticReconnect(false);
connectOptions.setUserName(MQTT_USERNAME);
connectOptions.setPassword(MQTT_PASSWORD.toCharArray());
mClient = new MqttAsyncClient(mBrokerUri, mClientName, new MemoryPersistence());
mClient.setCallback(mCallback);
mClient.connect(connectOptions);
Debug d = ((MqttAsyncClient) mClient).getDebug();
d.dumpClientDebug();
}
I do not use the automatic reconnect feature, but would like to handle reconnecting in my own custom code, since I need custom delays.
For testing purposes I do not start MQTT broker yet and try to connect.
I was hoping to detect the initial connection failure in the connectionLost callback method, but it does not get called.
The MqttException is not thrown either.
When I inspect the paho0.log.0 log file I see the failed connection there -
FINE 17-03-09 07:55:33.0726 al.TCPNetworkModule start 61 ef978a39c826cd6d4ad22f20d5abe6c236eddb060b5d765a1fe2e1d79837fcc8: Failed to create TCP socket
Throwable occurred: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule.start(TCPNetworkModule.java:70)
at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:650)
at java.lang.Thread.run(Thread.java:745)
FINE 17-03-09 07:55:33.0727 nternal.ClientComms connectBG:run 61 ef978a39c826cd6d4ad22f20d5abe6c236eddb060b5d765a1fe2e1d79837fcc8: connect failed: unexpected exception
Throwable occurred: Unable to connect to server (32103) - java.net.ConnectException: Connection refused: connect
at org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule.start(TCPNetworkModule.java:79)
at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:650)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule.start(TCPNetworkModule.java:70)
... 2 more
FINE 17-03-09 07:55:33.0732 nternal.ClientComms shutdownConnection 61 ef978a39c826cd6d4ad22f20d5abe6c236eddb060b5d765a1fe2e1d79837fcc8: state=DISCONNECTING
FINE 17-03-09 07:55:33.0732 ernal.CommsCallback stop 61 ef978a39c826cd6d4ad22f20d5abe6c236eddb060b5d765a1fe2e1d79837fcc8: stopped
FINE 17-03-09 07:55:33.0733 nal.CommsTokenStore quiesce 61 ef978a39c826cd6d4ad22f20d5abe6c236eddb060b5d765a1fe2e1d79837fcc8: resp=Client is currently disconnecting (32102)
But how to detect that connection failure in my code? (So that I could initiate the later reconnection).
UPDATE:
Reported this issue as Bug #336
Currently the only way to detect the initial connect failure of an async client is to pass it one more callback:
private final IMqttActionListener mConnectionCallback = new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d(LOG_TAG, "onSuccess " + asyncActionToken);
// do nothing, this case is handled in mCallback.connectComplete method
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable ex) {
Log.d(LOG_TAG, "onFailure " + asyncActionToken, ex);
// initial connect has failed
}
};
mClient = new MqttAsyncClient(mBrokerUri, mClientName, new MemoryPersistence());
mClient.setCallback(mCallback);
mClient.connect(connectOptions, null, mConnectionCallback);

AbstractXMPPConnection: Connection closed with error: java.net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer)

I am establishing connection with openfire using smack api at client side. able to generate successful connection and can chat.but after chatting some time I am getting the following exception.
AbstractXMPPConnection: Connection closed with error
java.net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer)
at libcore.io.IoBridge.maybeThrowAfterRecvfrom(IoBridge.java:545)
at libcore.io.IoBridge.recvfrom(IoBridge.java:509)
at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
at crittercism.android.m.read(Unknown Source)
at java.io.InputStreamReader.read(InputStreamReader.java:233)
at java.io.BufferedReader.read(BufferedReader.java:325)
at org.kxml2.io.KXmlParser.fillBuffer(KXmlParser.java:1506)
at org.kxml2.io.KXmlParser.peekType(KXmlParser.java:986)
at org.kxml2.io.KXmlParser.next(KXmlParser.java:346)
at org.kxml2.io.KXmlParser.next(KXmlParser.java:310)
at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.parsePackets(XMPPTCPConnection.java:1151)
at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.access$200(XMPPTCPConnection.java:937)
at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader$1.run(XMPPTCPConnection.java:952)
at java.lang.Thread.run(Thread.java:841)
Caused by: libcore.io.ErrnoException: recvfrom failed: ECONNRESET (Connection reset by peer)
at libcore.io.Posix.recvfromBytes(Native Method)
at libcore.io.Posix.recvfrom(Posix.java:141)
at libcore.io.BlockGuardOs.recvfrom(BlockGua
Gone through couple answers to the related posts but did not find the actual reason for this exception in my scenario. I am using the below code for establishing connection with openfire :
try { XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword(userName+Constants.openFireIP, password)
.setServiceName("182.**.***.**")
.setHost("182.**.***.**")
.setPort(5222)
.setResource("/Smack")
.build();
connecton = new XMPPTCPConnection(config);
System.out.println("connecton ######## "+connecton);
makeConnectionAvailable();
}
catch(Exception e){
System.out.println("Exception "+e.getMessage());
e.printStackTrace();
}
public void makeConnectionAvailable(){
try{
if(!connecton.isConnected()){
connecton.connect();
connecton.login();
connecton.addConnectionListener(connectionListener);
}else if(!connecton.isAuthenticated()){
connecton.login();
}
}
catch (Exception e){
e.printStackTrace();
}
}
Because of this connection becomes terminated and loosing incoming chat messages till i made connection again. let me know if anybody resolve this kind of problem.

How to check if MongoDB connection is established with Java?

In my app, MongoDB 3.2.4 runs on a custom port, I want to implement logic where my app will try to reach MongoDB on a custom port and if it fails it will use the default 27018 port.
In order to do that I use the following code:
String mongoClientURI = "mongodb://" + DB_SRV_USR + ":" + DB_SRV_PWD + "#" + DB_URL + ":" + DB_PORT_CUS + "/" + dbName;
MongoClientURI connectionString = new MongoClientURI(mongoClientURI);
// enable SSL connection
MongoClientOptions.builder().sslEnabled(true).build();
if (this.mongoClient == null) {
this.mongoClient = new MongoClient(connectionString);
}
// create database if doesn't exist
MongoDatabase mdb = this.mongoClient.getDatabase(dbName);
try {
this.mongoClient.getAddress();
} catch (com.mongodb.MongoSocketOpenException e) {
System.out.println("Switch to default port");
/*…use default port logic…*/
}
The problem is that this exception is not caught.
Although MongoDB throws the following exception:
com.mongodb.MongoSocketOpenException: Exception opening socket at
com.mongodb.connection.SocketStream.open(SocketStream.java:63) at
com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:114)
at
com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:128)
at java.lang.Thread.run(Thread.java:745) Caused by:
java.net.ConnectException: Connection refused: connect at
java.net.DualStackPlainSocketImpl.waitForConnect(Native Method) at
java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
at
java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at
java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at
java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) at
java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at
java.net.Socket.connect(Socket.java:589) at
com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:50)
at com.mongodb.connection.SocketStream.open(SocketStream.java:58)
... 3 more
my try-catch expression can't catch this exception.
I tried multiple approaches, such as to catch:
Exception
RuntimeException
MongoSocketOpenException
MongoException
MongoCommandException
none of them doesn't work.
My questions:
How can I check if MongoDB connection is established?
How can catch the exception MongoSocketOpenException?
I use this code to check connection:
try {
mongo.getAddress();
} catch (Exception e) {
System.out.println("Database unavailable!");
mongo.close();
return;
}
Not sure here my guess would be that this.mongoClient.getAddress(); does not throw that exception, but I don't really know
EDIT: I initialized it via:
Builder builder = MongoClientOptions.builder().connectTimeout(3000);
MongoClient mongo = new MongoClient(new ServerAddress("192.168.0.1", 3000), builder.build());

.getResponse Code Throwing IOException on a Valid URL

I'm building a webcrawler and have a method to check for bad link. At one point I am trying to get the HTTP response code to determine if it is valid or not. despite handing it a valid URL (opened it in a browser just fine) it still returns that it isn't valid. Here is the code:
public static boolean isBrokenLink(URL baseURL, String theHREF) {
boolean isBroken = false;
if (baseURL == null) {
try {
baseURL = new URL("HTTP", "cs.uwec.edu/~stevende/cs145testpages/", theHREF);
System.out.println(baseURL);
} catch (MalformedURLException e) {
isBroken = true;
//e.printStackTrace();
}
}
try {
URLConnection con = baseURL.openConnection();
HttpURLConnection httpProtocol = (HttpURLConnection) con;
System.out.println(httpProtocol.getResponseCode());
if (httpProtocol.getResponseCode() != 200 && httpProtocol.getResponseCode() == -1) {
isBroken = true;
}
} catch (IOException e) {
isBroken = true;
e.printStackTrace();
}
return isBroken;
}
}
And here is the URL I'm passing it. isBroken is the boolean that is being returned. I passing baseURL as null and theHREF as a relative link (page2.htm). I'm printing out the URL after creating it from the string. Thanks for any help!
Here is the error:
java.net.UnknownHostException: cs.uwec.edu/~stevende/cs145testpages/
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:432)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:527)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:211)
at sun.net.www.http.HttpClient.New(HttpClient.java:308)
at sun.net.www.http.HttpClient.New(HttpClient.java:326)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:996)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:932)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:850)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1300)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:468)
at edu.uwec.cs.carpenne.webcrawler.Webcrawler.isBrokenLink(Webcrawler.java:106)
at edu.uwec.cs.carpenne.webcrawler.Webcrawler.main(Webcrawler.java:181)
The exception tells us, that it is using the hostname and the local part as the (unknown) host. This looks like you have constructing the URL incorrectly. Maybe you forgot to use http:// prefix or used the wrong getters? You can debug it by calling baseURL.getHost(), baseURL.getPath() and baseURL.getProtocol() to see if it returns cs.uwec.edu and /~steve... and http.
I just noticed you added the baseURL with new URL("HTTP", "cs.uwec.edu/~stevende/cs145testpages/", theHREF) this is wrong, you need to use new URL("http", "cs.uwec.edu", 80, "/~stevende/cs145testpages/#"+theHREF). You can however typically skip the anchor/ref, as it will not transmitted to the server.
You can also use the single argument constructor new URL("http://cs.uwec.edu//~stevende/cs145testpages/").

Pelops - Catch Connection Error?

Is there a way to catch a connection error when using pelops in Java? I have the following code but for some reason, I'm not getting to my catch block.
public static Boolean testDBConnection() throws PelopsException {
try{
Cluster cluster = new Cluster("127.0.0.1", 9160);
Pelops.addPool(pool, cluster, keyspace);
Pelops.shutdown();
return true;
}
catch(PelopsException e)
{
System.out.println("SOMETHING WENT WRONG!");
System.out.println(e.getMessage());
return false;
}
}
This is probably something really easy, but I can't seem to get it to work. I see the exceptions coming through, but there is just no way I can catch this? Could someone please lead me in the right direction?
Thanks!
EDIT - Exception being returned in Eclipse Console...
15:47:33.545 [main] DEBUG o.s.c.pelops.pool.CommonsBackedPool - Made new connection 'Connection[Testing][127.0.0.1:9160][724408050]'
15:47:34.545 [main] ERROR o.scale7.cassandra.pelops.Connection - Failed to open transport. See cause for details...
org.apache.thrift.transport.TTransportException: java.net.ConnectException: Connection refused: connect
at org.apache.thrift.transport.TSocket.open(TSocket.java:185) ~[libthrift-0.5.0.jar:na]
at org.apache.thrift.transport.TFramedTransport.open(TFramedTransport.java:81) ~[libthrift-0.5.0.jar:na]
at org.scale7.cassandra.pelops.Connection.open(Connection.java:70) ~[scale7-pelops-0.913.jar:na]
at org.scale7.cassandra.pelops.pool.CommonsBackedPool$ConnectionFactory.makeObject(CommonsBackedPool.java:785) [scale7-pelops-0.913.jar:na]
at org.apache.commons.pool.impl.GenericKeyedObjectPool.addObject(GenericKeyedObjectPool.java:1685) [commons-pool-1.5.5.jar:1.5.5]
at org.apache.commons.pool.impl.GenericKeyedObjectPool.ensureMinIdle(GenericKeyedObjectPool.java:2058) [commons-pool-1.5.5.jar:1.5.5]
at org.apache.commons.pool.impl.GenericKeyedObjectPool.preparePool(GenericKeyedObjectPool.java:1722) [commons-pool-1.5.5.jar:1.5.5]
at org.scale7.cassandra.pelops.pool.CommonsBackedPool.addNode(CommonsBackedPool.java:373) [scale7-pelops-0.913.jar:na]
at org.scale7.cassandra.pelops.pool.CommonsBackedPool.<init>(CommonsBackedPool.java:104) [scale7-pelops-0.913.jar:na]
at org.scale7.cassandra.pelops.pool.CommonsBackedPool.<init>(CommonsBackedPool.java:64) [scale7-pelops-0.913.jar:na]
at org.scale7.cassandra.pelops.pool.CommonsBackedPool.<init>(CommonsBackedPool.java:52) [scale7-pelops-0.913.jar:na]
at org.scale7.cassandra.pelops.Pelops.addPool(Pelops.java:25) [scale7-pelops-0.913.jar:na]
at libraries.cassandra.testDBConnection(cassandra.java:192) [classes/:na]
at libraries.cassandra.main(cassandra.java:38) [classes/:na]
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:1.6.0_25]
at java.net.PlainSocketImpl.doConnect(Unknown Source) ~[na:1.6.0_25]
at java.net.PlainSocketImpl.connectToAddress(Unknown Source) ~[na:1.6.0_25]
at java.net.PlainSocketImpl.connect(Unknown Source) ~[na:1.6.0_25]
at java.net.SocksSocketImpl.connect(Unknown Source) ~[na:1.6.0_25]
at java.net.Socket.connect(Unknown Source) ~[na:1.6.0_25]
at org.apache.thrift.transport.TSocket.open(TSocket.java:180) ~[libthrift-0.5.0.jar:na]
... 13 common frames omitted
The exception being thrown org.apache.thrift.TTransportException is a checked exception that is not caught and wrapped by PelopsException which extends RuntimeException.
If you want your method to always return a PelopsException, you must catch(Exception e) and then throw new PelopsException(e.getMessage()) inside your catch block.
catch(Exception e)
{
System.out.println("SOMETHING WENT WRONG!");
System.out.println(e.getMessage());
throw new PelopsException(e.getMessage());
}
It may be throwing an unchecked exception or an Error (which is not an Exception).
Try changing your code to catch (Throwable e) and see what you get.

Categories