How to intercept the onSuccess() method in GWT - gwt

I need to do method interception for the onSuccess method in GWT.
I need to add some code before and after the calling of the onSuccess method in GWT? (I have many calls to the onSuccess method and I need to do this dynamically)
EDIT:
I need to add a progress bar in the right corner of the screen, that appears when the code enters the onsuccess method and disappears on the exit of onsuccess method.

From a visual perspective
void onSuccess(Value v) {
showProgressBar();
doLotsOfWork(v);
hideProgressBar();
}
will be a no-op. Browsers typically wait for event handlers to finish executing before re-rending the DOM. If the doLotsOfWork() method takes a noticeable amount of time to execute (e.g. >100ms) the user will notice the browser hiccup due to the single-threaded nature of JavaScript execution.
Instead, consider using an incrementally-scheduled command to break the work up. It would look roughly like:
void onSuccess(Value v) {
showProgressBar();
Scheduler.get().scheduleIncremental(new RepeatingCommand() {
int count = 0;
int size = v.getElements().size();
public boolean execute() {
if (count == size) {
hideProgressBar();
return false;
}
processOneElement(v.getElements().get(count++));
setProgressBar((double) count / size);
return true;
}
});
}
By breaking the work across multiple pumps of the browser's event loop, you avoid the situation where the webapp becomes non-responsive if there's a non-trivial amount of work to do.

Well, it is a generic non-functional requirement, I have done some research on this item, I have implemented a solution that Thomas Broyer has suggested on gwt group.. This solution has distinct advantage over other suggested solutions, You dont have to change your callback classes, what you have to do is just add a line of code after creation of async gwt-rpc service...
IGwtPersistenceEngineRPCAsync persistenceEngine = GWT.create(IGwtPersistenceEngineRPC.class);
((ServiceDefTarget) persistenceEngine).setRpcRequestBuilder(new ProgressRequestBuilder());
import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.rpc.RpcRequestBuilder;
public class ProgressRequestBuilder extends RpcRequestBuilder {
private class RequestCallbackWrapper implements RequestCallback {
private RequestCallback callback;
RequestCallbackWrapper(RequestCallback aCallback) {
this.callback = aCallback;
}
#Override
public void onResponseReceived(Request request, Response response) {
Log.debug("onResposenReceived is called");
// put the code to hide your progress bar
callback.onResponseReceived(request, response);
}
#Override
public void onError(Request request, Throwable exception) {
Log.error("onError is called",new Exception(exception));
// put the code to hide your progress bar
callback.onError(request, exception);
}
}
#Override
protected RequestBuilder doCreate(String serviceEntryPoint) {
RequestBuilder rb = super.doCreate(serviceEntryPoint);
// put the code to show your progress bar
return rb;
}
#Override
protected void doFinish(RequestBuilder rb) {
super.doFinish(rb);
rb.setCallback(new RequestCallbackWrapper(rb.getCallback()));
}
}

You cant do that. The rpc onSuccess() method runs asynchronously (in other words, depends on the server when it completes, the app doesnt wait for it). You could fire code immediately after the rpc call which may/ may not complete before the onSuccess for RPC calls.
Can you explain with an eg why exactly do u want to do that? Chances are you might have to redesign the app due to this async behavior, but cant say till you provide a use case. Preferably any Async functionality should be forgotten after the rpc call, and actioned upon only in the onSuccess.

Related

Async method in Spring Boot

