Example usage for com.google.gwt.http.client RequestBuilder send

List of usage examples for com.google.gwt.http.client RequestBuilder send

Introduction

In this page you can find the example usage for com.google.gwt.http.client RequestBuilder send.

Prototype

public Request send() throws RequestException 

Source Link

Document

Sends an HTTP request based on the current builder configuration.

Usage

From source file:org.jboss.errai.ui.shared.ServerTemplateProvider.java

License:Apache License

@Override
public void provideTemplate(final String url, final TemplateRenderingCallback renderingCallback) {
    final RequestBuilder request = new RequestBuilder(RequestBuilder.GET, url);
    request.setCallback(new RequestCallback() {
        @Override//ww w . j a v  a2  s . c  om
        public void onResponseReceived(Request request, Response response) {
            if (response.getStatusCode() == Response.SC_OK) {
                renderingCallback.renderTemplate(response.getText());
            } else {
                throw new RuntimeException("Failed to retrieve template from server at " + url
                        + " (status code: " + response.getStatusCode() + ")");
            }
        }

        @Override
        public void onError(Request request, Throwable exception) {
            throw new RuntimeException("Failed to retrieve template from server at " + url, exception);
        }
    });

    try {
        request.send();
    } catch (RequestException e) {
        throw new RuntimeException("Failed to retrieve template from server at" + request.getUrl(), e);
    }
}

From source file:org.jboss.hal.dmr.dispatch.impl.DMRHandler.java

License:Open Source License

private Request executeRequest(final AsyncCallback<DMRResponse> resultCallback, final ModelNode operation) {
    if (idCounter == Long.MAX_VALUE) {
        idCounter = 0;/*from  www.  jav a2s.  c om*/
    }

    Request request = null;
    try {
        final String id = String.valueOf(idCounter++);
        trace(Type.BEGIN, id, operation);

        final RequestBuilder requestBuilder = chooseRequestBuilder(operation);
        trace(Type.SERIALIZED, id, operation);

        final RequestCallback requestCallback = new RequestCallback() {
            @Override
            public void onResponseReceived(Request request, Response response) {
                trace(Type.RECEIVE, id, operation);

                int statusCode = response.getStatusCode();
                if (200 == statusCode) {
                    resultCallback.onSuccess(new DMRResponse(requestBuilder.getHTTPMethod(), response.getText(),
                            response.getHeader(HEADER_CONTENT_TYPE)));
                } else if (401 == statusCode || 0 == statusCode) {
                    resultCallback.onFailure(new DispatchError("Authentication required.", statusCode));
                } else if (403 == statusCode) {
                    resultCallback.onFailure(new DispatchError("Authentication required.", statusCode));
                } else if (307 == statusCode) {
                    String location = response.getHeader("Location");
                    Log.error("Redirect '" + location + "'. Could not execute " + operation.toString());
                    redirect(location);
                } else if (503 == statusCode) {
                    resultCallback.onFailure(new DispatchError(
                            "Service temporarily unavailable. Is the server is still booting?", statusCode));
                } else {
                    StringBuilder sb = new StringBuilder();
                    sb.append("Unexpected HTTP response").append(": ").append(statusCode);
                    sb.append("\n\n");
                    sb.append("Request\n");
                    sb.append(operation.toString());
                    sb.append("\n\nResponse\n\n");
                    sb.append(response.getStatusText()).append("\n");
                    String payload = response.getText().equals("") ? "No details"
                            : ModelNode.fromBase64(response.getText()).toString();
                    sb.append(payload);
                    resultCallback.onFailure(new DispatchError(sb.toString(), statusCode));
                }
                trace(Type.END, id, operation);
            }

            @Override
            public void onError(Request request, Throwable e) {
                trace(Type.RECEIVE, id, operation);
                resultCallback.onFailure(e);
                trace(Type.END, id, operation);
            }
        };
        requestBuilder.setCallback(requestCallback);
        request = requestBuilder.send();
        trace(Type.SEND, id, operation);
    } catch (RequestException e) {
        resultCallback.onFailure(e);
    }
    return request;
}

