1 package autotest.common; 2 3 4 import com.google.gwt.http.client.Request; 5 import com.google.gwt.http.client.RequestBuilder; 6 import com.google.gwt.http.client.RequestCallback; 7 import com.google.gwt.http.client.RequestException; 8 import com.google.gwt.http.client.Response; 9 import com.google.gwt.json.client.JSONException; 10 import com.google.gwt.json.client.JSONObject; 11 import com.google.gwt.json.client.JSONParser; 12 import com.google.gwt.json.client.JSONValue; 13 14 15 /** 16 * JsonRpcProxy that uses XmlHttpRequests to make requests to the server. This is the standard 17 * technique for AJAX and suffers from the usual restrictions -- Same-Origin Policy and a maximum of 18 * two simultaneous outstanding requests. 19 */ 20 class XhrJsonRpcProxy extends JsonRpcProxy { 21 protected RequestBuilder requestBuilder; 22 XhrJsonRpcProxy(String url)23 public XhrJsonRpcProxy(String url) { 24 requestBuilder = new RequestBuilder(RequestBuilder.POST, url); 25 } 26 27 @Override sendRequest(JSONObject request, final JsonRpcCallback callback)28 protected void sendRequest(JSONObject request, final JsonRpcCallback callback) { 29 try { 30 requestBuilder.sendRequest(request.toString(), new RpcHandler(callback)); 31 } 32 catch (RequestException e) { 33 notify.showError("Unable to connect to server"); 34 callback.onError(null); 35 return; 36 } 37 38 notify.setLoading(true); 39 } 40 41 private static class RpcHandler implements RequestCallback { 42 private JsonRpcCallback callback; 43 RpcHandler(JsonRpcCallback callback)44 public RpcHandler(JsonRpcCallback callback) { 45 this.callback = callback; 46 } 47 onError(Request request, Throwable exception)48 public void onError(Request request, Throwable exception) { 49 notify.setLoading(false); 50 notify.showError("Unable to make RPC call", exception.toString()); 51 callback.onError(null); 52 } 53 onResponseReceived(Request request, Response response)54 public void onResponseReceived(Request request, Response response) { 55 notify.setLoading(false); 56 57 String responseText = response.getText(); 58 int statusCode = response.getStatusCode(); 59 if (statusCode != 200) { 60 notify.showError("Received error " + Integer.toString(statusCode) + " " + 61 response.getStatusText(), 62 response.getHeadersAsString() + "\n\n" + responseText); 63 callback.onError(null); 64 return; 65 } 66 67 handleResponseText(responseText, callback); 68 } 69 } 70 handleResponseText(String responseText, JsonRpcCallback callback)71 private static void handleResponseText(String responseText, JsonRpcCallback callback) { 72 JSONValue responseValue = null; 73 try { 74 responseValue = JSONParser.parse(responseText); 75 } 76 catch (JSONException exc) { 77 JsonRpcProxy.notify.showError(exc.toString(), responseText); 78 callback.onError(null); 79 return; 80 } 81 82 JSONObject responseObject = responseValue.isObject(); 83 handleResponseObject(responseObject, callback); 84 } 85 } 86