How to check if MongoDB connection is established with Java? - 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());

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);

Java-TCL (tclblend) JDBC connection authentication error when used in different java Processes

I am trying to run several processes that connect to a DB, perform some operation and then finishes it.
My code looks like this
Java calls the script using Process
Runtime r = Runtime.getRuntime();
Process p = r.exec(expectPath+" "+expectScriptPath+" "+ticket);
SessionLogger sysout = new SessionLogger(logger,p.getInputStream());
sysout.start();
SessionLogger syserr = new SessionLogger(logger,p.getErrorStream());
syserr.start();
try {
return p.waitFor();
} catch (InterruptedException e) {
log.error(e.getMessage(),e);
return -1;
}
TCL script calls a java method
set inputData [ java::call myPackage.TCLDriverWrapper pullNextInputData $ticket ]
Java code creates a jdbc connection, performs a simple query and closes the connection
private static LegacyDriverTaskInputData pullNextInputData(String token) throws Exception {
Connection conn = null;
try{
conn = new TCLDriverWrapper().getConnection();
QueryRunner run = new QueryRunner();
ResultSetHandler<LegacyDriverTaskInputData> rsh = new BeanHandler<LegacyDriverTaskInputData>(LegacyDriverTaskInputData.class);
LegacyDriverTaskInputData inputData = run.query(conn,"select * from mytable where id = ?",rsh,Long.valueOf(token));
return inputData;
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw e;
} catch (SQLException e) {
e.printStackTrace();
throw e;
} finally {
DbUtils.close(conn);
}
}
where
private Connection getConnection() throws Exception{
String driver = "...";
if (driver == null || driver.trim().length()==0) {
throw new Exception("...");
}
Class.forName(driver);
Properties props = new Properties();
props.put("user", MyConfiguration.getProperty("javawrapper.user"));
props.put("password", MyConfiguration.getProperty("javawrapper.password"));
return DriverManager.getConnection(MyConfiguration.getProperty("javawrapper.jdbc"), props);
}
One thing I've noticed is that when I trigger just one Process at a time, everything works fine.
But if I try to run 3 Processes at the same time (each one in its own thread) I get an error like this
Processing java.sql.SQLRecoverableException: IO Error: Connection reset
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:498)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:553)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:254)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:528)
at java.sql.DriverManager.getConnection(DriverManager.java:620)
at java.sql.DriverManager.getConnection(DriverManager.java:169)
at (...)
Caused by: java.net.SocketException: Connection reset
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:113)
at java.net.SocketOutputStream.write(SocketOutputStream.java:153)
at oracle.net.ns.DataPacket.send(DataPacket.java:210)
at oracle.net.ns.NetOutputStream.flush(NetOutputStream.java:230)
at oracle.net.ns.NetInputStream.getNextPacket(NetInputStream.java:321)
at oracle.net.ns.NetInputStream.read(NetInputStream.java:268)
at oracle.net.ns.NetInputStream.read(NetInputStream.java:190)
at oracle.net.ns.NetInputStream.read(NetInputStream.java:107)
at oracle.jdbc.driver.T4CSocketInputStreamWrapper.readNextPacket(T4CSocketInputStreamWrapper.java:124)
at oracle.jdbc.driver.T4CSocketInputStreamWrapper.read(T4CSocketInputStreamWrapper.java:80)
at oracle.jdbc.driver.T4CMAREngine.unmarshalUB1(T4CMAREngine.java:1137)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:350)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227)
at oracle.jdbc.driver.T4CTTIoauthenticate.doOSESSKEY(T4CTTIoauthenticate.java:407)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:416)
... 19 more
java.sql.SQLRecoverableException: IO Error: Connection reset
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:498)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:553)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:254)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:528)
at java.sql.DriverManager.getConnection(DriverManager.java:620)
at java.sql.DriverManager.getConnection(DriverManager.java:169)
(...)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at tcl.lang.reflect.PkgInvoker.invokeMethod(PkgInvoker.java:128)
at tcl.lang.JavaInvoke.call(JavaInvoke.java:304)
at tcl.lang.JavaInvoke.callStaticMethod(JavaInvoke.java:217)
at tcl.lang.JavaCallCmd.cmdProc(JavaCallCmd.java:74)
at tcl.lang.AutoloadStub.cmdProc(Extension.java:119)
at tcl.lang.Interp.callCommand(Interp.java:1266)
Caused by: java.net.SocketException: Connection reset
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:113)
at java.net.SocketOutputStream.write(SocketOutputStream.java:153)
at oracle.net.ns.DataPacket.send(DataPacket.java:210)
at oracle.net.ns.NetOutputStream.flush(NetOutputStream.java:230)
at oracle.net.ns.NetInputStream.getNextPacket(NetInputStream.java:321)
at oracle.net.ns.NetInputStream.read(NetInputStream.java:268)
at oracle.net.ns.NetInputStream.read(NetInputStream.java:190)
at oracle.net.ns.NetInputStream.read(NetInputStream.java:107)
at oracle.jdbc.driver.T4CSocketInputStreamWrapper.readNextPacket(T4CSocketInputStreamWrapper.java:124)
at oracle.jdbc.driver.T4CSocketInputStreamWrapper.read(T4CSocketInputStreamWrapper.java:80)
at oracle.jdbc.driver.T4CMAREngine.unmarshalUB1(T4CMAREngine.java:1137)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:350)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227)
at oracle.jdbc.driver.T4CTTIoauthenticate.doOSESSKEY(T4CTTIoauthenticate.java:407)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:416)
... 19 more
java.sql.SQLRecoverableException: IO Error: Connection reset
It seems to me that something is not de-allocating some object properly, but I am not sure if it's on the java side, or if it's in the TCL side. Also, I don't know if TCL shares objects for different processes (does not make sense to me).
Any clue is welcome.
Code runs in Linux.

