javax.net.ssl.SSLHandshakeException: Connection reset by peer - java

I use following code to call an Azure mobile backend API in my Android app,
try {
mobileClient.invokeApi("CustomTransaction", senderToCheck,
Boolean.class, new ApiOperationCallback<Boolean>() {
#Override
public void onCompleted(Boolean result,
Exception error, ServiceFilterResponse response) {
if (error == null) {
CheckSender(result);
} else {
dial.dismiss();
Crouton.makeText(MyActivity.this,
"Eror Occured with service",
Style.ALERT).show();
}
}
});
} catch (SecurityException e) {
Log.d(TAG, "CouldNotConnectToSocket", e);
e.printStackTrace();
} catch (IllegalArgumentException e) {
Log.d(TAG, "CouldNotConnectToSocket", e);
e.printStackTrace();
}
Other information:
CustomTransaction - API Controller name;
senderToCheck - JSON parsable data transfer object;
Boolean.class - return type; and 4th parameter is the callback method
All objects are JSON parsable and this worked like several days ago.
So this API call/Azure call always times out giving a What does "connection reset by peer" mean? ,SSLHandShakeExceptionand and most of the time Connect gets Timed out.
Main cause for the problem is com.microsoft.windowsazure.mobileservices.MobileServiceException: Error while processing request.
I tried re-publishing my asp.net web app several times but it never hits controller action where my debugger point is placed when debugging the service call remotely.
I checked if my service is down, found it is up & running then checked Azure management portal logs, found out traceApi messages of some controller action methods. and of SQL Cpu usages and Data out packet sizes., but I never gets a proper reply from anywhere to solve this problem for two weeks now.
In case,if I am correct, think the solution for this problem lies in http://www.webapper.com/blog/index.php/2007/02/09/troubleshooting-javaxnetsslsslhandshakeexception/ but Im not pretty sure on doing it.
Please advise me on getting this fixed

Related

Java controller code runs even after returning

I am having an issue which my team and I have been debugging for hours without any clue to why my code is not executing in order,
The issue now is that in my controller I call two main functions, function 1 checks for payment and if payment is not successful, it throws an error which will be propagated to my controller which catches it and returns a 302 to redirect to an error page. However, based on my logs, my code executed function 2 which is saving the user details into my database first before checking for the payment response
My team is unable to replicate this behaviour in our dev and uat environment and this issue only occurs in production, in production, the code repeatedly runs the function 2 first based on the logs printed before returning the error page to the users,
Could this be a code issue or a server setting issue that is causing this? App is hosted on cloud foundry with autoscaling with two instances by default
Code of my controller:
public ResponseEntity<Void> executePayment(
#ModelAttribute PaymentRequestDto paymentRequestDto,
#RequestParam("sessionId") String sessionId,
HttpServletResponse response) {
GrafanaUtils.addToThreadContextTraceGroupId(sessionId);
MpgsPayApiResponseDto mpgsPayApiResponseDto;
String hashedCode = Base64.getEncoder().encodeToString((sessionId.getBytes()));
response.addCookie(CookieUtils.generateCookie(Constants.REDIRECT_COOKIE_ID, hashedCode));
// Call MPGS
try {
// error thrown from this service
mpgsPayApiResponseDto = authenticationService.executePayment(paymentRequestDto, sessionId);
} catch (Exception ex) {
GrafanaUtils.addToThreadContextTraceGroupId(ExceptionConstants.MPGS_CONNECTION_EXCEPTION, ex);
return ResponseEntity.status(HttpStatus.FOUND)
.location(URI.create(paymentUiBaseUrl.concat(paymentUiErrorPath))).build(); // should return here
}
// MPGS Success
// should never reach here if above code throws exception and return
// however code still runs after above throws error and return error page
try {
authenticationService.savePaymentDetails(mpgsPayApiResponseDto, sessionId);
} catch (Exception ex) {
log.error("[executePayment] Error saving payment details");
}
return ResponseEntity.status(HttpStatus.FOUND)
.location(URI.create(paymentUiBaseUrl.concat(paymentUiConfirmPath))).build();
}
Code of my service:
public MpgsPayApiResponseDto executePayment(PaymentRequestDto paymentRequestDto, String sessionId) {
if (!("PROCEED").equals(paymentRequestDto.getResponse().getGatewayRecommendation())) {
MpgsPayApiResponseDto mpgsPayApiResponseDto = mpgsService.retrieveTransaction(paymentRequestDto.getOrder().getId(),
paymentRequestDto.getTransaction().getId());
savePaymentDetails(mpgsPayApiResponseDto, sessionId);
log.info("[executePayment] Session {}: Error making payment ", sessionId);
throw new CustomException(ExceptionConstants.MPGS_CONNECTION_EXCEPTION); // code returns here
}
...
return mpgsPayApiResponseDto;
}

