List of usage examples for com.google.gwt.http.client RequestCallback RequestCallback
RequestCallback
From source file:net.ffxml.gwt.json.client.JsonRpc.java
License:Apache License
/** * Executes a json-rpc request./*from w w w . j a v a2 s .co m*/ * * @param url * The location of the service * @param username * The username for basic authentification * @param password * The password for basic authentification * @param method * The method name * @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, final String method, Object[] params, final AsyncCallback callback) { HashMap request = new HashMap(); request.put("method", method); if (params == null) { params = new Object[] {}; } request.put("params", params); 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); builder.setHeader("Content-Type", "application/json; charset=utf-8"); String body = new String(encode(request)); 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); } }
From source file:net.opentsdb.tsd.client.QueryUi.java
License:Open Source License
private void asyncGetJson(final String url, final GotJsonCallback callback) { final RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url); try {//w ww . j a v a 2 s .c om builder.sendRequest(null, new RequestCallback() { public void onError(final Request request, final Throwable e) { displayError("Failed to get " + url + ": " + e.getMessage()); // Since we don't call the callback we've been given, reset this // bit of state as we're not going to retry anything right now. pending_requests = 0; } public void onResponseReceived(final Request request, final Response response) { final int code = response.getStatusCode(); if (code == Response.SC_OK) { clearError(); callback.got(JSONParser.parse(response.getText())); return; } else if (code >= Response.SC_BAD_REQUEST) { // 400+ => Oops. // Since we don't call the callback we've been given, reset this // bit of state as we're not going to retry anything right now. pending_requests = 0; String err = response.getText(); // If the response looks like a JSON object, it probably contains // an error message. if (!err.isEmpty() && err.charAt(0) == '{') { final JSONValue json = JSONParser.parse(err); final JSONObject result = json == null ? null : json.isObject(); final JSONValue jerr = result == null ? null : result.get("err"); final JSONString serr = jerr == null ? null : jerr.isString(); err = serr.stringValue(); // If the error message has multiple lines (which is common if // it contains a stack trace), show only the first line and // hide the rest in a panel users can expand. final int newline = err.indexOf('\n', 1); final String msg = "Request failed: " + response.getStatusText(); if (newline < 0) { displayError(msg + ": " + err); } else { displayError(msg); final DisclosurePanel dp = new DisclosurePanel(err.substring(0, newline)); RootPanel.get("queryuimain").add(dp); // Attach the widget. final InlineLabel content = new InlineLabel(err.substring(newline, err.length())); content.addStyleName("fwf"); // For readable stack traces. dp.setContent(content); current_error.getElement().appendChild(dp.getElement()); } } else { displayError("Request failed while getting " + url + ": " + response.getStatusText()); // Since we don't call the callback we've been given, reset this // bit of state as we're not going to retry anything right now. pending_requests = 0; } graphstatus.setText(""); } } }); } catch (RequestException e) { displayError("Failed to get " + url + ": " + e.getMessage()); } }
From source file:net.opentsdb.tsd.client.RemoteOracle.java
License:Open Source License
@Override public void requestSuggestions(final Request request, final Callback callback) { if (current != null) { pending_req = request;//from w ww . j a v a 2 s .co m pending_cb = callback; return; } current = callback; { final String this_query = request.getQuery(); // Check if we can serve this from our local cache, without even talking // to the server. This is possible if either of those is true: // 1. We've already seen this query recently. // 2. This new query precedes another one and the user basically just // typed another letter, so if the new query is "less than" the last // result we got from the server, we know we already cached the full // range of results covering the new request. if ((last_query != null && last_query.compareTo(this_query) <= 0 && this_query.compareTo(last_suggestion) < 0) || queries_seen.check(this_query)) { current = null; cache.requestSuggestions(request, callback); return; } last_query = this_query; } final RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, SUGGEST_URL + type + "&q=" + last_query); try { builder.sendRequest(null, new RequestCallback() { public void onError(final com.google.gwt.http.client.Request r, final Throwable e) { current = null; // Something bad happened, drop the current request. if (pending_req != null) { // But if we have another waiting... requestSuggestions(pending_req, pending_cb); // ... try it now. } } // Need to use fully-qualified names as this class inherits already // from a pair of inner classes called Request / Response :-/ public void onResponseReceived(final com.google.gwt.http.client.Request r, final com.google.gwt.http.client.Response response) { if (response.getStatusCode() == com.google.gwt.http.client.Response.SC_OK // Is this response still relevant to what the requester wants? && requester.getText().startsWith(last_query)) { final JSONValue json = JSONParser.parse(response.getText()); // In case this request returned nothing, we pretend the last // suggestion ended with the largest character possible, so we // won't send more requests to the server if the user keeps // adding extra characters. last_suggestion = last_query + "\377"; if (json != null && json.isArray() != null) { final JSONArray results = json.isArray(); final int n = Math.min(request.getLimit(), results.size()); for (int i = 0; i < n; i++) { final JSONValue suggestion = results.get(i); if (suggestion == null || suggestion.isString() == null) { continue; } final String suggestionstr = suggestion.isString().stringValue(); last_suggestion = suggestionstr; cache.add(suggestionstr); } cache.requestSuggestions(request, callback); pending_req = null; pending_cb = null; } } current = null; // Regardless of what happened above, this is done. if (pending_req != null) { final Request req = pending_req; final Callback cb = pending_cb; pending_req = null; pending_cb = null; requestSuggestions(req, cb); } } }); } catch (RequestException ignore) { } }
From source file:net.s17fabu.vip.gwt.showcase.client.ContentWidget.java
License:Apache License
public void onSelection(SelectionEvent<Integer> event) { // Show the associated widget in the deck panel int tabIndex = event.getSelectedItem().intValue(); deckPanel.showWidget(tabIndex);/*from w ww .j ava 2 s .com*/ // Load the source code String tabHTML = getTabBar().getTabHTML(tabIndex); if (!sourceLoaded && tabHTML.equals(constants.contentWidgetSource())) { sourceLoaded = true; String className = this.getClass().getName(); className = className.substring(className.lastIndexOf(".") + 1); requestSourceContents(ShowcaseConstants.DST_SOURCE_EXAMPLE + className + ".html", sourceWidget, null); } // Load the style definitions if (hasStyle() && tabHTML.equals(constants.contentWidgetStyle())) { final String theme = Showcase.CUR_THEME; if (styleDefs.containsKey(theme)) { styleWidget.setHTML(styleDefs.get(theme)); } else { styleDefs.put(theme, ""); RequestCallback callback = new RequestCallback() { public void onError(Request request, Throwable exception) { styleDefs.put(theme, "Style not available."); } public void onResponseReceived(Request request, Response response) { styleDefs.put(theme, response.getText()); } }; String srcPath = ShowcaseConstants.DST_SOURCE_STYLE + theme; if (LocaleInfo.getCurrentLocale().isRTL()) { srcPath += "_rtl"; } String className = this.getClass().getName(); className = className.substring(className.lastIndexOf(".") + 1); requestSourceContents(srcPath + "/" + className + ".html", styleWidget, callback); } } }
From source file:net.s17fabu.vip.gwt.showcase.client.ContentWidget.java
License:Apache License
/** * Load the contents of a remote file into the specified widget. * /*from w ww . jav a 2 s. c om*/ * @param url a partial path relative to the module base URL * @param target the target Widget to place the contents * @param callback the callback when the call completes */ protected void requestSourceContents(String url, final HTML target, final RequestCallback callback) { // Show the loading image if (loadingImage == null) { loadingImage = "<img src=\"" + GWT.getModuleBaseURL() + "images/loading.gif\">"; } target.setDirection(HasDirection.Direction.LTR); DOM.setStyleAttribute(target.getElement(), "textAlign", "left"); target.setHTML(" " + loadingImage); // Request the contents of the file RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, GWT.getModuleBaseURL() + url); RequestCallback realCallback = new RequestCallback() { public void onError(Request request, Throwable exception) { target.setHTML("Cannot find resource"); if (callback != null) { callback.onError(request, exception); } } public void onResponseReceived(Request request, Response response) { target.setHTML(response.getText()); if (callback != null) { callback.onResponseReceived(request, response); } } }; builder.setCallback(realCallback); // Send the request Request request = null; try { request = builder.send(); } catch (RequestException e) { realCallback.onError(request, e); } }
From source file:nl.mpi.tg.eg.experiment.client.service.DataSubmissionService.java
License:Open Source License
private void submitData(final ServiceEndpoint endpoint, final UserId userId, final String jsonData, final DataSubmissionListener dataSubmissionListener) { final RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, serviceLocations.dataSubmitUrl() + endpoint.name()); builder.setHeader("Content-type", "application/json"); RequestCallback requestCallback = new RequestCallback() { @Override/* w w w . j a v a2 s.c o m*/ public void onError(Request request, Throwable exception) { logger.warning(builder.getUrl()); logger.log(Level.WARNING, "RequestCallback", exception); dataSubmissionListener.scoreSubmissionFailed(new DataSubmissionException( DataSubmissionException.ErrorType.connectionerror, endpoint.name())); } @Override public void onResponseReceived(Request request, Response response) { final JsArray<DataSubmissionResult> sumbmissionResult = JsonUtils .<JsArray<DataSubmissionResult>>safeEval("[" + response.getText() + "]"); // here we also check that the JSON return value contains the correct user id, to test for cases where a web cashe or wifi login redirect returns stale data or a 200 code for a wifi login if (200 == response.getStatusCode() && sumbmissionResult.length() > 0 && sumbmissionResult.get(0).getSuccess() && userId.toString().equals(sumbmissionResult.get(0).getUserId())) { final String text = response.getText(); logger.info(text); // localStorage.stowSentData(userId, jsonData); dataSubmissionListener.scoreSubmissionComplete(sumbmissionResult); } else { logger.warning(builder.getUrl()); logger.warning(response.getStatusText()); if (sumbmissionResult.length() > 0) { dataSubmissionListener.scoreSubmissionFailed( new DataSubmissionException(DataSubmissionException.ErrorType.dataRejected, sumbmissionResult.get(0).getMessage())); } else { dataSubmissionListener.scoreSubmissionFailed(new DataSubmissionException( DataSubmissionException.ErrorType.non202response, endpoint.name())); } } } }; try { // todo: add the application build number to the submitted data builder.sendRequest(jsonData, requestCallback); } catch (RequestException exception) { logger.log(Level.SEVERE, "submit data failed", exception); dataSubmissionListener.scoreSubmissionFailed( new DataSubmissionException(DataSubmissionException.ErrorType.buildererror, endpoint.name())); } }
From source file:nl.mpi.tg.eg.experiment.client.service.synaesthesia.registration.RegistrationService.java
License:Open Source License
private RequestCallback geRequestBuilder(final UserResults userResults, final RequestBuilder builder, final RegistrationListener registrationListener, final String targetUri, final String receivingRegex) { return new RequestCallback() { @Override/*w w w .j a v a2 s. c om*/ public void onError(Request request, Throwable exception) { registrationListener.registrationFailed( new RegistrationException(RegistrationException.ErrorType.connectionerror, exception)); logger.warning(builder.getUrl()); logger.log(Level.WARNING, "RequestCallback", exception); } @Override public void onResponseReceived(Request request, Response response) { if (200 == response.getStatusCode()) { final String text = response.getText(); logger.info(text); if (receivingRegex != null) { JSONObject jsonObject = (JSONObject) JSONParser.parseStrict(text); for (MetadataField key : userResults.getUserData().getMetadataFields()) { final String postName = key.getPostName(); if (postName.matches(receivingRegex)) { if (jsonObject.containsKey(postName)) { userResults.getUserData().setMetadataValue(key, jsonObject.get(postName) .toString().replaceFirst("^\"", "").replaceFirst("\"$", "")); } } } } registrationListener.registrationComplete(); } else { registrationListener.registrationFailed( new RegistrationException(RegistrationException.ErrorType.non202response, "An error occured on the server: " + response.getStatusText())); logger.warning(targetUri); logger.warning(response.getStatusText()); } } }; }
From source file:nl.ru.languageininteraction.synaesthesia.client.registration.RegistrationService.java
License:Open Source License
private RequestCallback geRequestBuilder(final RequestBuilder builder, final RegistrationListener registrationListener, final String targetUri) { return new RequestCallback() { @Override/*from w w w . j a v a 2 s .c o m*/ public void onError(Request request, Throwable exception) { registrationListener.registrationFailed(exception); logger.warning(builder.getUrl()); logger.log(Level.WARNING, "RequestCallback", exception); } @Override public void onResponseReceived(Request request, Response response) { if (200 == response.getStatusCode()) { final String text = response.getText(); logger.info(text); registrationListener.registrationComplete(); } else { registrationListener.registrationFailed(new RegistrationException( "An error occured on the server: " + response.getStatusText())); logger.warning(targetUri); logger.warning(response.getStatusText()); } } }; }
From source file:nl.sense_os.commonsense.login.client.forgotpassword.ForgotPasswordActivity.java
License:Open Source License
@Override public void forgotPassword(String username, String email) { // prepare request callback RequestCallback callback = new RequestCallback() { @Override/* w w w. j a v a2 s.c o m*/ public void onError(Request request, Throwable exception) { onForgotPasswordFailure(0, exception); } @Override public void onResponseReceived(Request request, Response response) { onForgotPasswordResponse(response); } }; CommonSenseApi.forgotPassword(callback, username, email); }
From source file:nl.sense_os.commonsense.login.client.login.LoginActivity.java
License:Open Source License
/** * Sends a login request to the CommonSense API. * //from w ww .j a v a 2 s . c o m * @param username * The username to use for log in. * @param password * The password to user for log in. Will be hashed before submission. */ @Override public void login(String username, String password) { // prepare request callback RequestCallback callback = new RequestCallback() { @Override public void onError(Request request, Throwable exception) { LOG.warning("login error: " + exception.getMessage()); onLoginFailure(0, exception); } @Override public void onResponseReceived(Request request, Response response) { onLoginResponse(response); } }; // send request CommonSenseClient.getClient().login(callback, username, password); }