I do not have a lot of experience in Java and would appreciate if you bring a light on the question.
I have the following piece of code (method) to establish the JDBC connection with a PostgreSQL database :
public void establishDBConnection() throws SQLException {
try (Connection connection = DriverManager.getConnection(
"jdbc:postgresql://" + dbServer + ":" + dbPort + "/" +
dbDatabase, dbUser, dbPassword))
catch (SQLException e) {
logger.error("Connection to Postgres Database Failed: " +
e.printStackTrace();
}
}
I expect that the SQLException would be caught by the catch block as soon as the method can't establish connection with the database (server is down). The catch block puts the exception on the console but I see that the same exception is displayed earlier right after the getConnection method execution. Thus, I have 2 quite the same exceptions on the console. See below.
The question is what is the reason for this and how to force the application to display only the exception generated by the catch block.
Logs:
Jul 07, 2017 9:11:53 PM org.postgresql.Driver connect
SEVERE: Connection error:
**org.postgresql.util.PSQLException: Connection to localhost:5433 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.**
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:265)
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:431)
at org.postgresql.Driver.connect(Driver.java:247)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at excel2db.service.impl.DBConnectionPostgresImpl.establishDBConnection(DBConnectionPostgresImpl.java:38)
at excel2db.excel2db.main(excel2db.java:86)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
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.postgresql.core.PGStream.<init>(PGStream.java:62)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:144)
... 13 more
21:11:53.465 [main] ERROR e.s.impl.DBConnectionPostgresImpl - **Connection to Postgres Database Failed: Connection to localhost:5433 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.**
There is only one exception being printed in your example: the SQLException being caught. What you think is a second exception is only (as the text shows) the cause of the SQLException: Postgres throws a SQLException, which is itself being thrown because there was a network ConnectException when Portgres tried to connect.
This chain of exceptions is very handy when you need to diagnose a failure. It allows going back to the original, low-level source of a problem. Just like, for example, it can be useful to know that you didn't got your mail (NoMailException) because the post office is on strike (OnStrikeException), because the government decided to lower the wages (WagesTooLowException). If you just had the original NoMailException, you wouldn't be able to know the reason why you got no mail, know that it's probably temporary, etc.
In this particular case, you can deduce that it was impossible to connect to the server, and not for example, that the password was incorrect.
Chaining exceptions is simply achieved by calling one of the exception constructors that take another exception as argument (most exceptions do). See https://docs.oracle.com/javase/8/docs/api/java/lang/Exception.html#Exception-java.lang.String-java.lang.Throwable-.
You need to load the driver's class into memory. Try This code :
try {
Class.forName("org.postgresql.Driver");
Connection connection = DriverManager.getConnection(jdbc:postgresql://server_address:5432/database_name?user=usernam&password=password);
} catch (Exception exception) {
exception.printStackTrace();
}
Related
I saw a lot of "java.net.ConnectException: Connection refused" questions but none referring to timeout of this error. My problem is I have to connect to a server that, in some cases, is blocked (connected by another software to the same port). So, I'm doing a loop with some max retries to try to connect:
My current code (of course, is depending on a lot of configurations for my software, but is working fine):
public TCPConnector(TCPDefinition tcpDefinition) throws IAException {
ivTcpDefinition = tcpDefinition;
// Initialize the socket
boolean retry = false;
int counter = 1;
do {
try {
ivSocket = new Socket();
ivSocket.connect(new InetSocketAddress(tcpDefinition.getHostname(), tcpDefinition.getPort()), tcpDefinition.getConnectTimeOut());
ivSocket.setSoTimeout(tcpDefinition.getAckTimeOut());
retry = false;
}
catch (UnknownHostException uhe) {
throw new IAException(null, new StringBuffer("Can't find host: ").append(tcpDefinition.getHostname()).toString(), uhe);
}
catch (SocketException see) {
StringBuilder sb = new StringBuilder("Connection refused to host ").append(tcpDefinition.getHostname()).
append(" port ").append(tcpDefinition.getPort()).append(". Connection Attempt Nr. ").append(counter);
logger.error(sb.toString(), see);
retry = true;
if (counter++ > tcpDefinition.getConnectRetries())
throw new IAException(null, sb.toString(), see);
else
logger.error("will retry to connect");
}
catch (IOException ioe) {
StringBuilder sb = new StringBuilder("I/O error while connecting to host ").append(tcpDefinition.getHostname()).
append(" port ").append(tcpDefinition.getPort()).append(". Connection Attempt Nr. ").append(counter);
logger.error(sb.toString(), ioe);
retry = true;
if (counter++ > tcpDefinition.getConnectRetries())
throw new IAException(null, sb.toString(), ioe);
else
logger.error("will retry to connect");
}
}
while (retry);
}
Well, the problem is this:
On Windows, every second, the SocketException is thrown, instead the IOException, while I have configured a timeout of 5000 msec to ivSocket.connect
On Linux, this is thrown every millisecond!!
Windows:
2019-12-05 12:40:47,609 ERROR DefaultQuartzScheduler_Worker-1 TCPConnector - Connection refused to host localhost port 13002. Connection Attempt Nr. 1
java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
2019-12-05 12:40:48,703 ERROR DefaultQuartzScheduler_Worker-1 TCPConnector - Connection refused to host localhost port 13002. Connection Attempt Nr. 2
java.net.ConnectException: Connection refused: connect
Linux:
2019-12-05 12:45:47,609 ERROR DefaultQuartzScheduler_Worker-1 TCPConnector - Connection refused to host localhost port 13002. Connection Attempt Nr. 1
java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
2019-12-05 12:45:47,610 ERROR DefaultQuartzScheduler_Worker-1 TCPConnector - Connection refused to host localhost port 13002. Connection Attempt Nr. 2
java.net.ConnectException: Connection refused: connect
Why the timeout is not executed? Well this is not exactly right. If I configure a timeout less than 1 second on Windows, then the timeout is executed. 500 msec:
2019-12-05 11:47:07,375 ERROR DefaultQuartzScheduler_Worker-1 TCPConnector - I/O error while connecting to host localhost port 13002. Connection Attempt Nr. 1
java.net.SocketTimeoutException: connect timed out
at java.net.PlainSocketImpl.socketConnect(Native Method)
2019-12-05 11:47:07,875 ERROR DefaultQuartzScheduler_Worker-1 TCPConnector - I/O error while connecting to host localhost port 13002. Connection Attempt Nr. 2
java.net.SocketTimeoutException: connect timed out
at java.net.PlainSocketImpl.socketConnect(Native Method)
It is possible to configure a "connect refuse" timeout?
There is no such thing as a "connection refused timeout".
"Connection refused" happens when the server sees the connection request, but there is no service listening for connections on the IP + port that the request is directed to. The server then "refuses" the connection. This typically happens instantly, so so no timeout is triggered.
"Connection timed out" happens (typically) when something stops the connection request from reaching the server1, 2. So the client-side will wait for the response from the server, and then resend / wait a few times. And eventually the time allotted for establishing a connection will expire ... and the connection times out.
As you can see these are different scenarios. And they are reported back to the Java client-side differently.
So the reason you are not getting timeouts is that the "connection refused" responses are coming back quick enough that your configured timeout is not exceeded.
That might also explain why setting the connect timeout small might have changed the behavior. There may also be issues with the granularity of the timeout that the OS allows Java to set.
To investigate this further, I think we would need a minimal reproducible example. For example, we need to see how you have implemented the code that manages the server-socket and accepts connections on the server side.
1 - The blockage could be on the server's reply packets.
2 - There are various possible causes for this kind of thing. The most likely are a firewall blocking traffic somewhere, a network routing problem, or using a private IP address on the wrong network.
I have orace 11g running on 192.168.1.217 and I am trying to connect it using JDBC driver with java and it gives me following error
IO Error: The Network Adapter could not establish the connection
Library I am using is ojdbc6.jar
Here is my code
public void makeOracleConnection() {
try {
Class.forName("oracle.jdbc.OracleDriver");
oraCon = DriverManager.getConnection("jdbc:oracle:thin:#192.168.1.217:1521:orcl", "hr", "hr");
oraStmt = oraCon.createStatement();
oraRsStmt=oraCon.createStatement(ResultSet.CONCUR_READ_ONLY,ResultSet.TYPE_SCROLL_INSENSITIVE);
} catch (Exception e) {
System.out.println("Error while making connection with Database : " + e.getMessage());
}
}
I have also tried to ping on 192.168.1.217 then pins is successful.
Also TNSLISTENER is running on that machine.
please help.
Please find print stack trace here
run:
java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:743)
at oracle.jdbc.driver.PhysicalConnection.connect(PhysicalConnection.java:657)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:560)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at test.oracle.makeOracleConnection(oracle.java:30)
at test.oracle.<init>(oracle.java:21)
at test.oracle.main(oracle.java:69)
Caused by: oracle.net.ns.NetException: The Network Adapter could not establish the connection
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:470)
at oracle.net.resolver.AddrResolution.resolveAndExecute(AddrResolution.java:506)
at oracle.net.ns.NSProtocol.establishConnection(NSProtocol.java:595)
at oracle.net.ns.NSProtocol.connect(NSProtocol.java:230)
at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1452)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:496)
... 8 more
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 oracle.net.nt.TcpNTAdapter.connect(TcpNTAdapter.java:163)
at oracle.net.nt.ConnOption.connect(ConnOption.java:159)
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:428)
... 13 more
BUILD SUCCESSFUL (total time: 1 second)
You get the error
java.net.ConnectException: Connection refused: connect
Which means that there is nothing listening on the machine and port you are trying to connect to. Your Java code looks correct so I would continue to investigate that Oracle is actually listening on port 1521 on 192.168.1.217.
If you run run netstat -n on the server you should find a line that looks like
TCP [::]:1521 [::]:0 LISTENING
If something really is listening on that port. If you do not find that line, check your Oracle configuration.
Try to connect with some other tool, ie sqlplus to verify that the issue is not with Oracle. If you cannot connect with sqlplus/sql developer, make sure that your oracle is configured to allow remote connections, and also listens on given addresses/ports
public void makeOracleConnection() {
try {
Class.forName("oracle.jdbc.OracleDriver");
Connection oraCon = DriverManager.getConnection("jdbc:oracle:thin:#192.168.1.217:1521:orcl", "hr", "hr");
Statement oraStmt = oraCon.createStatement();
//oraRsStmt=oraCon.createStatement(ResultSet.CONCUR_READ_ONLY,ResultSet.TYPE_SCROLL_INSENSITIVE);
ResultSet rs = oraStmt.executeQuery("select hello as result from dual");
while(rs.next()) {
System.out.println(rs.getString("result"));
}
}
catch (Exception e)
System.out.println("Error while making connection with Database : " + e.getMessage());
}
}
Try this out. Hope it'll help. I also don't like your connection path. Is it right? I think it should be something like this:
jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS_LIST=(LOAD_BALANCE=YES)(ADDRESS=(PROTOCOL=tcp)(HOST=ip adres)(PORT=port)))(CONNECT_DATA=(SERVICE_NAME = orcl)))","username","password"
I am trying to connect with database using jdbc in java file. It is not connecting at all and giving me the error constantly "Something went wrong"; I guess it is because of the port number because all other data such as username, password and other code seems correct.
I want to check the default port number so that I can try it properly. I did try using all three of these 8080, 80 and 3306 but it shows me error.
Here port 8080 is used for HTTP server, 3306 is supposed to be default from the research and 80 randomly.
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver found");
} catch (ClassNotFoundException e) {
System.out.println("Driver not found");
}
String url="jdbc:mysql://localhost:8080 or 80 or 3306 or without port number/test";
String user="user";
String password="";
Connection con=null;
try {
con=DriverManager.getConnection(url, user, password);
System.out.println("Success");
} catch (SQLException e){
e.printStackTrace();
}
}
The error is giving below when used String url="jdbc:mysql://localhost:3306/test";
Driver found
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:377)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1036)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:338)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2232)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2265)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2064)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:790)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:44)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:377)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:395)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:325)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at com.town.connect.Dbconnection.main(Dbconnection.java:26)
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:382)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:241)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:228)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:431)
at java.net.Socket.connect(Socket.java:527)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:213)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:297)
... 15 more
You can access those settings via
mysql> show variables;
DriverManager.getConnection("jdbc:mysql://"+dbaddress+"/"+dbname+"?user=" + username + "&password=" + password)
This statement can help you. No need to define any other port. Just define the following variables as per your mysql configuration.
dbaddress
dbname
username
password
And if this doesn't works can you post the stacktrace or a screenshot for your error ?
If you want to know the port number you can use following command
SHOW VARIABLES WHERE Variable_name = 'port';
I've tried to used RMI, here is server side. at first it worked without any exception, but now after three times whenever i try to run the below code, i will get some errors
The code is:
import java.rmi.server.UnicastRemoteObject;
/**
* Created by elyas on 12/11/14 AD.
*/
public class LogicImplement extends UnicastRemoteObject implements Logic
{
public LogicImplement() throws Exception
{
java.rmi.registry.LocateRegistry.createRegistry(6060);
java.rmi.Naming.rebind("Object1",this);
}
#Override
public int sum(int a, int b) throws Exception
{
int result = a + b;
System.out.println("ana sum executed");
return result;
}
public static void main(String[] args)
{
try
{
LogicImplement logicImplement = new LogicImplement();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
The error is like this: i've tried to change the Object1 to for example Object2, but again i will get error, also i change the port number...
what is solution?
java.rmi.ConnectException: Connection refused to host: 127.0.0.1; nested exception is:
java.net.ConnectException: Connection refused
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:341)
at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source)
at java.rmi.Naming.rebind(Naming.java:177)
at LogicImplement.<init>(LogicImplement.java:12)
at LogicImplement.main(LogicImplement.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: 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:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)
at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40)
at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:147)
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613)
... 12 more
java.net.ConnectException: Connection refused
There could be couple of reasons for this exception:
You have not started your rmiregistry in background.
You are trying to connect to the wrong port number.
Your firewall maybe blocking the connections.
The Answer was very simple, By default, the registry runs on port 1099. To start the registry on a different port, specify the port number on the command line. Do not forget to unset your CLASSPATH environment variable. for more information check this link: Running the Example Programs
** So for fixing this code i must change the port number form 6060 to 1099
notice that: if 1099 is used by other services you have to test 1100, and if 1100 is used too, you have yo use 1101 and so on. :-)
Since this was a port number issue, there is another way to start the registry on the port number you want:
java.rmi.registry.Registry rmiRegistry = java.rmi.registry.LocateRegistry.
createRegistry(6060); // Creates a registry on 6060
rmiRegistry.rebind("Object1",this); // Binds to registry created on 6060
You haven't started the RMI Registry.
When you get past this, if it still happens when calling the remote method, see item A.1 of the RMI FAQ.
I am running two axis2 services which communicate with each other. On every service startup I get this error:
2014-02-24 13:02:31,258 [INFO ] HTTPSender - Unable to sendViaPost to url[http://127.0.0.1:8081/axis2/services/MYSERVICE1.MYSERVICE1HttpSoap12Endpoint/]
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:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.commons.httpclient.protocol.ReflectionSocketFactory.createSocket(ReflectionSocketFactory.java:140)
at org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory.createSocket(DefaultProtocolSocketFactory.java:125)
at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:707)
at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionAdapter.open(MultiThreadedHttpConnectionManager.java:1361)
at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:387)
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
at org.apache.axis2.transport.http.AbstractHTTPSender.executeMethod(AbstractHTTPSender.java:621)
at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:193)
at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:75)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:404)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:231)
at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:443)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:406)
at org.apache.axis2.description.OutInAxisOperationClient$NonBlockingInvocationWorker.run(OutInAxisOperation.java:446)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
Since this error is not important, I would like to catch it and to print some better error message instead of the whole stack trace. Where do I catch this error?
Looking at the stack trace, I don't think you can catch it. Catching it would require that you own code somewhere in the Thread where the exception is being thrown.
Looking at the lowest stack in the trace shows this:
at java.lang.Thread.run(Thread.java:724)
To me this says that the exception is occurring in a thread most likely started by Axis. Because of this you can't catch it and show an error message.
If this is expected behavior, the best you can do is to configure your logging framework not to show INFOs from Axis. Be aware that this may mean you'll also miss more useful error messages as well.
All in all, I would focus on how to solve the "Unable to sendViaPost" from happening rather than suppressing the logging statement.
To answer your comment question: As you can see from the stack trace, the exception is not caught by any client code but is bubbled up to Thread itself. This is the stopping point for an Exception and where it stops. If you were going to catch it you'd have to have code in its call stack (which you don't, since when the thread is created by Axis a new call stack is created for the new thread Axis starts).
Read more here. The only difference in your case is that since the exception is not thrown on the main thread the program doesn't exit, but the thread where the exception occurs is terminated.
To sum it up: You have no code in the call stack and therefore cannot catch the exception. The only other option is to turn of INFO statements for Axis.
If I am understanding the question properly you're attempting to catch something that is not the exception that is being thrown.
This:
HTTPSender - Unable to sendViaPost to url[http://127.0.0.1:8081/axis2/services/MYSERVICE1.MYSERVICE1HttpSoap12Endpoint/]
is what is being attempted. When it failed it's throwing a ConnectException.
Which you can simply catch with
try{
//Code that Makes the Connection
}
catch (ConnectException e)
{
e.printStackTrace();//Or What ever your message may be
}
Without seeing some code it's impossible to give a definitive answer. But this likely will solve the problem.
One Caveat, if you do catch a ConnectException to suppress it, you could suppress when there actually is a problem that would also throw a ConnectException.
If this is happening when you are starting up the server you might want to check why this is happening before trying to suppress it.
If it's refusing the connection that you are attempting you might want to ensure where it is connecting to has an available socket to connect to.
2014-02-24 13:02:31,258 [INFO] HTTPSender - Unable to
sendViaPost to
url[http://127.0.0.1:8081/axis2/services/MYSERVICE1.MYSERVICE1HttpSoap12Endpoint/]
Well, if you look closely, the message which you are trying to catch isn't an ERROR at all. It's an INFO log generated from HTTPSender. Only thing which you should catch in this entire stacktrace is java.net.ConnectException and check for message Connection refused.
You can make it easier for your clients though and provide a message, by wrapping the java.net.ConnectException with message Connection refused or throwing a custom exception with the original exception as the cause.
UPDATE
java.net.ConnectException is an elementary exception in network transactions. Generally standard libraries do not catch them unless there is something specific to be done.
In this case, if you are unable to catch hold of java.net.ConnectException, then you can look out to catch AxisFault thrown by org.apache.axis2.description.OutInAxisOperationClient.send.
Below snippet may be useful for you.
try {
...
} catch (RemoteException ex) {
if(ex instanceof AxisFault){
logger.error("Axis Fault error: " + ((AxisFault)ex).getFaultString());
throw new CustomExcpetion(" Custom Message ");
}
}
Also note that AxisFault is a subclass of java.rmi.RemoteException and this will not get caught when you use java.lang.Exception in a catch statement.
Shishir