I am using mobicents CAP implementation to build a CAP application for CAMEL charging; my application is working fine and I can send and receive messages between SSF and SCF.
What I am looking for is: how to detect it the SCTP link between client and server has been broken? Because when I deliberately stop the server and keep the client running, on sending CAPDialog doesn't raise any error.
When I stop the server, on console I see following exception:
2015-04-14 13:15:29,669 [Thread-0 ] ERROR org.mobicents.protocols.sctp.SelectorThread - Exception while finishing connection for Association=clientAsscoiation
java.net.ConnectException: Connection refused: no further information
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
at sun.nio.ch.SocketChannelImpl.finishConnect(Unknown Source)
at org.mobicents.protocols.sctp.SelectorThread.finishConnectionTcp(SelectorThread.java:407)
at org.mobicents.protocols.sctp.SelectorThread.finishConnection(SelectorThread.java:368)
at org.mobicents.protocols.sctp.SelectorThread.run(SelectorThread.java:151)
at java.lang.Thread.run(Unknown Source)
And during this if I try to send a CAPDialog e.g. send an oAnswer event, it simple doesn't tell if the request was successful or not (which ideally should return a failure in my case)
OAnswerSpecificInfo oAnswerSpecificInfo = this.getCapProvider().getCAPParameterFactory().createOAnswerSpecificInfo(null,
false, false, null, null, null);
ReceivingSideID legID = this.getCapProvider().getCAPParameterFactory().createReceivingSideID(LegType.leg2);
MiscCallInfo miscCallInfo = this.getCapProvider().getINAPParameterFactory().createMiscCallInfo(MiscCallInfoMessageType.notification, null);
EventSpecificInformationBCSM eventSpecificInformationBCSM = this.getCapProvider()
.getCAPParameterFactory()
.createEventSpecificInformationBCSM(oAnswerSpecificInfo);
CAPDialogCircuitSwitchedCall capDialog = (CAPDialogCircuitSwitchedCall) getCapProvider().getCAPDialog(localDialogId);
capDialog.addEventReportBCSMRequest(EventTypeBCSM.oAnswer, eventSpecificInformationBCSM, legID, miscCallInfo, null);
capDialog.setUserObject(getParamAsString("referenceId"));
capDialog.setReturnMessageOnError(true);
capDialog.send();
"capDialog.send();" code does not return back an error even when any underlying SS7 link is down.
If you have access to SCTP stack you can check if SCTP connection is up or down:
Association association = ...;
association.isConnected();
Related
I'm trying to understand why this error occurs:
javax.net.ssl|WARNING|01|main|2021-07-04 12:08:30.668 CEST|SSLSocketImpl.java:497|SSLSocket duplex close failed (
"throwable" : {
java.net.SocketException: Socket is closed
at java.base/java.net.Socket.shutdownInput(Socket.java:1538)
at java.base/sun.security.ssl.BaseSSLSocketImpl.shutdownInput(BaseSSLSocketImpl.java:216)
at java.base/sun.security.ssl.SSLSocketImpl.shutdownInput(SSLSocketImpl.java:751)
at java.base/sun.security.ssl.SSLSocketImpl.bruteForceCloseInput(SSLSocketImpl.java:701)
at java.base/sun.security.ssl.SSLSocketImpl.duplexCloseOutput(SSLSocketImpl.java:562)
at java.base/sun.security.ssl.SSLSocketImpl.close(SSLSocketImpl.java:486)
at java.base/sun.security.ssl.SSLSocketImpl$AppInputStream.close(SSLSocketImpl.java:1034)
at com.ibm.db2.jcc.t4.a0.j(a0.java:343)
at com.ibm.db2.jcc.t4.b.freeTransport_(b.java:5523)
at com.ibm.db2.jcc.t4.a.close_(a.java:455)
at com.ibm.db2.jcc.am.Agent.close(Agent.java:345)
at com.ibm.db2.jcc.t4.b.b(b.java:965)
at com.ibm.db2.jcc.t4.b.a(b.java:804)
at com.ibm.db2.jcc.t4.b.a(b.java:441)
at com.ibm.db2.jcc.t4.b.a(b.java:414)
at com.ibm.db2.jcc.t4.b.<init>(b.java:352)
at com.ibm.db2.jcc.DB2SimpleDataSource.getConnection(DB2SimpleDataSource.java:233)
at com.ibm.db2.jcc.DB2SimpleDataSource.getConnection(DB2SimpleDataSource.java:200)
at com.ibm.db2.jcc.DB2SimpleDataSource.getConnection(DB2SimpleDataSource.java:182)
at com.example.MainApplication.main(MainApplication.java:36)}
)
javax.net.ssl|ALL|01|main|2021-07-04 12:08:30.668 CEST|SSLSocketImpl.java:1217|Closing output stream
Exception in sql: com.ibm.db2.jcc.am.SqlNonTransientConnectionException
DB2 SQL Error: SQLCODE=-20157, SQLSTATE=08004, SQLERRMC=WEBADMIN;QUIESCE DATABASE;;, DRIVER=4.25.13
com.ibm.db2.jcc.am.SqlNonTransientConnectionException: DB2 SQL Error: SQLCODE=-20157, SQLSTATE=08004
The exception is thrown when I'm invoking getConnection() method of the DriverManager:
connection = DriverManager.getConnection(DB_URL, properties);
I'm using Java 11.0.11 from Oracle (non-OpenJDK).
Talk with your DBA team or whoever manages the database - you get this exception because someone (or some job) has put the database into a specific state that is used for maintenance activity.
Normally this is a temporary situation, and the database (or Db2-instance) needs to be brought back to normal mode by an unquiesce action, when the maintenance activity is completed. After the unquiesce action, your connection should complete as normal.
The SQLCODE (-20157) and SQLERRMC ( SQLERRMC=WEBADMIN;QUIESCE DATABASE;) that are in the message tell you the cause of this exception.
Lookup SQL20157N in the docs to get the detailed explanation.
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.
Problem Description: MongoDB version is 3.4
In fact, did not do anything on the normal query, write,
because it is in the testing phase, QPS is small.
Question:
1: How is this anomaly produced.
2: what configuration or adjustment needs to be done? help me
02-01 15:11:47 WARN - Got socket exception on connection [connectionId{localValue:43}] to 172.16.199.96:22001. All connections to 172.16.199.96:22001 will be closed.
02-01 15:11:47 INFO - Closed connection [connectionId{localValue:43}] to 172.16.199.96:22001 because there was a socket exception raised by this connection.
org.springframework.data.mongodb.UncategorizedMongoDbException: Exception receiving message; nested exception is com.mongodb.MongoSocketReadException: Exception receiving message
at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:107)
at org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:2135)
at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:1978)
at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1784)
at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1767)
at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:641)
at org.springframework.data.mongodb.core.MongoTemplate.findOne(MongoTemplate.java:606)
at org.springframework.data.mongodb.core.MongoTemplate.findOne(MongoTemplate.java:598)
at com.xxx.xxx.xxx.xxx(xxxService.java:46)
at com.xxx.xxx.xxx.xxx(xxxService.java:157)
at com.xxx.xxx.xxx.xxx(xxxService.java:142)
at com.xxx.xxx.xxx.xxx(xxxService.java:87)
at com.alibaba.dubbo.common.bytecode.Wrapper2.invokeMethod(Wrapper2.java)
at com.alibaba.dubbo.rpc.proxy.javassist.JavassistProxyFactory$1.doInvoke(JavassistProxyFactory.java:46)
at com.alibaba.dubbo.rpc.proxy.AbstractProxyInvoker.invoke(AbstractProxyInvoker.java:72)
at com.alibaba.dubbo.rpc.protocol.InvokerWrapper.invoke(InvokerWrapper.java:53)
at com.alibaba.dubbo.rpc.filter.ExceptionFilter.invoke(ExceptionFilter.java:64)
at com.alibaba.dubbo.rpc.protocol.ProtocolFilterWrapper$1.invoke(ProtocolFilterWrapper.java:69)
at com.alibaba.dubbo.monitor.support.MonitorFilter.invoke(MonitorFilter.java:75)
at com.alibaba.dubbo.rpc.protocol.ProtocolFilterWrapper$1.invoke(ProtocolFilterWrapper.java:69)
at com.alibaba.dubbo.rpc.filter.TimeoutFilter.invoke(TimeoutFilter.java:42)
at com.alibaba.dubbo.rpc.protocol.ProtocolFilterWrapper$1.invoke(ProtocolFilterWrapper.java:69)
at com.alibaba.dubbo.rpc.protocol.dubbo.filter.TraceFilter.invoke(TraceFilter.java:78)
at com.alibaba.dubbo.rpc.protocol.ProtocolFilterWrapper$1.invoke(ProtocolFilterWrapper.java:69)
at com.alibaba.dubbo.rpc.filter.ContextFilter.invoke(ContextFilter.java:61)
at com.alibaba.dubbo.rpc.protocol.ProtocolFilterWrapper$1.invoke(ProtocolFilterWrapper.java:69)
at com.alibaba.dubbo.rpc.filter.GenericFilter.invoke(GenericFilter.java:132)
at com.alibaba.dubbo.rpc.protocol.ProtocolFilterWrapper$1.invoke(ProtocolFilterWrapper.java:69)
at com.alibaba.dubbo.rpc.filter.ClassLoaderFilter.invoke(ClassLoaderFilter.java:38)
at com.alibaba.dubbo.rpc.protocol.ProtocolFilterWrapper$1.invoke(ProtocolFilterWrapper.java:69)
at com.alibaba.dubbo.rpc.filter.EchoFilter.invoke(EchoFilter.java:38)
at com.alibaba.dubbo.rpc.protocol.ProtocolFilterWrapper$1.invoke(ProtocolFilterWrapper.java:69)
at com.alibaba.dubbo.rpc.protocol.dubbo.DubboProtocol$1.reply(DubboProtocol.java:100)
at com.alibaba.dubbo.remoting.exchange.support.header.HeaderExchangeHandler.handleRequest(HeaderExchangeHandler.java:98)
at com.alibaba.dubbo.remoting.exchange.support.header.HeaderExchangeHandler.received(HeaderExchangeHandler.java:170)
at com.alibaba.dubbo.remoting.transport.DecodeHandler.received(DecodeHandler.java:52)
at com.alibaba.dubbo.remoting.transport.dispatcher.ChannelEventRunnable.run(ChannelEventRunnable.java:81)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: com.mongodb.MongoSocketReadException: Exception receiving message
at com.mongodb.connection.InternalStreamConnection.translateReadException(InternalStreamConnection.java:483)
at com.mongodb.connection.InternalStreamConnection.receiveMessage(InternalStreamConnection.java:228)
at com.mongodb.connection.UsageTrackingInternalConnection.receiveMessage(UsageTrackingInternalConnection.java:96)
at com.mongodb.connection.DefaultConnectionPool$PooledConnection.receiveMessage(DefaultConnectionPool.java:440)
at com.mongodb.connection.CommandProtocol.execute(CommandProtocol.java:112)
at com.mongodb.connection.DefaultServer$DefaultServerProtocolExecutor.execute(DefaultServer.java:168)
at com.mongodb.connection.DefaultServerConnection.executeProtocol(DefaultServerConnection.java:289)
at com.mongodb.connection.DefaultServerConnection.command(DefaultServerConnection.java:176)
at com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol(CommandOperationHelper.java:216)
at com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol(CommandOperationHelper.java:207)
at com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol(CommandOperationHelper.java:113)
at com.mongodb.operation.FindOperation$1.call(FindOperation.java:516)
at com.mongodb.operation.FindOperation$1.call(FindOperation.java:510)
at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:431)
at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:404)
at com.mongodb.operation.FindOperation.execute(FindOperation.java:510)
at com.mongodb.operation.FindOperation.execute(FindOperation.java:81)
at com.mongodb.Mongo.execute(Mongo.java:836)
at com.mongodb.Mongo$2.execute(Mongo.java:823)
at com.mongodb.DBCursor.initializeCursor(DBCursor.java:870)
at com.mongodb.DBCursor.hasNext(DBCursor.java:142)
at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:1964)
... 37 common frames omitted
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:210)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at com.mongodb.connection.SocketStream.read(SocketStream.java:85)
at com.mongodb.connection.InternalStreamConnection.receiveResponseBuffers(InternalStreamConnection.java:494)
at com.mongodb.connection.InternalStreamConnection.receiveMessage(InternalStreamConnection.java:224)
... 57 common frames omitted
java version 1.8.
spring boot version 1.5.3.
deployed with docker.
mongo.hosts=ip:port,ip:port,ip:port
mongo.database.name=dbname
mongo.username=username
mongo.password=pwd
mongo.connections.per.host=32
mongo.max.wait.time=2000
mongo.connect.timeout=2000
You can try,
autoConnectRetry simply means the driver will automatically attempt to reconnect to the server(s) after unexpected disconnects. In production environments you usually want this set to true.
This is from another post, How to configure MongoDB Java driver MongoOptions for production use?
for everybody who is experiencing the same random MongoSocketReadException, you may need the socketTimeoutMS or maxIdleTimeMS parameters instead. The parameter autoConnectRetry is not exposed any more in the mongodb connection string.
Our situation: we switched to mongodb atlas serverless solution for our development and testing environments, ever since then we got this MongoSocketReadException like every 15 min. or randomly. We are also behind a enterprise firewall.
According to https://www.mongodb.com/docs/v6.0/tutorial/connection-pool-performance-tuning/:
a misconfigured firewall closes a socket connection incorrectly and the driver cannot detect that the connection closed improperly.
you need => Use socketTimeoutMS to ensure that sockets are always closed. Set socketTimeoutMS to two or three times the length of the slowest operation that the driver runs.
because the socketTimeoutMS is by default 0, which will never timeout.
And another parameter maxIdleTimeMS may also affect the connection because if the socket is closed and on the client side it's not detected, the connection will be still waiting in idle time and not cloesd. And by default it's 0 meaning it waits forever with no upper boundaries.
So configure this to a small amount may help the driver to close the the problematic connection with its closed socket, before it tries to connect to the db using the same connection and presumes the connection is still there.
So our solution:
...mongodbUri...?socketTimeoutMS=150000&maxIdleTimeMS=150000
we changed the socketTimeoutMS from 0 to 15s and same for the maxIdleTimeMS.
I'm getting similar error to this link1.
When I post(client to server) a small xml via REST, everything works fine. Unfortunately I'm getting an error while I'm posting some bigger xmls, when the connection lasts longer than 10/15 min. (I assume It's some kind of timeout)
I corrected my SSL certs as it was mentioned in the link1 - configureClient() method is the same in my case as the solution from the one in the link1.
I added also System.setProperty("java.net.preferIPv4Stack" , "true"); - sometimes it solves Connection reset
Essential info:
Error: javax.ws.rs.ProcessingException: java.net.SocketException: Connection reset
Method: REST POST
Java version: 7
Engine: Jersey 2.x
Side: Client
System: Windows 7
My client:
System.setProperty("java.net.preferIPv4Stack" , "true");
RestMethodes restMethodes = new RestMethodes();
ClientConfig config = new ClientConfig();
config = config.property(ClientProperties.CONNECT_TIMEOUT, 0);
config = config.property(ClientProperties.READ_TIMEOUT, 0);
config.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
Client client = configureClient(config);
client.register(HttpAuthenticationFeature.basic(USER, PASS));
WebTarget target = client.target(SERVER_URL + "/bundles/assets");
Invocation.Builder responseInvocation = target.request(MediaType.APPLICATION_JSON);
// My exception is thrown there
Response response = responseInvocation.post(Entity.xml(assetsString));
String entity = response.readEntity(String.class);
//entity = jsonPrettyPrinter(entity);
if (entity.isEmpty() || entity.equals("")) {
log.info("[POST ASSETS] Failed : Response is empty");
}
Response.StatusType codeName = response.getStatusInfo();
int code = response.getStatus();
if (code != 200) {
log.error("[POST ASSETS] Failed : HTTP error code : " + response.getStatus() + "\n" + entity);
response.close();
} else {
log.info("[POST ASSETS] RESPONSE CODE ID : " + code + " CODE NAME : " + codeName);
log.info("[POST ASSETS] RESPONSE : " + entity);
response.close();
}
client.close();
My ERROR
Exception in thread "main" javax.ws.rs.ProcessingException: java.net.SocketException: Connection reset
at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:287)
at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:252)
at org.glassfish.jersey.client.JerseyInvocation$1.call(JerseyInvocation.java:684)
at org.glassfish.jersey.client.JerseyInvocation$1.call(JerseyInvocation.java:681)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:444)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:681)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:437)
at org.glassfish.jersey.client.JerseyInvocation$Builder.post(JerseyInvocation.java:343)
at com.sas.spl.saslineagebridges.test.PostTester.main(PostTester.java:61)
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:209)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at sun.security.ssl.InputRecord.readFully(InputRecord.java:465)
at sun.security.ssl.InputRecord.read(InputRecord.java:503)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973)
at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:930)
at sun.security.ssl.AppInputStream.read(AppInputStream.java:105)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:286)
at java.io.BufferedInputStream.read(BufferedInputStream.java:345)
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:704)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:647)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:675)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1569)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:338)
at org.glassfish.jersey.client.internal.HttpUrlConnector._apply(HttpUrlConnector.java:399)
at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:285)
... 11 more
EDIT:
I forgot to mention that I managed to post my request via CURL from bash with infinity timeout and keep alive, so It shouldn't be the servers issue. The CURL REST post took 24 min. and my java client throws connection reset after 15 min. In my opinion It might be my fault.
You are facing a timeout issue, although your client seems well configured. This timeout can be caused by any firewall, proxy, load-balancer, or even the server itself if it is running a web server like Apache in front of the application server. Please check what is in-between your client and the application server, and set timeouts accordingly everywhere.
It doesn't mean that you can't do nothing on the client itself, but it's much more difficult to solve there.
On Windows you will need to enable the TCP keep-alives, first.
After, according to the Client Transport you are using, we will try to add TCP keep-alives to the sockets built by the underlying factory, something similar that we know possible on Axis clients. This solution is more time-consuming for you.
I am currently trying to connect to a MongoDB replica set using the (relatively) new 3.0 Java driver. However I can't seem to catch the MongoSecurityExceptions that occur when the user provides bad credentials. This is my current code.
try {
MongoClientURI mongoClientURI = new MongoClientURI("mongodb://<user>:<password>#member1.com:27017/?authSource=db"
this.mongoClient = new MongoClient(mongoClientURI);
}
catch(Exception e) {
// TODO: some proper exception handling
System.err.println(e.toLocalizedMessage());
}
This code works fine when run with correct credentials, but an exception is thrown outside of the try-catch when bad credentials are provided.
com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=null, userName='<user>', source='<source>', password=<hidden>, 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(Thread.java:745)
Any idea where to handle authentication exceptions?
The MongoClient constructors do not throw any connectivity-related exceptions. Rather, they return immediately after starting one or more background threads that attempt to establish a connection and authenticate based on the provided credentials.
It's only when an application uses the MongoClient to perform some operation on the MongoDB server that an exception will be thrown. However, that exception is a generic timeout exception indicating that the driver failed to find a suitable server for the operation before the server selection timeout expires. For example:
MongoClient client = new MongoClient(asList(new ServerAddress("localhost"), new ServerAddress("localhost:27018")),
singletonList(MongoCredential.createCredential("username",
"admin",
"bad".toCharArray())),
MongoClientOptions.builder().serverSelectionTimeout(1000).build());
try {
client.getDB("admin").command("ping");
} catch (MongoTimeoutException e) {
// do something
}
will throw a MongoTimeoutException after 1 second. While no MongoSecurityException is thrown, the message of the MongoTimeoutException will contain relevant details. For example, when connecting to a three member replica set when one of the servers is down, and authentication failed on the remaining two, the message field of the MongoTimeoutException will be something like:
Timed out after 1000 ms while waiting for a server that matches
ReadPreferenceServerSelector{readPreference=primary}. Client view of
cluster state is {type=UNKNOWN, servers=[{address=localhost:27017,
type=UNKNOWN, state=CONNECTING,
exception={com.mongodb.MongoSocketOpenException: Exception opening
socket}, caused by {java.net.ConnectException: Connection refused}},
{address=localhost:27018, type=UNKNOWN, state=CONNECTING,
exception={com.mongodb.MongoSecurityException: Exception
authenticating MongoCredential{mechanism=null, userName='username',
source='admin', password=, mechanismProperties={}}}, caused by
{com.mongodb.MongoCommandException: Command failed with error 18:
'Authentication failed.' on server localhost:27018. The full response
is { "ok" : 0.0, "code" : 18, "errmsg" : "Authentication failed." }}}]