View Javadoc

1   package org.appfuse.webapp.client.application.base.request;
2   
3   import com.google.web.bindery.event.shared.EventBus;
4   import com.google.web.bindery.requestfactory.shared.RequestTransport;
5   import com.google.web.bindery.requestfactory.shared.ServerFailure;
6   
7   /**
8    * Wraps {@link RequestTransport} to post events as requests are sent and
9    * received.
10   */
11  public class EventSourceRequestTransport implements RequestTransport {
12      private final EventBus eventBus;
13      private final RequestTransport wrapped;
14  
15      public EventSourceRequestTransport(EventBus eventBus) {
16          this(eventBus, new CustomDefaultRequestTransport(eventBus));
17      }
18  
19      private EventSourceRequestTransport(EventBus eventBus, RequestTransport wrapped) {
20          this.eventBus = eventBus;
21          this.wrapped = wrapped;
22      }
23  
24      public void send(String payload, final TransportReceiver receiver) {
25          TransportReceiver myReceiver = new TransportReceiver() {
26  
27              @Override
28              public void onTransportSuccess(String payload) {
29                  try {
30                      receiver.onTransportSuccess(payload);
31                  } finally {
32                      eventBus.fireEvent(new RequestEvent(RequestEvent.State.RECEIVED));
33                  }
34              }
35  
36              @Override
37              public void onTransportFailure(ServerFailure failure) {
38                  try {
39                      receiver.onTransportFailure(failure);
40                  } finally {
41                      eventBus.fireEvent(new RequestEvent(RequestEvent.State.RECEIVED));
42                  }
43              }
44          };
45  
46          try {
47              wrapped.send(payload, myReceiver);
48          } finally {
49              eventBus.fireEvent(new RequestEvent(RequestEvent.State.SENT));
50          }
51      }
52  }