SocketException: Connection reset - Client Jersey 2.0 Java 7 - java

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.

Related

what could be the reason for a file on mapped network drive not being seen by java?

My code is:
File file = new File( "T:\\sub1\\15a12f0103135510.jpg");
long lastModified = file.lastModified();
System.out.println( "last modified: " + lastModified);
System.out.println( "done: " + file.exists());
Last modified returns 0. file.exists returns false. However, I can access and open the file through windows explorer, no problem. Accessing the network share directly doesn't work either (in code). Tried smb - shows errors too. I am the admin user on the machine. What could possibly be the reason? what can I check?
if I do the following:
URL url = new URL( "file://host/share/sub1/15a12f0103135510.jpg");
url.openStream();
I get the following error:
java.io.IOException: sun.net.ftp.FtpProtocolException: Welcome message: 501 Proxy unable to contact ftp server
at sun.net.www.protocol.ftp.FtpURLConnection.connect(FtpURLConnection.java:308)
at sun.net.www.protocol.ftp.FtpURLConnection.getInputStream(FtpURLConnection.java:400)
at java.net.URL.openStream(URL.java:1045)
at apiteest.ApiTest.main(ApiTest.java:24)
Caused by: sun.net.ftp.FtpProtocolException: Welcome message: 501 Proxy unable to contact ftp server
at sun.net.ftp.impl.FtpClient.connect(FtpClient.java:1022)
at sun.net.ftp.impl.FtpClient.connect(FtpClient.java:1005)
at sun.net.www.protocol.ftp.FtpURLConnection.connect(FtpURLConnection.java:294)
... 3 more
Suppressed: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:210)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
at java.io.BufferedInputStream.read(BufferedInputStream.java:265)
at sun.net.ftp.impl.FtpClient.readServerResponse(FtpClient.java:420)
at sun.net.ftp.impl.FtpClient.readReply(FtpClient.java:497)
at sun.net.ftp.impl.FtpClient.issueCommand(FtpClient.java:539)
at sun.net.ftp.impl.FtpClient.close(FtpClient.java:1131)
at sun.net.www.protocol.ftp.FtpURLConnection.connect(FtpURLConnection.java:303)
... 3 more
Exception in thread "main" java.io.IOException: sun.net.ftp.FtpProtocolException: Welcome message: 501 Proxy unable to c
ontact ftp server
Update:
the code works when executed from powershell but not when executed from powershell started as administrator (the same user though). it also doesn't work from a service, even though the service runs under the same user. Why is it so? And how to enable the share (and possibly the mapped drive) for the service?

GCM Timeout & Connection Refused after 5000 push notifications sent

I need to sent 500 push notifications per second across gcm service. Unfortunately unlike chrome49 I have to encrypt message for every chrome50 customer, encryption keys are indicated in the request header. After above 5000 messages sent i receive Timeout & Connection Refused from https://android.googleapis.com/gcm/send and its stop working for some time and then works normally periodically
Post requests runing in threads
try {
String path = "https://android.googleapis.com/gcm/send";
URI uri = new URIBuilder()
.setPath(path)
.build();
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-Encoding", "aesgcm");
httpPost.addHeader("Cache-Control", "no-cache");
httpPost.addHeader("Connection", "Keep-Alive");
httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader("Authorization", "key=" + appKey);
httpPost.addHeader("Encryption", encryptionHeader);
httpPost.addHeader("Crypto-Key", cryptoKeyHeader);
httpPost.setEntity(new StringEntity(jsonFromData));
HttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity).replace("%", "#");
LOGGER.info(responseString);
} catch (Exception e) {
e.printStackTrace();
}
Exception: connection refused
org.apache.http.conn.HttpHostConnectException: Connection to
https://android.googleapis.com refused at
org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:190)
at
org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:294)
at
org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:643)
at
org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:479)
at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784)
at
com.mpsdevelopment.push.threads.SenderThread.sent(SenderThread.java:100)
at
com.mpsdevelopment.push.threads.SenderThread.run(SenderThread.java:76)
at
java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266) at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Connection timed out
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method) at
java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
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.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:668) at
org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:414)
at
org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:180)
... 13 more
When you experience ERR_CONNECTION_REFUSED, check your internet connection, check any cables and reboot any routers, modems, or other network devices you may be using. The error mainly occurs due to the problems in the internet connection and if there are problems in the devices you use to connect to the internet. Follow the steps in this link to solve this problem.
Based from this thread, many problems can crop up in corporate networks, since firewalls might block access to the rather unusual port or proxies might interfere with any outgoing traffic. The exception indicates a networking problem on your part – it’s simply getting a timeout. I guess neither Google nor your provider are the problem here. Check your setup and any firewalls (corporate or personal) between you and the outer internet.

How to detect SCTP connection failuer

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

ContentStreamUpdateRequest socket write error when sending large strings