From source file:org.jboss.uberfire.dmr.poc.client.local.dmr.DMRRequest.java

License:Open Source License

public static void sendRequest(ModelNode requestData, DMRCallback callback) {
    System.out.println("***** Sending DMR Request **********");
    System.out.println(requestData.toString());
    System.out.println("************************************");
    RequestBuilder request = makeRequest(requestData);
    request.setCallback(callback);/*from w w w  .  j av a  2  s .  c o  m*/
    try {
        request.send();
    } catch (RequestException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jbpm.workbench.cm.client.navbar.LogoWidgetView.java

License:Apache License

@PostConstruct
public void init() {
    final RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, "banner/banner.html");
    rb.setCallback(new RequestCallback() {
        @Override/*from  w w w. j av  a  2  s  . c  o  m*/
        public void onResponseReceived(final Request request, final Response response) {
            final HTMLPanel html = new HTMLPanel(response.getText());
            container.setWidget(html);
        }

        @Override
        public void onError(final Request request, final Throwable exception) {
            container.setWidget(new Label(translationService.format(ShowcaseConstants.LOGO_BANNER_ERROR)));
        }
    });
    try {
        rb.send();
    } catch (RequestException re) {
        container.setWidget(new Label(translationService.format(ShowcaseConstants.LOGO_BANNER_ERROR)));
    }

    initWidget(container);
}

From source file:org.mindinformatics.gwt.domeo.plugins.resource.pmcimages.service.impl.JsonPmcImagesConnector.java

License:Apache License

@Override
public void retrievePmcImagesData(final IPmcImagesRequestCompleted completionCallback, String pmid,
        String pmcid, String doi) throws IllegalArgumentException {

    if (_application.isHostedMode()) {
        String response = "[{\"uysie:hasCaption\": \"Representative self-terminating radical reactions.\","
                + "\"uysie:hasFullText\": \"Most organic radical reactions occur through a cascade of two or more individual steps [1,2]. Knowledge of the nature and rates of these steps  in other words, the mechanism of the reaction  is of fundamental interest and is also important in synthetic planning. In synthesis, both the generation of the initial radical of the cascade and the removal of the final radical are crucial events [3]. Many useful radical reactions occur through chains that provide a naturally coupled regulation of radical generation and removal. Among the non-chain methods, generation and removal of radicals by oxidation and reduction are important, as is the\","
                + "\"uysie:hasFileName\": \"nihms28314f1\","
                + "\"uysie:hasTitle\": \"Do alpha-acyloxy and alpha-alkoxycarbonyloxy radicals fragment to form acyl and alkoxycarbonyl radicals?\"}]";

        @SuppressWarnings("unchecked")
        JsArray<JsPmcImage> responseOnSets = (JsArray<JsPmcImage>) parseJson(response);
        HashMap<String, JsPmcImage> images = new HashMap<String, JsPmcImage>();
        for (int i = 0; i < responseOnSets.length(); i++) {
            images.put(responseOnSets.get(i).getName(), responseOnSets.get(i));
        }// w  ww  .  java  2  s . com

        completionCallback.returnPmcImagesData(images);
        return;
    }

    String requestUrl = ApplicationUtils.getUrlBase(GWT.getModuleBaseURL())
            + "yaleImageFinder/retrievePmcImagesData?format=json";
    try {
        RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, requestUrl);
        builder.setHeader("Content-Type", "application/json");

        JSONObject request = new JSONObject();
        if (pmid != null)
            request.put("pmid", new JSONString(pmid));
        if (pmcid != null)
            request.put("pmcid", new JSONString(pmcid));
        if (doi != null)
            request.put("doi", new JSONString(doi));

        JSONArray messages = new JSONArray();
        messages.set(0, request);

        builder.setTimeoutMillis(20000);
        builder.setRequestData(messages.toString());
        builder.setCallback(new RequestCallback() {
            public void onError(Request request, Throwable exception) {
                if (exception instanceof RequestTimeoutException) {
                    _application.getLogger().exception(this,
                            "Couldn't load images metadata (timeout) " + exception.getMessage());
                    completionCallback.pmcImagesDataNotFound();
                    //                  ((ProgressMessagePanel)((DialogGlassPanel)_application.getDialogPanel()).getPanel()).addErrorMessage("Could not load images metadata  (timeout)");
                    //                  handler.bibliographySetListNotCreated("Could not load existing bibliography  (timeout)");
                } else {
                    _application.getLogger().exception(this, "Couldn't load images metadata");
                    completionCallback.pmcImagesDataNotFound();
                    //                  ((ProgressMessagePanel)((DialogGlassPanel)_application.getDialogPanel()).getPanel()).addErrorMessage("Could not load existing bibliography (onError)");
                    //                  handler.bibliographySetListNotCreated("Could not load existing bibliography (onError)");
                }
            }

            public void onResponseReceived(Request request, Response response) {
                if (200 == response.getStatusCode()) {
                    try {
                        _application.getLogger().debug(this, response.getText());
                        @SuppressWarnings("unchecked")
                        JsArray<JsPmcImage> responseOnSets = (JsArray<JsPmcImage>) parseJson(
                                response.getText());
                        HashMap<String, JsPmcImage> images = new HashMap<String, JsPmcImage>();
                        for (int i = 0; i < responseOnSets.length(); i++) {
                            images.put(responseOnSets.get(i).getName(), responseOnSets.get(i));
                        }
                        completionCallback.returnPmcImagesData(images);
                    } catch (Exception e) {
                        _application.getLogger().exception(this,
                                "Could not parse images metadata " + e.getMessage());
                        completionCallback.pmcImagesDataNotFound();
                        //                     ((ProgressMessagePanel)((DialogGlassPanel)_application.getDialogPanel()).getPanel()).addErrorMessage("Could not parse existing bibliography  " + e.getMessage());
                        //                     handler.bibliographySetListNotCreated("Could not parse existing bibliography " + e.getMessage() + " - "+ response.getText());
                    }
                } else if (503 == response.getStatusCode()) {
                    _application.getLogger().exception(this,
                            "Existing bibliography by url 503: " + response.getText());
                    completionCallback.pmcImagesDataNotFound();
                    //                  ((ProgressMessagePanel)((DialogGlassPanel)_application.getDialogPanel()).getPanel()).addErrorMessage("Could not retrieve existing bibliography  " + response.getStatusCode());
                    //                  handler.bibliographySetListNotCreated("Could not retrieve existing bibliography " + response.getStatusCode() + " - "+ response.getText());
                    //completionCallback.textMiningNotCompleted(response.getText());
                } else {
                    _application.getLogger().exception(this,
                            "Load images metadata " + response.getStatusCode() + ": " + response.getText());
                    //                  ((ProgressMessagePanel)((DialogGlassPanel)_application.getDialogPanel()).getPanel()).addErrorMessage("Could not retrieve existing bibliography  " + response.getStatusCode());
                    //                  handler.bibliographySetListNotCreated("Could not retrieve existing bibliography " + response.getStatusCode() + " - "+ response.getText());
                    //handler.setExistingBibliographySetList(new JsArray(), true);
                    //completionCallback.textMiningNotCompleted(response.getText());
                    completionCallback.pmcImagesDataNotFound();
                }
            }
        });
        builder.send();

    } catch (RequestException e) {
        _application.getLogger().exception(this, "Couldn't save annotation");
        completionCallback.pmcImagesDataNotFound();

    }
}