I have a problem with sending email with method annotated as #Async.
Firstly, I am not sure if it is possible to work as I want so I need help with explanation.
Here is what am doing now:
In main method i have annotation
#EnableAsync(proxyTargetClass = true)
Next I have AsyncConfig class
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import java.util.concurrent.Executor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
#Configuration
public class AsyncConfig extends AsyncConfigurerSupport {
#Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(2);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("email-");
executor.initialize();
return executor;
}
}
Of course, its rest application so i have controller, service etc, looks normally, nothing special
My async method looks like this:
#Async
public void sendEmail() throws InterruptedException {
log.info("Sleep");
Thread.sleep(10000L);
//method code
log.info("Done");
}
I executing this method in another service method:
#Override
public boolean sendSystemEmail() {
try {
this.sendEmail();
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("pending sendEmail method");
return true;
}
Now what I want archive is to ignore executing sendEmail() function and execute return true; meanwhile function sendEmail() will be executing in another Thread. Of course it doesn't work now as I want. Unfortunately.
Note that I am new into async programming, so I have lack of knowledge in some parts of this programming method.
Thanks for any help.
First – let’s go over the rules – #Async has two limitations:
it must be applied to public methods only
self-invocation – calling the async method from within the same class – won’t work
The reasons are simple – the method needs to be public so that it can be proxied. And self-invocation doesn’t work because it bypasses the proxy and calls the underlying method directly.
http://www.baeldung.com/spring-async

How to save/edit object and refresh datagrid using request factory

I started with dynatableref example of Request Factory. I read request factory document. but still I am unclear about life cycle or flow of client to server.
I want to make a call to server. Insert data and update grid also. It is easy with RPC call. But I don't understand how to do with Request Factory.
This is one method of request factory. It call persist method automatically of server. It refresh grid also automatically. can I anybody tell how is it working?
context.fire(new Receiver<Void>() {
#Override
public void onConstraintViolation(Set<ConstraintViolation<?>> errors) {
// Otherwise, show ConstraintViolations in the UI
dialog.setText("Errors detected on the server");
editorDriver.setConstraintViolations(errors);
}
#Override
public void onSuccess(Void response) {
// If everything went as planned, just dismiss the dialog box
dialog.hide();
}
});
I want to edit some data in to grid also. is this method help me? or I have to write other method.
I wrote other method like
requestFactory.schoolCalendarRequest().savePerson(personProxy).fire(new Receiver<PersonProxy>() {
#Override
public void onSuccess(PersonProxy person) {
// Re-check offset in case of changes while waiting for data
dialog.hide();
}
});
This is not refreshing grid. why?
The flow client-server of the RuequestFactory is similar to RPC or any XMLHTTP request
1) You invoke a remote method on the server.
2) You receive a response in the Receiver object (which is the Callback object). In onSeccess Method you get the returned object if everything went well. onFailure you get an error if something went wrong.
So to populate the Person table from data retrieved from the server the code should look something like this
requestFactory.schoolCalendarRequest().getPersonList(param1).fire(new Receiver<List<PersonProxy>>() {
#Override
public void onSuccess(List<PersonProxy> personList) {
personTable.getDataProvider().setList(personList);
}
});
Now when you edit a Person (e.g. name ) it's important to initialize and use the same RequestContext until you call fire on the request. So the part where you update the Person's name should look something like this
column.setFieldUpdater(new FieldUpdater<Person, String>() {
#Override
public void update(PersonProxy personProxy, String value) {
RequestContext requestContext = requestFactory.schoolCalendarRequest()
PersonProxy personProxy= requestContext.edit(personProxy);
personProxy.setName(value);
requestFactory.schoolCalendarRequest().savePerson(personProxy).fire(new Receiver<PersonProxy>() {
#Override
public void onSuccess(PersonProxy person) {
//Do something after the update
}
});
}
});
The interaction with the RequestFactory should be placed in a Presenter, so you should probably consider implementing a MVP pattern.

GWT Button Click Enable/Disable Pattern -- GwtEvent assertLive() in dev mode