I get the following exception when sending data to solr using the ContentStreamUpdateRequest of SolrJ
Exception in thread "main" org.apache.solr.client.solrj.SolrServerException: java.net.SocketException: Software caused connection abort: socket write error
at org.apache.solr.client.solrj.impl.CommonsHttpSolrServer.request(CommonsHttpSolrServer.java:478)
at org.apache.solr.client.solrj.impl.CommonsHttpSolrServer.request(CommonsHttpSolrServer.java:244)
at com.atosworldline.documentarchiver.core.solr.SolrIndexer.addDocument(SolrIndexer.java:48)
at com.atosworldline.documentarchiver.core.solr.SolrIndexerTest.main(SolrIndexerTest.java:14)
Caused by: java.net.SocketException: Software caused connection abort: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
at java.io.BufferedOutputStream.write(BufferedOutputStream.java:105)
at org.apache.commons.httpclient.HttpConnection.write(HttpConnection.java:975)
at org.apache.commons.httpclient.HttpConnection.write(HttpConnection.java:943)
at org.apache.commons.httpclient.HttpConnection.print(HttpConnection.java:1033)
at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionAdapter.print(MultiThreadedHttpConnectionManager.java:1644)
at org.apache.commons.httpclient.HttpMethodBase.writeRequestLine(HttpMethodBase.java:2218)
at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2059)
at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096)
at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398)
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323)
at org.apache.solr.client.solrj.impl.CommonsHttpSolrServer.request(CommonsHttpSolrServer.java:422)
... 3 more
The reason for that exception is, that I'm sending the binary data of the document to solr. If I remove this, the application runs successfull.
I'm using the following code to send the request
SolrServer solrServer = new CommonsHttpSolrServer(url);
ContentStreamUpdateRequest request = new ContentStreamUpdateRequest(EXTRACT);
request.addFile(document);
//request.setParam("literal.id", documentName);
request.setAction(ACTION.COMMIT, true, true);
byte[] byteContent = FileUtils.readFileToByteArray(document);
String base64encodedFile = Base64.byteArrayToBase64(byteContent, 0, byteContent.length);
request.setParam(SolrDBSchema.DOCUMENT.toString(), base64encodedFile);
request.setParam("literal." + SolrDBSchema.OWNER.toString(), owner);
request.setParam("literal." + SolrDBSchema.VALID.toString(), Boolean.toString(valid));
request.setParam("literal." + SolrDBSchema.DATE.toString(), validFor.toString());
request.setParam("literal." + SolrDBSchema.DOCUMENT_TYPE.toString(), documentType);
solrServer.request(request);
I think the String base64encodedFile is to long for a HTTP request, but I don't know a solution for that problem. As far as I know Solr is not able to store the document by configuration.
Since you are using SolrJ, consider setting the RequestWriter to use the BinaryRequestWriter, like this:
solrServer.setRequestWriter(new BinaryRequestWriter());
This will allow you to write your data to Solr in the binary format and may bypass the issue you are experiencing sending the large data stream as XML.
Note that you will need to ensure you have the BinaryUpdateRequestHandler enabled in your solrconfig.xml settings.
<requestHandler name="/update/javabin" class="solr.BinaryUpdateRequestHandler" />

WebService / java.net.SocketTimeoutException: Read timed out

I am facing an issue in WebService, in details :
Caused by: org.apache.cxf.interceptor.Fault: Could not send Message.
at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:64)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:220)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:276)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:222)
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:73)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:171)
... 26 more
Caused by: java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(SocketInputStream.java:129)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:258)
at java.io.BufferedInputStream.read(BufferedInputStream.java:317)
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:687)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:632)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1000)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:373)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponse(HTTPConduit.java:1900)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.close(HTTPConduit.java:1828)
at org.apache.cxf.transport.AbstractConduit.close(AbstractConduit.java:66)
at org.apache.cxf.transport.http.HTTPConduit.close(HTTPConduit.java:590)
at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:62)
... 31 more
When I try to send a request to the target service, it takes 30-60 seconds and than the exception above is thrown. I am using Tomcat 5,and I would like to ask is there any way of increasing the timeout value ?
Also the WSDL and WebService which I want to access is running and available.
I greatly appreciate any help in this,
Kind regards,
P.
You need to set "ReceiveTimeout" for this request.
This page has details on adding this property to request context:
http://cxf.apache.org/docs/developing-a-consumer.html
I'm a bit late to this party, but I tried the other solutions, and they didn't work, but this did.
MyWebService service = new MyWebService();
MyWebServicePortType client = service.MyWebServicePort();
Client cl = ClientProxy.getClient(client);
HTTPConduit http = (HTTPConduit) cl.getConduit();
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setConnectionTimeout(0);
httpClientPolicy.setReceiveTimeout(0);
http.setClient(httpClientPolicy);
client.doSomething(...);
Right before you make your Web Service call (i.e. port.someAction(....)), you need to set the Request Timeout to a larger amount in the requestContext:
// Set request context property.
java.util.Map<String, Object> requestContext =
((javax.xml.ws.BindingProvider) port).getRequestContext();
requestContext.put("com.sun.xml.ws.request.timeout", new Long(600000));
Or, if you are using JAX-WS:
// Set request context property.
java.util.Map<String, Object> requestContext =
((javax.xml.ws.BindingProvider) port).getRequestContext();
requestContext.put("com.sun.xml.internal.ws.request.timeout", new Long(600000));
Here is a post that really helped me:
How do I set the timeout for a JAX-WS webservice client?

Categories

Resources