From source file:org.opencms.ugc.client.CmsRpcCallHelper.java

License:Open Source License

/**
 * Executes the RPC call.<p>/*from  w ww  . j a  v a  2  s . c o  m*/
 *
 * @param requestBuilder the request builder returned by the service interface
 */
@SuppressWarnings("synthetic-access")
public void executeRpc(RequestBuilder requestBuilder) {

    final RequestCallback callback = requestBuilder.getCallback();
    RequestCallback callbackWrapper = new RequestCallback() {

        public void onError(com.google.gwt.http.client.Request request, Throwable exception) {

            m_requestCounter.decrement();
            callback.onError(request, exception);
        }

        public void onResponseReceived(com.google.gwt.http.client.Request request,
                com.google.gwt.http.client.Response response) {

            m_requestCounter.decrement();
            callback.onResponseReceived(request, response);
        }
    };
    requestBuilder.setCallback(callbackWrapper);
    m_requestCounter.increment();
    try {
        requestBuilder.send();
    } catch (Exception e) {
        m_requestCounter.decrement();
    }
}

From source file:org.openmoney.omlets.mobile.client.utils.RestRequest.java

License:Open Source License

/**
 * Sends a request using the given callback to notify the results. 
 * This method does not uses authentication, to perform authenticated 
 * requests see {@link #sendAuthenticated(AsyncCallback)}
 *//*from   ww  w .  jav a  2 s .com*/
