java.net.SocketTimeoutException: connect timed out when connecting to postgresql using jdbc - postgresql

We are planning to switch DB from Oracle to PostgreSQL. After creating tables, I am about to load actual data into PostgreSQL tables. In order to do it, I connect to db using JDBC. It gives me error like below.
Connection Failed! Check output console
org.postgresql.util.PSQLException: The connection attempt failed.
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:275)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:194)
at org.postgresql.Driver.makeConnection(Driver.java:450)
at org.postgresql.Driver.connect(Driver.java:252)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at JDBCExample.main(JDBCExample.java:31)
Caused by: java.net.SocketTimeoutException: connect timed out
at java.net.PlainSocketImpl.socketConnect(Native Method)
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.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at org.postgresql.core.PGStream.<init>(PGStream.java:68)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:144)
... 7 more
At first I thought that data loading may take time and could cause this kind of problem, but I tested with following JDBC connection java. It still returns same error like above.
public class JDBCExample {
public static void main(String[] argv) {
System.out.println("-------- PostgreSQL "
+ "JDBC Connection Testing ------------");
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your PostgreSQL JDBC Driver? "
+ "Include in your library path!");
e.printStackTrace();
return;
}
System.out.println("PostgreSQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:postgresql://aaa.bbb.ccc.ddd:5432/test", "tom",
"secret");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
catch (Exception e) {
e.printStackTrace();
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
}
}
In this case, what should I check first? There is some log file recording these errors in Postgresql? Is this something related with firewall? I even do not know our coporate has firewall? Could you give some guidance for this issue?

Related

How to catch SOAP request message in CXF with WSS4JOutInterceptor when connection fails

I can catch SOAP request message according to
this SO answer.
However if the server is unavailable I get the following exception from SAAJOutInterceptor (added by WSS4JOutInterceptor) and LoggingCallback is not invoked hence message is not caugth:
org.apache.cxf.binding.soap.SoapFault: Connection refused: connect
at org.apache.cxf.binding.soap.saaj.SAAJOutInterceptor$SAAJOutEndingInterceptor.handleMessage(SAAJOutInterceptor.java:221)
at org.apache.cxf.binding.soap.saaj.SAAJOutInterceptor$SAAJOutEndingInterceptor.handleMessage(SAAJOutInterceptor.java:174)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:531)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:440)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:355)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:313)
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:96)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:140)
...
Caused by: com.ctc.wstx.exc.WstxIOException: Connection refused: connect
at com.ctc.wstx.sw.BaseStreamWriter.flush(BaseStreamWriter.java:262)
at org.apache.cxf.binding.soap.saaj.SAAJOutInterceptor$SAAJOutEndingInterceptor.handleMessage(SAAJOutInterceptor.java:215)
...
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 sun.net.NetworkClient.doConnect(NetworkClient.java:175)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:463)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:558)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:242)
at sun.net.www.http.HttpClient.New(HttpClient.java:339)
at sun.net.www.http.HttpClient.New(HttpClient.java:357)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1220)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1199)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1050)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:984)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1334)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1309)
at org.apache.cxf.transport.http.URLConnectionHTTPConduit$URLConnectionWrappedOutputStream.setupWrappedStream(URLConnectionHTTPConduit.java:274)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleHeadersTrustCaching(HTTPConduit.java:1345)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.onFirstWrite(HTTPConduit.java:1306)
at org.apache.cxf.transport.http.URLConnectionHTTPConduit$URLConnectionWrappedOutputStream.onFirstWrite(URLConnectionHTTPConduit.java:307)
at org.apache.cxf.io.AbstractWrappedOutputStream.write(AbstractWrappedOutputStream.java:47)
at org.apache.cxf.io.AbstractThresholdOutputStream.unBuffer(AbstractThresholdOutputStream.java:89)
at org.apache.cxf.io.AbstractThresholdOutputStream.write(AbstractThresholdOutputStream.java:63)
at org.apache.cxf.io.CacheAndWriteOutputStream.write(CacheAndWriteOutputStream.java:80)
at org.apache.cxf.io.CacheAndWriteOutputStream.write(CacheAndWriteOutputStream.java:80)
at org.apache.cxf.io.AbstractWrappedOutputStream.write(AbstractWrappedOutputStream.java:51)
at com.ctc.wstx.io.UTF8Writer.flush(UTF8Writer.java:100)
at com.ctc.wstx.sw.BufferingXmlWriter.flush(BufferingXmlWriter.java:242)
at com.ctc.wstx.sw.BaseStreamWriter.flush(BaseStreamWriter.java:260)
...
I need to save request SOAP message with all the security stuff added by WSS4JOutInterceptor (certificate, signature ...) regardless of whether the message was successfully send or whether the server is even up.
The thing is that you must first write to the output stream where you catch the message and write to network connection only in onClose callback:
class RequestInterceptor extends AbstractPhaseInterceptor<Message> {
OutputStream outputStream
OutputStream originalOutputStream
public RequestInterceptor() {
super(Phase.PRE_STREAM);
}
#Override
public void handleMessage(Message message) throws Fault {
originalOutputStream = message.getContent(OutputStream.class)
CacheAndWriteOutputStream newOutputStream = new CacheAndWriteOutputStream(outputStream)
message.setContent(OutputStream.class, newOutputStream)
newOutputStream.registerCallback(new CachedOutputStreamCallback() {
void onFlush(CachedOutputStream cos) {
}
void onClose(CachedOutputStream cos) {
cos.writeCacheTo(originalOutputStream)
originalOutputStream.close()
}
})
}
}

