Archive for December, 2011

December 2, 2011

Intercepting RequestFactory requests

by Stefan

With RequestContext#fire() it is possible to provide a Receiver instance (“Callback”) to handle the result of a request to the server. One could think of some use cases where the same processing should be done for all RequestFactory calls, e.g.

  • Indicate a running request, e.g. change the mouse cursor, display a status or similar.
  • Handle http error codes, e.g. session time-outs or server unavailability.
  • Handle request time-outs.

To intercept all requests made via a RequestFactory it is possible to provide a customized RequestTransport implementation. This is done during the initialization:

import com.google.gwt.core.client.GWT;
import com.google.web.bindery.event.shared.EventBus;
import com.google.web.bindery.event.shared.SimpleEventBus;
import com.google.web.bindery.requestfactory.shared.RequestTransport;

import cleancodematters.requestfactory.tutorial.client.PizzaRequestFactory;

public class CustomTransportDemo {

  public PizzaRequestFactory initializeRequestFactory() {
    
    EventBus eventBus = new SimpleEventBus();
    RequestTransport transport = new CustomRequestTransport();
    
    PizzaRequestFactory factory = GWT.create( PizzaRequestFactory.class );
    factory.initialize( eventBus, transport );
    return factory;
  }
}

CustomRequestTransport extends the DefaultRequestTransport implementation and can do the pre- and post processing for all requests. See this very basic example to change the cursor during a running request:

import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Style.Cursor;
import com.google.web.bindery.requestfactory.gwt.client.DefaultRequestTransport;
import com.google.web.bindery.requestfactory.shared.ServerFailure;

public class CustomRequestTransport extends DefaultRequestTransport {

  @Override
  public void send( String payload, TransportReceiver receiver ) {
    doBeforeSend();
    super.send( payload, wrap( receiver ) );
  }
  
  private TransportReceiver wrap( final TransportReceiver delegate ) {
    return new TransportReceiver() {
      
      public void onTransportSuccess( String payload ) {
        doOnSuccess();
        delegate.onTransportSuccess( payload );
      }
      
      public void onTransportFailure( ServerFailure failure ) {
        doOnFailure( failure );
        delegate.onTransportFailure( failure );
      }
    };
  }

  protected void doBeforeSend() {
    // Some processing before the request is send
    Document.get().getBody().getStyle().setCursor( Cursor.WAIT );
  }

  protected void doOnSuccess() {
    // Some processing on success
    Document.get().getBody().getStyle().setCursor( Cursor.DEFAULT );
  }
  
  protected void doOnFailure( ServerFailure failure ) {
    // Some processing on failure
    Document.get().getBody().getStyle().setCursor( Cursor.DEFAULT );
  }
}