public Request send(AsyncCallback<T> callback) {

    // Start loading progress
    OmletsMobile.get().getMainLayout().startLoading();

    String url = "";

    // Append parameters as GET
    if (httpMethod == RequestBuilder.GET) {
        url = Configuration.get().getServiceUrl(this.path, parameters);
    } else {
        url = Configuration.get().getServiceUrl(this.path);
    }
    ErrorHandler.debug("RestRequest:" + httpMethod + ",url:" + url);

    RequestBuilder request = new RequestBuilder(httpMethod, url);
    request.setTimeoutMillis(40 * 1000); // 40 seconds
    request.setHeader("Accept", "application/json");
    request.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");

    if (httpMethod == RequestBuilder.POST) {
        request.setHeader("Content-Type", "application/json");

        // Send post body parameters
        if (parameters != null) {
            String json = parameters.toJSON();
            request.setRequestData(json);
        } else {
            // Send post without data
            request.setRequestData("");
        }
    }
    // Send a JSON post object
    if (postObject != null) {
        request.setHeader("Content-Type", "application/json");
        request.setRequestData(new JSONObject(postObject).toString());
    }
    if (username != null && !username.isEmpty()) {
        request.setHeader("Authorization", "Basic " + Base64.encode(username + ":" + password));
    }
    request.setCallback(new RequestCallbackAdapter(callback));
    try {
        // Send request
        return request.send();
    } catch (RequestException e) {
        callback.onFailure(e);

        // Stop loading progress
        OmletsMobile.get().getMainLayout().stopLoading();

        // Returns an emulated request, which does nothing
        return new Request() {
            @Override
            public void cancel() {

            }

            @Override
            public boolean isPending() {
                return false;
            }
        };
    }
}

From source file:org.openremote.web.console.service.JSONControllerConnector.java

License:Open Source License

private void doJsonRequest(String url, String username, String password, JSONControllerCallback callback,
        Integer timeout) {/* w ww. ja  v  a2s  . co  m*/
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
    Request request = null;

    // Add accept header
    builder.setHeader("Accept", "application/json");

    if (username != null && username.length() > 0) {
        if (password == null)
            password = "";

        // Add authentication header
        String authStr = username + ":" + password;
        String authEnc = "Basic " + BrowserUtils.base64Encode(authStr);
        builder.setHeader("Authorization", authEnc);
    }

    builder.setCallback(callback);

    if (timeout != null) {
        builder.setTimeoutMillis(timeout);
    }

    try {
        request = builder.send();
    } catch (RequestException e) {
        callback.onError(request, e);
    }
}