Mongo db authentication failure in java code does not go to catch block

I am trying to write code where mongo DB authentication is tested.
However when authentication fails the code does not reach to the catch block.
Here is the code :
MongoClient client = null;
try {
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(
MongoCredential.createScramSha1Credential(
"abc",
"test",
"abc#123".toCharArray()
)
);
client = new MongoClient(host,credentials, MongoClientOptions
.builder().connectionsPerHost(20)
.threadsAllowedToBlockForConnectionMultiplier(15)
.connectTimeout(5000)
.writeConcern(WriteConcern.ACKNOWLEDGED).build());
} catch (Exception e) {
client = new MongoClient(host, MongoClientOptions
.builder().connectionsPerHost(20)
.threadsAllowedToBlockForConnectionMultiplier(15)
.connectTimeout(5000)
.writeConcern(WriteConcern.ACKNOWLEDGED).build());
// e.printStackTrace();
}
client.getDatabase("admin").runCommand(new Document("ping",1));
com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='abc', source='test', password=<hidden>, mechanismProperties={}}
at com.mongodb.connection.SaslAuthenticator.authenticate(SaslAuthenticator.java:61)
at com.mongodb.connection.InternalStreamConnectionInitializer.authenticateAll(InternalStreamConnectionInitializer.java:99)
at com.mongodb.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:44)
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:128)
at java.lang.Thread.run(Unknown Source)
This code never falls through into the catch block and runs the line just after the catch block.
Can you tell me how to handle this situation.

mongoDB async driver java - unable to connect with authentication

Recently we've updated our mongoDB with port 35489 and also with authentication and roles to the database.
I've granted readWrite and readWriteAnyDatabase roles for a user and can successfully connect from our c# coding from mentioning it from the web.config
My web.config:
<add key="MongoConnectionString" value="mongodb://readWriteUser:********#192.168.1.225:35489/admin" />
Now, my problem is I'm uanble to connect to mongoDB from java async driver and it is throwing an exception like
Exception
Exception in monitor thread while connecting to server localhost:35489 com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=null, userName='AdminAllDatabases', source='admin', password=, mechanismProperties={}} at com.mongodb.connection.SaslAuthenticator.authenticate(SaslAuthenticator.java:61) at com.mongodb.connection.DefaultAuthenticator.authenticate(DefaultAuthenticator.java:32) at com.mongodb.connection.InternalStreamConnectionInitializer.authenticateAll(InternalStreamConnectionInitializer.java:99) at com.mongodb.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:44) at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115) at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:127) at java.lang.Thread.run(Unknown Source) Caused by: com.mongodb.MongoCommandException: Command failed with error 18: 'Authentication failed.' on server localhost:35489. The full response is { "ok" : 0.0, "code" : 18, "errmsg" : "Authentication failed." } at com.mongodb.connection.CommandHelper.createCommandFailureException(CommandHelper.java:170) at com.mongodb.connection.CommandHelper.receiveCommandResult(CommandHelper.java:123) at com.mongodb.connection.CommandHelper.executeCommand(CommandHelper.java:32) at com.mongodb.connection.SaslAuthenticator.sendSaslContinue(SaslAuthenticator.java:99) at com.mongodb.connection.SaslAuthenticator.authenticate(SaslAuthenticator.java:58) ... 6 common frames omitted
My async java driver code:
public static final String DEFAULT_URI = "mongodb://readWriteUser:******#localhost:35489/";
public static synchronized ConnectionString getConnectionString()
{
if (connectionString == null)
{
connectionString = new ConnectionString(DEFAULT_URI);
}
return connectionString;
}
public static synchronized MongoClient getMongoClient()
{
if (mongoClient == null)
{
mongoClient = MongoClients.create(getConnectionString());
}
return mongoClient;
}
we've tried with both localhost and ip address, but nothing seems to work.
Can anyone suggest me the right way to do this?

