What is best way to attempt multiple time same RPC call while failing RPC call?
just example: Here one case like if RPC get failed due to network connection, it will catch in onFailure(Throwable caught).
Now here it should recall same RPC again for check network connection. The maximum attempt should be 3 times only then show message to user like "Network is not established"
How can I achieve it?
Some couple of thoughts like call same rpc call in onFailure but here request become different.but I want same request have a three request and it is not good approach and I don't know if any good solution for it.
Thanks In Advance.
Use a counter in your AsynCallBack implementation. I recommend as well to use a timer before requesting the server again.
This code should work:
final GreetingServiceAsync greetingService = GWT.create(GreetingService.class);
final String textToServer = "foo";
greetingService.greetServer(textToServer, new AsyncCallback<String>() {
int tries = 0;
public void onSuccess(String result) {
// Do something
}
public void onFailure(Throwable caught) {
if (tries ++ < 3) {
// Optional Enclose the new call in a timer to wait sometime before requesting the server again
new Timer() {
public void run() {
greetingService.greetServer(textToServer, this);
}
}.schedule(4000);
}
}
});
#Jens given this answer from Google Groups.
You could transparently handle this for all your requests of a given GWT-RPC interface by using a custom RpcRequestBuilder. This custom RpcRequestBuilder would make 3 request attempts and if all 3 fail, calls the onFailure() method.
MyRemoteServiceAsync service = GWT.create(MyRemoteService.class);
((ServiceDefTarget) service).setRpcRequestBuilder(new RetryThreeTimesRequestBuilder());
The custom RequestBuilder could also fire a "NetworkFailureEvent" on the eventBus if multiple application components may be interested in that information. For example you could overlay the whole app with a dark screen and periodically try sending Ping requests to your server until network comes back online. There is also the onLine HTML 5 property you can check, but its not 100% reliable (https://developer.mozilla.org/en-US/docs/Web/API/window.navigator.onLine)
Related
I am trying to implement session timeout with help of a GWT Timer which will make a RPC call to server to check whether the session is valid or expired by using lastaccessedtime. but every time i make a RPC call it updates the lastaccessedtime (understandable as i am making a RPC call), any way i can prevent my Timer RPC call from updating the lastaccessedtime?
wrote some server side logic to get the lastaccessedtime and try to find out session is valid or not
com.google.gwt.user.client.Timer elapsedTimer;
public void onModuleLoad() {
elapsedTimer = new Timer () {
public void run() {
validateSession();
}};
//giving time delay of 1sec to call the batches
elapsedTimer.scheduleRepeating(60000);
}
public void validateSession(){
//Problem code every time i make this call it updates the last accessed time
viewService.validateSessionGWT(new AsyncCallback<ModuleData>() {
#Override
public void onFailure(Throwable e) {
//do something
}
#Override
public void onSuccess(ModuleData data) {
if(data.getSessionExpired()){
//redirect to login page
}
}
});
}
any idea how to overcome this problem or any other idea to implement Session management in GWT
NOTE: already gone through this which is similar to my approach
https://itsecrets.wordpress.com/2011/07/20/session-timeouts-with-gwt-rpc-calls/
Your GWT servlets extend the RemoteServiceServlet. So you can override processPost and add a custom last call timestamp in you http session. Every request updates this field.
I suggest to implement an abstract servlet that is extended by all your gwt servlets. Additionally you should not only set the custom last access field, but check it just before and only call the super method if everything is fine.
Then your timer and the servlet request you already have should only check this Session field.
Perhaps not the best solution but this should work.
I have a project that does 2 RPC calls and then saves the data that the user provided in tha datastore. The first RPC call works ok, but from the second I always recieve the onFailure() message. How can I determine why the onFailure() is triggered? I tried caught.getCause() but it doesn't return anything.
feedbackService.saveFeedback(email,studentName,usedTemplates,
new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
caught.getCause();
Window.alert("Failure!");
}
public void onSuccess(String result) {
Window.alert("Saved!");
}
});
Throwable instance is instance of an Exception. You can check if it is a custom Exception like this:
if (caught instanceOf CustomException){
or if you want to show the message of exception you can use the getMessage():
Window.alert("Failure: " + caught.getMessage());
GWT-rpc is not not easy to ebug if an error occurs.
The easiest part is th check if the Exception is part of StatusCodeException.
A Statuscode of 404 means, you are pointing to a wrong endpoint
0 means, that
The searver is unreachable
You don't have permissions to check, if the server is available (X-domain-request)
You can use the Chrome-Web-Inspector to bedug GWT-RPC
You should be able to see all calls from the browser to you backend.
The most common failures are because of serialization of object. You have to ensure, that all dtransferred object implement java.io.Serializable
Most of the time it will just be a server side exception being raised which fires the onFailure() method.
Try putting breakpoints on your server side. That should help you pinpoint what's going wrong.
I've been implementing a GWT application that calls a REST-service (which we're also developing). When the REST-service returns anything with a HTTP-status other than 200 I would expect the onFailure method of AsyncCallback to be called. However I can't get this to happen.
To test it further I created a test GWT app and a test servlet. The part of the GWT app that calls the service looks like this:
JsonpRequestBuilder jsonp = new JsonpRequestBuilder();
jsonp.setCallbackParam("_jsonp");
jsonp.setFailureCallbackParam("_jsonp_failure");
jsonp.requestObject(url, new AsyncCallback<JavaScriptObject>()
{
#Override
public void onFailure(Throwable caught)
{
Window.alert("Failure: " + caught.getMessage());
}
#Override
public void onSuccess(JavaScriptObject result)
{
Window.alert("Success");
}
});
The servlet-code looks like this:
public class MyRestServlet extends HttpServlet
{
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException
{
String padding = httpServletRequest.getParameter("_jsonp_failure");
httpServletResponse.setContentType("application/x+javascript");
httpServletResponse.setStatus(500);
PrintWriter out = httpServletResponse.getWriter();
out.println(padding + "({\"some\":\"json\"});");
out.close();
}
}
OnFailure eventually gets called when the request times out, but I would expect it to be called as soon as the http response arrives(if it's a failure). I guess there is something I haven't understood and I would really appreciate to get some help with this.
Thanks
According to HTML5, if there's an error loading the script, an error event should be dispatched, and GWT doesn't listen for it (because almost no browser actually fires it AFAICT).
For best browser compatibility, you'd better always send a 200 status, but then call the failure callback (or in other words, return an error state/condition, rather than throw an exception).
Also, the argument to the failure callback is expected to be a string (will be the message of the exception).
From the server code where you call the REST service, throw an exception yourself if the response is something other than 200 (by writing code to check the response yourself). This way it will persist to the client side as an error and onFailure will be called in client side.
In GWT's mind currently nothing went wrong. It sent a request, got some result did not matter what, the call was successful. It does call the onFailure on a timeout because something did go wrong with the request "physically", and GWT persisted the exception to the client side as a failure.
I've built the following simple server, and I'm stress testing it using ab.
If I run ab making 3000 total request (300 concurrent) it works. If I run it again, it shows me:
apr_socket_connect(): Connection reset by peer (54)
And If after this error I try to make a single request with curl without restarting the server, it works. If I run again ab it shows the same error.
It seems that it can't handle too many concurrent connections. Below the code:
public static void main(String[] args) throws Exception {
ServerBootstrap bootstrap = new ServerBootstrap(
new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
#Override
public ChannelPipeline getPipeline() throws Exception {
return Channels.pipeline(new StringEncoder(), new MyServerHandler());
}
});
bootstrap.bind(new InetSocketAddress(9090));
System.out.println("Running");
}
Here is the handler:
public class MyServerHandler extends SimpleChannelUpstreamHandler {
private static AtomicLong request = new AtomicLong();
#Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
ChannelFuture channelFuture = e.getChannel().write("This is request #" + request.incrementAndGet() + "\n");
channelFuture.addListener(ChannelFutureListener.CLOSE);
}
#Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
throws Exception {
System.out.println(e.getCause());
e.getChannel().close();
}
}
As you see it's very simple, it just shows the total number of requests handled.
Any tips?
Thanks
'Connection reset by peer' usually means you have written to a connection that has already been closed by the other end. In other words, an application protocol error. You get the error itself on a subsequent read or write.
I don't immediately see anything wrong, but you could try the following to try to get more information:
Override channelClosed and output something so that you're 100% sure that Netty is at least trying to close the channel.
Use jvisualvm to have a look at the JVM running your server; you should be able to see the threads and whether they're active or not.
Write something to System.out server-side on channelConnected so you know that your connections have made it that far (especially for the 2nd run).
When you run ab the second time, is there an error for every connection attempt, or just for some?
What I find odd is that it seems to work the first time, but not thereafter. Keep in mind that this may not be a Netty - or even a JVM - issue, but rather the OS somehow limiting the the connection attempts.
I have done some tests with my own Netty test server, and found that starting large batches concurrent connections will produce an unpredictable outcome (most will connect, some will fail, but always a different ratio). As of yet I haven't figure out why that is (yet), but I suspect it is my OS refusing the connections rather than Netty.
I am writing some interface for users to collect data and send to a server. I went for GWT for various reasons.
Now, when I try to call my server:
String url = "http://127.0.0.1:3000/data/collection.xml";
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url));
Request request = builder.sendRequest(data, new RequestCallback() {
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
result.setText("SUCCESS!");
} else {
result.setText("ERROR with code: " + response.getStatusCode());
My server gets the request (a POST with some data) but I get ERROR with code: 0 (!) all the time. I guess this has to do with SOP. I read lots about this SOP but I am even more confused now. I tried to follow this tutorial but that's using a different approach (I managed to adapt it to issue GET calls only, but return objects are always null).
Can anyone point me into the right direction? thanks
You can not call any service from another server because of SOP. What you can do, you can use your original server as proxy to other servers.. I would recommend you to read this tutorial.