To avoid users clicking repetitively on the same button and by the same token send multiple requests to server, I have used the following pattern:
In button ClickHandler.onClick, disable the button.
In call back, re-enable the button.
See pattern in code below. The "rpcCall" function below basically is the core implementation of the Button onClick(final ClickEvent event).
private void rpcCall(final ClickEvent event)
{
final AsyncCallback<Void> callback = new AsyncCallback<Void>()
{
#Override
public void onSuccess(Void result)
{
final Button source = (Button) event.getSource(); // Dev mode isLive assertion failure.
source.setEnabled(true);
// Process success...
}
#Override
public void onFailure(Throwable caught)
{
final Button source = (Button) event.getSource();
source.setEnabled(true);
// Process error...
}
};
// Disable sender.
final Button source = (Button) event.getSource();
source.setEnabled(false);
// RPC call.
final RpcAsync rpcAsync = getRpcAsync();
RpcAsync.rpcCall(..., callback);
}
I just noticed a "This event has already finished being processed by its original handler manager, so you can no longer access it" exception caused by an isLive assertion failure in dev mode when the onSuccess async function calls event.getSource().
It seems to work in production/javascript mode though.
This dev mode assertion failure makes me question this pattern.
Is it a good pattern? Why do I get the exception only in dev mode? What would be a better pattern?
Obviously, I could bypass the call to event.getSource() by passing the source Button as an argument of the rpc wrapper call function, but it seems redundant with the event object already carrying such a reference.
Historically, the way you got the event object in IE was to use window.event, which only lasted the time to process the event. GWT's Event object therefore had to put guards so you're discouraged to keep a hold on an event instance, as it could suddenly reflect another event being processed, or no event at all (weird!)
Fortunately, Microsoft has since fixed their browser, and this is why it works when you test it (I bet you didn't test in IE6 ;-) ).
The correct way to handle that situation is to extract all the data you need from the event and keep them in final variables:
private void rpcCall(final ClickEvent event)
{
final Button source = (Button) event.getSource();
final AsyncCallback<Void> callback = new AsyncCallback<Void>()
{
#Override
public void onSuccess(Void result)
{
source.setEnabled(true);
// Process success...
}
#Override
public void onFailure(Throwable caught)
{
source.setEnabled(true);
// Process error...
}
};
// Disable sender.
source.setEnabled(false);
// RPC call.
final RpcAsync rpcAsync = getRpcAsync();
RpcAsync.rpcCall(..., callback);
}

How to call GWT client code from within a GQuery event handler?

I'm learning GQuery. It seems cool, but also a little confusing.
I have the following GWT client code. The selected item fades out, nicely. But the delete method never gets called. There is no error. It's very odd.
Is it even possible to call non-GQuery functions from inside a GQuery method?
delete.addClickHandler( new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
$(myIndicator).fadeOut(500, new Function(){
#Override
public void f() {
super.f();
delete();
}
});
}
});
And the delete method is:
private void delete() {
removeFromParent();
ruleDeleteRequestEvent.fire(new RuleDeleteRequestEvent(ruleBinder.getModel()));
}
Do not call super.f(), if so the default implementation of Function.f() will throw an Exception preventing the next line be executed (take a look to the source code) .

GWT Callbacks Implementation

I'm maintaining software that contains a bunch of user groups. When an Admin clicks "Remove" on a user of a group, two things should happen:
delete the group member (involves updating cache, db, etc.)
reload a list of group members (the user sees this list when he/she deletes a user)
It turns out that #2 finishes before #1 - race condition. As a result, I want to add a callback so that #2 does not execute until #1 is successful.
Is this code acceptable for GWT to ensure #2 occurs before #1?
doTask1();
GWT.runAsync(new RunAsyncCallback()
{
public void onFailure(final Throwable reason)
{
}
public void onSuccess()
{
doTask2();
}
});
GWT#runAsync() is used for GWT's "code splitting" feature, which allows deferred loading of code (and other runtime resources) until they are needed. You need to use GWT's asynchronous operation patterns (i.e. AsyncCallback or Command) to pass a callback to doTask1() that is invoked once the asynchronous operations there complete. For example, if doTask1() executes a GWT RPC method:
public void doTask1(final Command onCompletion) {
myRpcService.doTask1(new AsyncCallback<Void>() {
#Override
public void onFailure(Throwable caught) {
// Error handling
}
#Override
public void onSuccess(Void ignored) {
onCompletion.execute();
}
});
}
public void doTask2() {
// Perform task 2
}
public void doTasks1And2() {
doTask1(new Command() {
#Override
public void execute() {
doTask2();
}
});
}
No, you can still have a race condition with that style of control flow. Instead, you want something like this:
doTask1(new MyCallback() {
public void onTask1Complete() {
doTask2();
}
}
doTask1() needs to accept a callback so that once it is complete, it will execute the next operation.
To see why, let's assume that both doTask1() and doTask2() are making HTTP calls. You have no guarantee what order the server might receive these two connections unless you wait until the doTask1()'s request has returned . In your example code, you make the request in doTask1() (which immediately returns while the request is asynchronously made), and then make the second call without waiting for the first.