smack api giving error to login gtalk

I used all the api's related to smack so that i could login and use the gtalk in my and app. All the api's (smack 3.22, asmack, qsmack) give me same error. Error is coppied from logcat and pasted below. Please help me i am almost frustated now :(
XMPPConnection xmppConnection;
String host = "talk.google.com";
int port = 6222;
String service = "gmail.com";
String username = "test1";
String password = "password";
try {
xmppConnection = new XMPPConnection(new ConnectionConfiguration(host,
port, service));
xmppConnection.connect();
xmppConnection.login(username, password);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
No response from the server.:
at org.jivesoftware.smack.NonSASLAuthentication.authenticate(NonSASLAuthentication.java:74)
at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:404)
at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:349)
at com.android.xmppproject.XmppManager.performLogin(XmppManager.java:56)
at com.android.xmppproject.XMPPProjectActivity.onCreate(XMPPProjectActivity.java:29)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
at android.app.ActivityThread.access$2300(ActivityThread.java:125)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
I think you have provided incorrect GTalk port.
Please try port = 5222

Not able to invoke remote method in RMI communication

I am trying to execute one RMI program but i am getting exception when i try to call the remote method from RMI client program.
Server program:
import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;
public class Hello extends UnicastRemoteObject implements HelloInterface {
private String message;
public Hello() throws RemoteException{
int port=1024;
Registry registry;
try{
registry = LocateRegistry.createRegistry(port);
registry.rebind("samplermi", this);
System.out.println ("Server started and listening on port " + port);
}
catch(RemoteException e){
System.out.println("remote exception"+ e);
}
}
public String sayHi (String name) throws RemoteException {
message = "Hi .. Welcome " + name;
return message;
}
public static void main(String args[]){
try{
Hello serverObj = new Hello();
}
catch (Exception e){
e.printStackTrace();
System.exit(1);
}
}
}
Client Program:
registry=LocateRegistry.getRegistry(serverAddress,serverPort);
if(registry !=null){
String[] availRemoteServices = registry.list();
for(int i=0;i<availRemoteServices.length;i++){
System.out.println("Service " + i + ": " +availRemoteServices[i]);
}
}
rmiServer=(HelloInterface)(registry.lookup("samplermi"));
System.out.println("calling remote method!");
// call the remote method
welcomeMsg = rmiServer.sayHi(text);
System.out.println("Message from server: " + welcomeMsg);
I am getting connection exception only at the time of calling the remote method sayHI. It works fine for lookup and listing the service name.
R:\Deptapps\itdm\Sample_RMI>java NewSampleRMIClient
Getting Registry Object from server!!
Registry Object Created!!
Service 0: samplermi
Services listed successfully!
Look up successful!
calling remote method!
java.rmi.ConnectException: Connection refused to host; nested exception is:
java.net.ConnectException: Connection timed out: connect
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(Unknown Source)
at sun.rmi.transport.tcp.TCPChannel.createConnection(Unknown Source)
at sun.rmi.transport.tcp.TCPChannel.newConnection(Unknown Source)
at sun.rmi.server.UnicastRef.invoke(Unknown Source)
at Hello_Stub.sayHi(Unknown Source)
at NewSampleRMIClient.main(NewSampleRMIClient.java:42)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
Note: The same program is working correctly when running server in solaris and client from windows. It is not working only when running server in AIX and client from windows.
Kindly can someone help in resolving this issue. I have been trying to fix this issue since 2 days but no use. Please help me!!
This is covered in Item A.1 of the RMI FAQ.
Run rmiregistry.exe before running Hello.class, it solved my problem.
RMi Working on the default port 1099. So no need to create the port.. If you are using default port number then exception may not be fired. and program may work properly.