Recovering from HBase server failure using Async HBase client

I'm currently trying to find a way to deal with unexpected HBase failures in my application. More specifically, what I'm trying to solve is a case where my application inserts data to HBase and then HBase fails and restarts.
In order to check how my application reacts to that scenario I wrote an application that uses HBase Async client by doing a tight loop and saving the results in HBase. When I start the application I can see rows are saved into the table, if during this time I intentionally fail my HBase server and restart it the client seems to reconnect but new insertions are not saved into the table
The code looks like this:
HConnection connection = HConnectionManager.createConnection();
HBaseClient hbaseClient = new HBaseClient(connection);
IntStream.range(0, 10000)
.forEach(new IntConsumer() {
#Override
public void accept(int value) {
try {
System.out.println("in value: " + value);
Thread.sleep(2000);
Get get = new Get(Bytes.toBytes("key"));
hbaseClient.get(TableName.valueOf("testTable"), get, new ResponseHandler<Result>() {
#Override
public void onSuccess(Result response) {
System.out.println("SUCCESS");
}
#Override
public void onFailure(IOException e) {
System.out.println("FAILURE");
}
});
urlsClient.save("valuekey", "w" + value, new FailureHandler<IOException>() {
#Override
public void onFailure(IOException failure) {
System.out.println("FAILURE");
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
This is obviously just a simple test but what I'm trying to achieve is that the async client will successfully save new rows after I restarted my HBase server. What the asynchronous HBase clients prints to me if I actually print the stacktrace in the "onFailure" method is:
org.apache.hadoop.hbase.ipc.RpcClient$CallTimeoutException: Call id=303, waitTime=60096, rpcTimeout=60000
at org.apache.hadoop.hbase.ipc.AsyncRpcChannel.cleanupCalls(AsyncRpcChannel.java:612)
at org.apache.hadoop.hbase.ipc.AsyncRpcChannel$1.run(AsyncRpcChannel.java:119)
at io.netty.util.HashedWheelTimer$HashedWheelTimeout.expire(HashedWheelTimer.java:581)
at io.netty.util.HashedWheelTimer$HashedWheelBucket.expireTimeouts(HashedWheelTimer.java:655)
at io.netty.util.HashedWheelTimer$Worker.run(HashedWheelTimer.java:367)
at java.lang.Thread.run(Thread.java:745)
And so my questions are:
How should one deal with a situation like I mentioned using the specified async client?
If this async client is no longer relevant could someone suggest a different async client that can perform asynchronous puts? I tried the BufferedMutator but it does not seem to actually flush any contents but just fails with the following java.lang.IllegalAccessError: tried to access method com.google.common.base.Stopwatch.<init>()V from class org.apache.hadoop.hbase.zookeeper.MetaTableLocator (but this gets a little off topic so I wont expand anymore)
Thanks
It's been quite a long time since I asked this question but I ended up using the HBase high availability instead of finding a way to solve it with code

RESTEasy JSON Exception Response: Send list of objects

I have web client (HTML5) and backend server based on RESTEasy webservices and session beans. In my server side code I am iterating over list of objects and per object i am executing some business logic:
List<TestTO> failedTestList = new ArrayList<TestTO>();
for (TestTO testTO : testTOList) {
try {
// some weired business logic :P
} catch (Exception e) {
logger.error("Unable to create data -" + e.getMessage());
failedTestList.add(testTO);
}
}
if (!failedTestList.isEmpty()) {
// throw custom exception embedded with failed TO list
}
I have written custome exception handlers, to catch exceptions and return proper response back to client. This class looks like:
public class CustomExceptionHandler implements ExceptionMapper<CustomException> {
public CustomException getCustomErrorCode(final CustomException customException) {
// Some logic to get cause and set error code
return customException;
}
#Override
public Response toResponse(final CustomException customException) {
return Response.serverError().entity(
"{\"Error Code\":\"" + getCustomErrorCode(customException).getErrorCode() + "\", "
+ "\"Error Message\":\"" + customException.getLocalizedMessage() + "\"}").build();
}
}
I am thinking of an option to send this failed TO list back to client, so that it can understand processing of which objects got failed. I was going through different articles, but could not find anything which fits my requirement.
Please give me an idea and link to reference, on how to implement such requirement. Please note that, my client expects response in JSON format. Please let me know, if you require more information.
Thanks.

The Best Way to Debug Retrofit Error Messages

I'm new to Retrofit. I have used Volley, and I kind of like Retrofit. I was just about to select Retrofit when I ran into this very non-descriptive error message when trying to do a POST.
Exception in thread "main" retrofit.RetrofitError
at retrofit.RetrofitError.httpError(RetrofitError.java:37)
at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:413)
at retrofit.RestAdapter$RestHandler.invoke(RestAdapter.java:282)
at myapi.api.$Proxy7.logon(Unknown Source)
at myapi.api.TestDriver.main(TestDriver.java:94)
Well, I must say that this type of error message is about as useful as a warm jacket in the Sahara.
Does anyone even know where to begin with debugging this type of message? I really am not about to delegate to a REST api that does not provide useful error messages.
You probably want to add a catch clause to TestDriver.main:
try {
service.logon();
} catch (RetrofitError e) {
System.out.println(e.getResponse().getStatus());
}
Create a custom ErrorHandler for Retrofit.
I found that catching the error didn't provide a whole lot of extra information but creating a custom ErrorHandler for Retrofit allowed me to dig deeper into the actual error, like so:
class MyErrorHandler implements ErrorHandler {
#Override public Throwable handleError(RetrofitError cause) {
Response r = cause.getResponse();
if (r != null && r.getStatus() == 401) {
return new UnauthorizedException(cause);
}
return cause;
}
}
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("https://api.github.com")
.setErrorHandler(new MyErrorHandler())
.setLogLevel(RestAdapter.LogLevel.FULL) // Do this for development too.
.build();
From the Custom Synchronous Error Handling section on Retrofit Page.
Set the Log Level to FULL as well, as shown in above config code.
Unfortunately RetrofitError (1.6.1) was tricky. 401's made getResponse() always return null which made it hard to tell if its a connection issue or authentication issue. At least for me, I had to look at the message to get the 401 error. Hopefully this helps someone else trying to do something similar.
public class RetrofitErrorHandler implements ErrorHandler {
#Override
public Throwable handleError(RetrofitError cause) {
if (cause.isNetworkError()) {
if(cause.getMessage().contains("authentication")){
//401 errors
return new Exception("Invalid credentials. Please verify login info.");
}else if (cause.getCause() instanceof SocketTimeoutException) {
//Socket Timeout
return new SocketTimeoutException("Connection Timeout. " +
"Please verify your internet connection.");
} else {
//No Connection
return new ConnectException("No Connection. " +
"Please verify your internet connection.");
}
} else {
return cause;
}
}
}

data cache for odata4j

I am implementing a RESTlet service via odata4j on Android.
When running the application there is a constant flow of data, which needs to be sent to a odata server.
The following method get's the new data:
private void freshData(Data data) {
try {
dataTransmitter.sendData(data, this.ptId);
} catch (Exception ex) {
//
}
The following method sends the data to the server:
ODataJerseyConsumer c = ODataJerseyConsumer.create(serviceUrl);
public void sendData(Data data, int ptId) throws Exception {
OEntity newData = c.createEntity(entitySet)
.properties(OProperties.int32("ptID", ptID),
OProperties.double_("data", data.getDouble())))
.execute;
So far no problem. But what if the mobile connection is cut off or lags?
1) Is there way to get the status from execute() (positive send, or no mobile connection for instance).
2) If the send has failed, or is still in progress I somehow need to store the new data to send it, when the old data is out. Is there a feature in odata4j (0.8-SNAPSHOT) available I haven't found, or do I need to do this with a queue for example?
Thank you for the help!

Categories

Resources