Amazon SQS Queue Does Not Exist

I am trying to access an amazon queue using java sdk. The queue is set in an environment with EC2 instance roles so I do not need to use credentials to access it.
Here is my code
public AWSSimpleQueueServiceClient(String queueName, String endPoint) {
try{
this.queueName = queueName;
logger.debug("Queue Name = " + this.queueName + "Endpoint = " + endPoint);
this.sqs = new AmazonSQSClient(new InstanceProfileCredentialsProvider());
if(endPoint != null) {
this.sqs.setEndpoint(endPoint);
}
} catch (Exception e) {
logger.error("Exception while creating AWS SQS Client = " + e.getMessage());
}
}
QueueName and Endpoint are got from configuration files.
I try to send/receive messages from the queue but it gives me the following exception
Exception in thread "main" com.amazonaws.services.sqs.model.QueueDoesNotExistException: The specified queue does not exist or you do not have access to it. (Service: AmazonSQS; Status Code: 400; Error Code: AWS.SimpleQueueService.NonExistentQueue; Request ID: c30b2c9a-0e62-560d-9306-628ebff676d8)
at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:1160)
at com.amazonaws.http.AmazonHttpClient.executeOneRequest(AmazonHttpClient.java:748)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:467)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:302)
at com.amazonaws.services.sqs.AmazonSQSClient.invoke(AmazonSQSClient.java:2422)
at com.amazonaws.services.sqs.AmazonSQSClient.getQueueUrl(AmazonSQSClient.java:541)
at com.ensighten.inform.sqsClient.AWSSimpleQueueServiceClient.getQueueUrl(AWSSimpleQueueServiceClient.java:66)
However, when I try to access the queue using the curl command, I get a response
aws sqs receive-message --queue-url <Endpoint>/031143137427/<QueueName> -- region us-east-1
{
"Messages": [
{
"Body": "Test",
"ReceiptHandle": "AQEBA49LjMDLPyyl4QKwHx9/oVFDV7mZDiOOpdKS/IC2zR3GNblg2IoHuqWBgr5iw7URCkL03Dm23TCs0Z2hB2DIzU+9qxZTOa9Ti57eiHOyAL2XAlbk7TAqGCR4lcsdSW8+LJ5zWCTkBUg5iZOqy4P0KFTfI7KtJJb2aAmeWJpApu+yJRTNAkYtdN91EcYOVFHqc1p6HJmtvvW6vJwfHB5JEbagXdfWwH3/UnJ/O36JwuFoLDp/NBRu6TO+bmYxeZmCN4GdhHuT0a11weki6Ez47Ln63G11LeQ4SFdZTC7QOWflypf8FSbG8W4JGGPZ8J8iWTkW7PGGw6DRavSu97rx3w==",
"MD5OfBody": "1f871ceacd9f4028ed371e91400efe80",
"MessageId": "0f6290d2-4554-4d96-8f93-7564ef667feb"
}
]
}
This is an exception that I get when I try it on another machine setup with EC2 roles.
Exception in thread "main" com.amazonaws.AmazonClientException: Unable to load credentials from Amazon EC2 metadata service
at com.amazonaws.auth.InstanceProfileCredentialsProvider.handleError(InstanceProfileCredentialsProvider.java:244)
at com.amazonaws.auth.InstanceProfileCredentialsProvider.loadCredentials(InstanceProfileCredentialsProvider.java:225)
at com.amazonaws.auth.InstanceProfileCredentialsProvider.getCredentials(InstanceProfileCredentialsProvider.java:124)
at com.amazonaws.services.sqs.AmazonSQSClient.invoke(AmazonSQSClient.java:2413)
at com.amazonaws.services.sqs.AmazonSQSClient.getQueueUrl(AmazonSQSClient.java:541)
at com.ensighten.inform.sqsClient.AWSSimpleQueueServiceClient.getQueueUrl(AWSSimpleQueueServiceClient.java:74)
at com.ensighten.inform.sqsClient.AWSSimpleQueueServiceClient.getMessagesFromQueue(AWSSimpleQueueServiceClient.java:93)
at com.ensighten.inform.jobRunner.TestJobRunner.execute(TestJobRunner.java:96)
at com.ensighten.inform.jobRunner.TestJobRunner.main(TestJobRunner.java:90)
Caused by: java.net.SocketTimeoutException: connect timed out
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:392)
at java.net.Socket.connect(Socket.java:579)
at sun.net.NetworkClient.doConnect(NetworkClient.java:175)
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 com.amazonaws.internal.EC2MetadataClient.readResource(EC2MetadataClient.java:90)
at com.amazonaws.internal.EC2MetadataClient.getDefaultCredentials(EC2MetadataClient.java:55)
at com.amazonaws.auth.InstanceProfileCredentialsProvider.loadCredentials(InstanceProfileCredentialsProvider.java:186)
... 7 more
This is how I get the URL of the queue. Tried doing it two ways below. It errors out with the above exception
public String getQueueUrl() {
GetQueueUrlRequest queueUrlRequest = new GetQueueUrlRequest(this.queueName);
logger.debug("Queue Name... = " + this.queueName);
//FIRST WAY -----------> EXCEPTION on the line below
System.out.println("Queue URL .....= " + this.sqs.getQueueUrl(this.queueName));
//SECOND WAY
return this.sqs.getQueueUrl(queueUrlRequest).getQueueUrl();
}
I have been trying to figure this out for a while now. Any help is appreciated.