From source file:org.opentaps.gwt.common.client.listviews.EntityEditableListView.java

License:Open Source License

/**
 * Handles the save all batch action, this takes all records that need
 * to be created, update or deleted and send them in one request.
 * The posted data is the same format as for a <code>service-multi</code>.
 *//*from ww  w  .j  av  a2s  .  c om*/
protected void doBatchAction() {
    UtilUi.logInfo("doBatchAction ...", MODULE, "doBatchAction");
    String data = makeBatchPostData();
    if (data == null) {
        UtilUi.logInfo("nothing to do", MODULE, "doBatchAction");
        return;
    }

    RequestBuilder request = new RequestBuilder(RequestBuilder.POST, GWT.getHostPageBaseURL() + saveAllUrl);
    request.setHeader("Content-type", "application/x-www-form-urlencoded");
    request.setRequestData(data);
    request.setTimeoutMillis(UtilLookup.getAjaxDefaultTimeout());
    request.setCallback(new RequestCallback() {
        public void onError(Request request, Throwable exception) {
            // display error message
            markGridNotBusy();
            UtilUi.errorMessage(exception.toString());
        }

        public void onResponseReceived(Request request, Response response) {
            // if it is a correct response, reload the grid
            markGridNotBusy();
            UtilUi.logInfo("onResponseReceived, response = " + response, MODULE, "doBatchAction");
            if (!ServiceErrorReader.showErrorMessageIfAny(response, saveAllUrl)) {
                // commit store changes
                getStore().commitChanges();
                loadFirstPage();
            }
        }
    });
    try {
        markGridBusy();
        UtilUi.logInfo("posting batch", MODULE, "doBatchAction");
        request.send();
    } catch (RequestException e) {
        // display error message
        UtilUi.errorMessage(e.toString(), MODULE, "doBatchAction");
    }
}

From source file:org.opentaps.gwt.common.client.services.Service.java

License:Open Source License

/**
 * Sends the request and get the result asynchronously.
 * @param cb an <code>AsyncCallback</code> instance for the returned <code>Record</code>
 *///www . java  2 s.co m
public void request(final AsyncCallback<Record> cb) {
    RequestBuilder request = new RequestBuilder(RequestBuilder.POST, GWT.getHostPageBaseURL() + url);
    request.setHeader("Content-type", "application/x-www-form-urlencoded");
    request.setRequestData(data);
    request.setTimeoutMillis(UtilLookup.getAjaxDefaultTimeout());
    request.setCallback(new RequestCallback() {
        public void onError(Request request, Throwable exception) {
            // display error message
            if (autoPopupErrors) {
                UtilUi.errorMessage(exception.toString());
            } else {
                UtilUi.logError("onError, error = " + exception.toString(), MODULE, "request");
            }
            cb.onFailure(exception);
        }

        public void onResponseReceived(Request request, Response response) {
            UtilUi.logInfo("onResponseReceived, response = " + response, MODULE, "request");
            String err = ServiceErrorReader.getErrorMessageIfAny(response, url);
            if (err == null) {
                if (store != null) {
                    store.loadJsonData(response.getText(), false);
                    Record rec = null;
                    if (store.getTotalCount() > 0) {
                        rec = store.getRecordAt(0);
                    }
                    cb.onSuccess(rec);
                }
            } else {
                if (autoPopupErrors) {
                    UtilUi.errorMessage(err);
                } else {
                    UtilUi.logError("onResponseReceived, error = " + err, MODULE, "request");
                }
                cb.onFailure(new RequestException(err));
            }
        }
    });
    try {
        UtilUi.logInfo("posting request", MODULE, "request");
        request.send();
    } catch (RequestException e) {
        if (autoPopupErrors) {
            UtilUi.errorMessage(e.toString());
        } else {
            UtilUi.logError("Caught RequestException, error = " + e.toString(), MODULE, "request");
        }
        cb.onFailure(e);
    }
}