List of usage examples for com.google.gwt.http.client RequestCallback RequestCallback
RequestCallback
From source file:com.textquo.dreamcode.client.publicstores.GlobalStore.java
License:Open Source License
/** * Add new object.//from w ww . j a v a 2 s .c om * Server stores object with id generated by a sharded counter (if not given) * * @param callback */ public void add(String type, String id, String jsonObject, final DreamcodeCallback callback) { String url = Routes.DREAMCODE + Routes.COLLECTIONS + "?type=" + type + "&id=" + id; RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url); try { builder.setHeader("content-type", "application/json"); builder.sendRequest(jsonObject, new RequestCallback() { public void onResponseReceived(com.google.gwt.http.client.Request request, com.google.gwt.http.client.Response response) { String jsonResponse = response.getText(); if (response.getStatusCode() == com.google.gwt.http.client.Response.SC_OK) { callback.success(jsonResponse); } else { callback.failure(new Throwable("Error: " + response.getStatusCode())); } } public void onError(com.google.gwt.http.client.Request request, Throwable throwable) { callback.failure(throwable); } }); } catch (RequestException e) { callback.failure(new Throwable(e.getMessage())); } // TODO: Make this code below work: // ClientResource resource = new ClientResource(Routes.DREAMCODE + Routes.COLLECTIONS); // resource.setOnResponse(new Uniform() { // public void handle(Request request, Response response) { // try { // Status status = response.getStatus(); // if (!Status.isError(status.getCode())) { // String jsonResponse = response.getEntity().getText(); // callback.success(jsonResponse); // } else { // callback.failure(new Throwable("Error: " + status.getCode())); // } // } catch (Exception e) { // callback.failure(new Throwable(e.getMessage())); // } // } // }); // JsniHelper.consoleLog("Adding object id=" + id + " type=" + type + " data=" + jsonObject); // if(JsonHelper.isValid(jsonObject)){ // resource.getReference().addQueryParameter("type", type); // resource.getReference().addQueryParameter("id",id); // resource.post(jsonObject, MediaType.APPLICATION_JSON); // } else { // callback.failure(new Throwable("Invalid JSON object")); // } }
From source file:com.totsp.gwittir.rest.client.transports.HTTPTransport.java
License:Open Source License
/** Executes a request and handles the pre and post hooks * * @param builder the initial builder//from www . ja v a 2 s . c om * @param callback the request callback to pass to the final builder * @return a RequestControl implementation to return back out. */ protected XHRRequestControl doRequest(RequestBuilder builder, final RequestCallback callback) { doPreHook(builder); RequestCallback innerCallback = new RequestCallback() { public void onResponseReceived(Request request, Response response) { response = doPostHook(response); callback.onResponseReceived(request, response); } public void onError(Request request, Throwable exception) { callback.onError(request, exception); } }; builder.setCallback(innerCallback); try { return new XHRRequestControl(builder.send()); } catch (RequestException e) { callback.onError(null, e); return new XHRRequestControl(null); } }
From source file:com.vaadin.client.communication.Heartbeat.java
License:Apache License
/** * Sends a heartbeat to the server/*from w ww. j a va2s .c o m*/ */ public void send() { timer.cancel(); final RequestBuilder rb = new RequestBuilder(RequestBuilder.POST, uri); final RequestCallback callback = new RequestCallback() { @Override public void onResponseReceived(Request request, Response response) { int status = response.getStatusCode(); if (status == Response.SC_OK) { connection.getConnectionStateHandler().heartbeatOk(); } else { // Handler should stop the application if heartbeat should // no longer be sent connection.getConnectionStateHandler().heartbeatInvalidStatusCode(request, response); } schedule(); } @Override public void onError(Request request, Throwable exception) { // Handler should stop the application if heartbeat should no // longer be sent connection.getConnectionStateHandler().heartbeatException(request, exception); schedule(); } }; rb.setCallback(callback); try { getLogger().fine("Sending heartbeat request..."); rb.send(); } catch (RequestException re) { callback.onError(null, re); } }
From source file:com.vaadin.terminal.gwt.client.ApplicationConnection.java
License:Open Source License
/** * Sends an asynchronous or synchronous UIDL request to the server using the * given URI.//from w w w .j ava 2 s .c o m * * @param uri * The URI to use for the request. May includes GET parameters * @param payload * The contents of the request to send * @param synchronous * true if the request should be synchronous, false otherwise */ protected void doUidlRequest(final String uri, final String payload, final boolean synchronous) { if (!synchronous) { RequestCallback requestCallback = new RequestCallback() { public void onError(Request request, Throwable exception) { showCommunicationError(exception.getMessage()); endRequest(); } public void onResponseReceived(Request request, Response response) { VConsole.log("Server visit took " + String.valueOf((new Date()).getTime() - requestStartTime.getTime()) + "ms"); int statusCode = response.getStatusCode(); switch (statusCode) { case 0: showCommunicationError("Invalid status code 0 (server down?)"); endRequest(); return; case 401: /* * Authorization has failed. Could be that the session * has timed out and the container is redirecting to a * login page. */ showAuthenticationError(""); endRequest(); return; case 503: // We'll assume msec instead of the usual seconds int delay = Integer.parseInt(response.getHeader("Retry-After")); VConsole.log("503, retrying in " + delay + "msec"); (new Timer() { @Override public void run() { decrementActiveRequests(); doUidlRequest(uri, payload, synchronous); } }).schedule(delay); return; } if ((statusCode / 100) == 4) { // Handle all 4xx errors the same way as (they are // all permanent errors) showCommunicationError( "UIDL could not be read from server. Check servlets mappings. Error code: " + statusCode); endRequest(); return; } // for(;;);[realjson] final String jsonText = response.getText().substring(9, response.getText().length() - 1); handleJSONText(jsonText); } }; try { doAsyncUIDLRequest(uri, payload, requestCallback); } catch (RequestException e) { VConsole.error(e); endRequest(); } } else { // Synchronized call, discarded response (leaving the page) SynchronousXHR syncXHR = (SynchronousXHR) SynchronousXHR.create(); syncXHR.synchronousPost(uri + "&" + PARAM_UNLOADBURST + "=1", payload); /* * Although we are in theory leaving the page, the page may still * stay open. End request properly here too. See #3289 */ endRequest(); } }
From source file:de.kp.ames.search.client.http.ConnectionManager.java
License:Open Source License
/** * @param url/*from w w w . j a v a2 s . com*/ * @param callback */ public void sendGetRequest(final String url, final HashMap<String, String> headers, final ConnectionCallback callback) { RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url)); builder.setTimeoutMillis(CoreGlobals.CONNECTION_TIMEOUT); /* * Set header parameters */ if (headers.isEmpty() == false) { Set<String> keys = headers.keySet(); for (String key : keys) { builder.setHeader(key, headers.get(key)); } } /* * Set request callback */ builder.setCallback(new RequestCallback() { public void onResponseReceived(Request request, Response response) { SC.logWarn("======> cm.RequestCallback.onResponseReceived"); if (STATUS_CODE_OK == response.getStatusCode()) { handleSuccess(response, callback); } else { handleFailure(response, callback); } } public void onError(Request request, Throwable exception) { SC.logWarn("======> cm.RequestCallback.onError"); if (exception instanceof RequestTimeoutException) { handleTimeout(exception, callback); } else { handleError(exception, callback); } } }); try { builder.send(); } catch (RequestException e) { handleError(e, callback); } }
From source file:de.kp.ames.search.client.http.ConnectionManager.java
License:Open Source License
/** * @param url/*from w ww .j a va 2 s . c om*/ * @param requestData * @param callback */ public void sendPostRequest(final String url, final HashMap<String, String> headers, final String requestData, final ConnectionCallback callback) { RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url)); builder.setTimeoutMillis(CoreGlobals.CONNECTION_TIMEOUT); /* * Set header parameters */ if (headers.isEmpty() == false) { Set<String> keys = headers.keySet(); for (String key : keys) { builder.setHeader(key, headers.get(key)); } } /* * Set request data */ if (requestData != null) builder.setRequestData(requestData); /* * Set request callback */ builder.setCallback(new RequestCallback() { public void onResponseReceived(Request request, Response response) { if (STATUS_CODE_OK == response.getStatusCode()) { SC.logWarn("====> cm.onResponseReceived"); handleSuccess(response, callback); } else { handleFailure(response, callback); } } public void onError(Request request, Throwable exception) { if (exception instanceof RequestTimeoutException) { handleTimeout(exception, callback); } else { handleError(exception, callback); } } }); try { builder.send(); } catch (RequestException e) { handleError(e, callback); } }
From source file:de.kp.ames.web.client.core.http.ConnectionManager.java
License:Open Source License
/** * @param url//from www.j av a2 s . c o m * @param callback */ public void sendGetRequest(final String url, final HashMap<String, String> headers, final ConnectionCallback callback) { RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url)); builder.setTimeoutMillis(GuiConstants.CONNECTION_TIMEOUT); /* * Set header parameters */ if (headers.isEmpty() == false) { Set<String> keys = headers.keySet(); for (String key : keys) { builder.setHeader(key, headers.get(key)); } } /* * Set request callback */ builder.setCallback(new RequestCallback() { public void onResponseReceived(Request request, Response response) { if (STATUS_CODE_OK == response.getStatusCode()) { handleSuccess(response, callback); } else { handleFailure(response, callback); } } public void onError(Request request, Throwable exception) { if (exception instanceof RequestTimeoutException) { handleTimeout(exception, callback); } else { handleError(exception, callback); } } }); try { builder.send(); } catch (RequestException e) { handleError(e, callback); } }
From source file:de.kp.ames.web.client.core.http.ConnectionManager.java
License:Open Source License
/** * @param url/*from www. j a v a 2 s .c om*/ * @param requestData * @param callback */ public void sendPostRequest(final String url, final HashMap<String, String> headers, final String requestData, final ConnectionCallback callback) { RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url)); builder.setTimeoutMillis(GuiConstants.CONNECTION_TIMEOUT); /* * Set header parameters */ if (headers.isEmpty() == false) { Set<String> keys = headers.keySet(); for (String key : keys) { builder.setHeader(key, headers.get(key)); } } /* * Set request data */ if (requestData != null) builder.setRequestData(requestData); /* * Set request callback */ builder.setCallback(new RequestCallback() { public void onResponseReceived(Request request, Response response) { if (STATUS_CODE_OK == response.getStatusCode()) { handleSuccess(response, callback); } else { handleFailure(response, callback); } } public void onError(Request request, Throwable exception) { if (exception instanceof RequestTimeoutException) { handleTimeout(exception, callback); } else { handleError(exception, callback); } } }); try { builder.send(); } catch (RequestException e) { handleError(e, callback); } }
From source file:de.lilawelt.zmachine.client.machine.Memory.java
License:Open Source License
public void initialize(ZUserInterface ui, String storyFile) { Log.debug("Trying to load story from " + storyFile); final PopupPanel p = new PopupPanel(); p.add(new HTML("Please wait, loading game...")); p.center();// www. j a v a 2 s . co m p.show(); zui = ui; RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(storyFile)); try { builder.sendRequest(null, new RequestCallback() { public void onError(Request request, Throwable exception) { // Couldn't connect to server (could be timeout, SOP violation, etc.) Log.debug("Server connect failed"); zui.fatal("Could not connect to server: " + exception.getMessage()); } public void onResponseReceived(Request request, Response response) { if (200 == response.getStatusCode()) { String story = response.getText(); Log.debug("Text length: " + story.length()); //String[] tokens = story.split(" "); dataLength = story.length(); Log.debug("Initial length: " + dataLength); data = new byte[dataLength]; int count = 0; for (int i = 0; i < dataLength - 3; i++) { char e1 = story.charAt(i++); //if ( i < 100 ) //Log.debug("Charvalue at pos "+i+": "+e1); if (e1 == '\n' || e1 == '\r') { e1 = story.charAt(i++); if (e1 == '\n' || e1 == '\r') { e1 = story.charAt(i++); } } e1 = (char) tab.indexOf(e1); char e2 = story.charAt(i++); if (e2 == '\n') { e2 = story.charAt(i++); } e2 = (char) tab.indexOf(e2); char e3 = story.charAt(i++); if (e3 == '\n') { e3 = story.charAt(i++); } e3 = (char) tab.indexOf(e3); char e4 = story.charAt(i); if (e4 == '\n') { e4 = story.charAt(++i); } e4 = (char) tab.indexOf(e4); //Log.debug("Values: "+e1+" "+e2+" "+e3+" "+e4); byte c1 = (byte) ((e1 << 2) + (e2 >> 4)); byte c2 = (byte) (((e2 & 15) << 4) + (e3 >> 2)); byte c3 = (byte) (((e3 & 3) << 6) + e4); //c1 = (byte) ( e2 >> 4); data[count++] = c1; if (e3 != 64) data[count++] += c2; if (e4 != 64) data[count++] += c3; } /* data = new byte[dataLength]; int count = 0; for ( int i = 0; i < dataLength; i++ ) { char c = story.charAt(i); if ( (int) c == 127 ) { i++; if ( (int) story.charAt(i) == 127 ) { i++; data[count] = 127; data[count] += 127; } else { data[count] = 127; } data[count] += story.charAt(i); } else { data[count] = (byte) c; } //Log.debug("Text item: "+(int)c); count++; } */ dataLength = count; Log.debug("Loaded " + count + " bytes of story."); /* Log.debug("byte0: "+fetchByte(0)); Log.debug("byte1: "+fetchByte(1)); for ( int i = 0; i < dataLength; i++ ) { if ( i != fetchByte(i)) Log.debug("Data "+i+": "+fetchByte(i)); } */ p.hide(); Machine.get().start(); } else { Log.debug("Server returned error on load: " + response.getText()); zui.fatal("Server returned error on load: " + response.getText()); } } }); } catch (RequestException e) { // Couldn't connect to server zui.fatal("I/O error loading storyfile."); } Log.debug("Initialized memory"); }
From source file:ecc.gwt.warning.client.JsonRpc.java
License:Apache License
/** * Executes a json-rpc request./*from w ww . j a v a 2s.co m*/ * * @param url * The location of the service * @param username * The username for basic authentification * @param password * The password for basic authentification * @param params * An array of objects containing the parameters * @param callback * A callbackhandler like in gwt's rpc. */ public void request(final String url, String username, String password, Map paramMap, boolean isStream, final AsyncCallback callback) { HashMap request = new HashMap(); request.putAll(paramMap); //request.put("id", new Integer(requestSerial++)); if (username == null) if (requestUser != null) username = requestUser; if (password == null) if (requestPassword != null) password = requestPassword; RequestCallback handler = new RequestCallback() { public void onResponseReceived(Request request, Response response) { try { String resp = response.getText(); if (resp.equals("")) throw new RuntimeException("empty"); HashMap reply = (HashMap) decode(resp); if (reply == null) { RuntimeException runtimeException = new RuntimeException("parse: " + response.getText()); fireFailure(runtimeException); callback.onFailure(runtimeException); } if (isErrorResponse(reply)) { RuntimeException runtimeException = new RuntimeException("error: " + reply.get("error")); fireFailure(runtimeException); callback.onFailure(runtimeException); } else if (isSuccessfulResponse(reply)) { callback.onSuccess(reply.get("result")); } else { RuntimeException runtimeException = new RuntimeException("syntax: " + response.getText()); fireFailure(runtimeException); callback.onFailure(runtimeException); } } catch (RuntimeException e) { fireFailure(e); callback.onFailure(e); } finally { decreaseRequestCounter(); } } public void onError(Request request, Throwable exception) { try { if (exception instanceof RequestTimeoutException) { RuntimeException runtimeException = new RuntimeException("timeout"); fireFailure(runtimeException); callback.onFailure(runtimeException); } else { RuntimeException runtimeException = new RuntimeException("other"); fireFailure(runtimeException); callback.onFailure(runtimeException); } } catch (RuntimeException e) { fireFailure(e); callback.onFailure(e); } finally { decreaseRequestCounter(); } } private boolean isErrorResponse(HashMap response) { return response.get("error") != null && response.get("result") == null; } private boolean isSuccessfulResponse(HashMap response) { return response.get("error") == null && response.containsKey("result"); } }; increaseRequestCounter(); RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url); if (requestTimeout > 0) builder.setTimeoutMillis(requestTimeout); String body = ""; if (isStream) { builder.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); body = new String(encode(request)); } else { builder.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); StringBuffer sb = new StringBuffer(); for (Iterator iterator = request.entrySet().iterator(); iterator.hasNext();) { Map.Entry<String, Object> entry = (Map.Entry<String, Object>) iterator.next(); sb.append(entry.getKey()).append("=").append(String.valueOf(entry.getValue())).append("&"); } body = sb.toString(); if (body.endsWith("&")) body = body.substring(0, body.length() - 1); } builder.setHeader("Content-Length", Integer.toString(body.length())); if (requestCookie != null) if (Cookies.getCookie(requestCookie) != null) builder.setHeader("X-Cookie", Cookies.getCookie(requestCookie)); if (username != null) builder.setUser(username); if (password != null) builder.setPassword(password); try { builder.sendRequest(body, handler); } catch (RequestException exception) { handler.onError(null, exception); } }