java.rmi.ConnectException: Connection refused to host: 192.168.0.55

I am quite a beginner with NetBeans and Java, so I'm pretty sure my questions are very basic but trying to find the solution for 2 weeks I am totally stuck
This is the problem:
I want to implement a RMI Server Client application
So first step was trying with NetBeans to have one work from the net
I used the oracle tutorial to have the first part implemented
http://docs.oracle.com/javase/tutorial/rmi/server.html
My problem is not that the client does not connect, but that the server can't even register in the port I give him. The IP in the error message is my private IP.
This is the error message I get:
Conectando a: 127.0.0.1 / 19400 / PlanificadorTalsa
ServidorPlanificadorStarter exception:
java.rmi.ConnectException: Connection refused to host: 192.168.0.55; nested exception is:
java.net.ConnectException: Connection refused: connect
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619)
at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:342)
at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source)
at Starter.ServidorPlanificadorStarter.main(ServidorPlanificadorStarter.java:52)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:345)
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 java.net.Socket.connect(Socket.java:538)
at java.net.Socket.<init>(Socket.java:434)
at java.net.Socket.<init>(Socket.java:211)
at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40)
at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:148)
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613)
... 5 more
I am running windows 8.1, and disabled firewall. I am also using a security file granting all permissions
this is my java code I execute from NetBeans:
import Conexion.DatosConexion;
import Servidor.*;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class ServidorPlanificadorStarter implements InterfazServidorPlanificador {
private static String ip;
private static String Servidor = "SERVIDORNUBE";
private static int puerto;
private static String nombreServidor;
public ServidorPlanificadorStarter(){
super();
}
public static void main(String[] args) {
if (System.getSecurityManager() == null) {
System.setSecurityManager(new SecurityManager());
}
try {
DatosConexion datos = DatosConexion.getInstance();
ip = datos.getServiceIP(Servidor);
puerto = Integer.valueOf(datos.getServicePort(Servidor));
nombreServidor = datos.getServiceName(Servidor);
System.setProperty("java.rmi.server.hostname", ip);
System.out.println("Conectando a: " + ip + " / " + puerto + " / " + nombreServidor);
InterfazServidorPlanificador engine = new ServidorPlanificadorStarter();
InterfazServidorPlanificador stub =
(InterfazServidorPlanificador) UnicastRemoteObject.exportObject(engine, puerto);
Registry registry = LocateRegistry.getRegistry();
registry.rebind(nombreServidor, stub);
System.out.println("ServidorPlanificador bound");
} catch (Exception e) {
System.err.println("ServidorPlanificadorStarter exception:");
e.printStackTrace();
}
}
}
The interface is as follows (very basic, as I have done nothing with it)
public interface InterfazServidorPlanificador extends Remote {
//void addObserver(RemoteObserver o) throws RemoteException;
}
Did you start RMI registry as in tutorial?
http://docs.oracle.com/javase/tutorial/rmi/running.html

Connection refused exception when using HttpURLConnection in Play framework

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.

Categories