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

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

Introduction

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

Prototype

public Request sendRequest(String requestData, RequestCallback callback) throws RequestException 

Source Link

Document

Sends an HTTP request based on the current builder configuration with the specified data and callback.

Usage

From source file:fr.mncc.gwttoolbox.ajax.client.Json.java

License:Open Source License

private static <T extends JavaScriptObject> void sendRequest(RequestBuilder.Method httpMethod, String url,
        String data, final AsyncCallback<T> callback) {
    try {/* w  w w  .j av a2 s.  c  om*/
        RequestBuilder requestBuilder = new RequestBuilder(httpMethod, url);
        requestBuilder.setHeader("Accept", "application/json");
        requestBuilder.setHeader("Content-Type", "application/json");
        requestBuilder.sendRequest(data, new RequestCallback() {
            @Override
            public void onResponseReceived(Request request, Response response) {
                if (response.getStatusCode() != Response.SC_OK) {
                    if (callback != null)
                        callback.onFailure(new Exception("status code = " + response.getStatusCode()
                                + ", status text = " + response.getStatusText()));
                } else {
                    if (callback != null)
                        callback.onSuccess(JsonParser.<T>fromJson(response.getText()));
                }
            }

            @Override
            public void onError(Request request, Throwable exception) {
                if (callback != null)
                    callback.onFailure(exception);
            }
        });
    } catch (RequestException e) {
        GWT.log(e.toString());
    }
}

From source file:fr.mncc.gwttoolbox.rpc.client.requests.RestCall.java

License:Open Source License

private static <T extends JavaScriptObject> void sendRequest(final RequestBuilder.Method method,
        final String url, final String data, final AsyncCallback<T> callback) {
    try {//from   w w  w  .ja  v  a 2 s  .  c  om
        final RequestBuilder rb = new RequestBuilder(method, URL.encode(url));
        rb.setHeader("Accept", "application/json");
        rb.sendRequest(data, new RequestCallback() {
            @Override
            public void onError(final com.google.gwt.http.client.Request request, final Throwable exception) {
                if (callback != null)
                    callback.onFailure(exception);
            }

            @Override
            public void onResponseReceived(final com.google.gwt.http.client.Request request,
                    final Response response) {
                if (response.getStatusCode() != Response.SC_OK) {
                    if (callback != null)
                        callback.onFailure(
                                new Exception("response.getStatusCode() = " + response.getStatusCode()));
                } else {
                    final JsonParser<T> parser = new JsonParser<T>();
                    if (callback != null)
                        callback.onSuccess(parser.fromJson(response.getText()));
                }
            }
        });
    } catch (final Exception exception) {
        if (callback != null)
            callback.onFailure(exception);
    }
}

From source file:fr.mncc.minus.ajax.client.Ajax.java

License:Open Source License

private static <T extends JavaScriptObject> void sendRequest(RequestBuilder.Method httpMethod, String url,
        String data, final AsyncCallback<T> callback) {
    try {/*from  w w w.  ja va 2s .c o m*/
        RequestBuilder requestBuilder = new RequestBuilder(httpMethod, url);
        requestBuilder.setHeader("Accept", "application/json");
        requestBuilder.setHeader("Content-Type", "application/json");
        requestBuilder.sendRequest(data, new RequestCallback() {

            @Override
            public void onResponseReceived(Request request, Response response) {
                if (response.getStatusCode() != Response.SC_OK) {
                    if (callback != null) {
                        callback.onFailure(new Exception("status code = " + response.getStatusCode()
                                + ", status text = " + response.getStatusText()));
                    }
                } else {
                    if (callback != null) {
                        callback.onSuccess(JsonParser.<T>fromJson(response.getText()));
                    }
                }
            }

            @Override
            public void onError(Request request, Throwable exception) {
                if (callback != null) {
                    callback.onFailure(exception);
                }
            }
        });
    } catch (RequestException e) {
        GWT.log(e.toString());
    }
}

From source file:grails.plugin.console.charts.client.application.share.AbstractSharePresenter.java

License:Apache License

@Override
public void onGetLinkClicked(String format) {
    ShareDetails details = getView().getEditorDriver().flush();
    details.setConnectionString(AppUtils.CONNECTION_STRING);
    details.setQuery(AppUtils.QUERY);//from ww  w .j av a 2s .co m
    details.setAppearance(AppUtils.APPEARANCE);
    details.setView(AppUtils.VIEW);

    // Retrieve the AutoBean controller
    AutoBean<ShareDetails> bean = AutoBeanUtils.getAutoBean(details);

    String json = AutoBeanCodex.encode(bean).getPayload();

    try {
        RequestBuilder rb = new RequestBuilder(RequestBuilder.POST,
                AppUtils.getLinkPath() + "?format=" + format);

        rb.sendRequest(json, new RequestCallback() {
            @Override
            public void onResponseReceived(Request request, Response response) {
                JSONValue value = JSONParser.parseStrict(response.getText());
                JSONObject result = value.isObject();

                if (result.get("error") != null) {
                    Window.alert("Error occurred: " + result.get("error").isString().stringValue());
                    return;
                }

                getView().setLink(result.get("link").isString().stringValue());
            }

            @Override
            public void onError(Request request, Throwable exception) {
                Window.alert("Error occurred: " + exception.getMessage());
            }
        });
    } catch (RequestException e) {
        Window.alert("Error occurred: " + e.getMessage());
    }

}

From source file:gwt.dojo.showcase.client.Showcase.java

License:Apache License

private void loadAndSwitchView(final ListItem listItem) {

    final RequestCallback requestCallback = new RequestCallback() {
        @Override//  ww  w.  j a v a2  s.  co  m
        public void onResponseReceived(Request request, Response response) {
            if (200 == response.getStatusCode()) {
                try {
                    // Process the response in response.getText()

                    // fillInDemoSource();
                    DivElement rightPane = Document.get().getElementById("rightPane").cast();
                    DivElement tmpContainer = Document.get().createDivElement();
                    tmpContainer.setInnerHTML(response.getText());
                    rightPane.appendChild(tmpContainer);
                    JsArray ws = MobileParser.parse(tmpContainer);
                    for (int i = 0, n = ws.length(); i < n; i++) {
                        if (ws.getJsObject(i).hasProperty("startup")) {
                            _WidgetBase w = ws.getJsObject(i);
                            w.startup();
                        }
                    }

                    // reparent
                    rightPane.removeChild(tmpContainer);
                    NodeList<Node> children = tmpContainer.getChildNodes();
                    for (int i = 0, n = children.getLength(); i < n; i++) {
                        Element elem = tmpContainer.getChild(i).cast();
                        rightPane.appendChild(elem);
                    }

                    showProgressIndicator(false);
                    Scheduler.get().scheduleDeferred(new ScheduledCommand() {
                        @Override
                        public void execute() {
                            initView(listItem);
                            listItem.transitionTo(listItem.getString("viewId"));
                            // triggreTransition(listItem,
                            // listItem.getString("id"));
                        }
                    });
                } catch (Exception e) {
                    Window.alert("Error: " + e);
                }
            } else {
                // Handle the error. Can get the status text from
                // response.getStatusText()
                onError(request, new RequestException("HTTP Error: " + response.getStatusCode()));
            }
        }

        @Override
        public void onError(Request request, Throwable exception) {
            Window.alert("Failed to load demo.");
            showProgressIndicator(false);
            inTransitionOrLoading = false;
        }
    };

    showProgressIndicator(true);

    String url = listItem.getString("demourl");
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));

    Request request = null;
    try {
        request = builder.sendRequest(null, requestCallback);
    } catch (RequestException e) {
        requestCallback.onError(request, e);
    }
}

From source file:io.apiman.manager.ui.client.local.services.ConfigurationService.java

License:Apache License

/**
 * Starts a timer that will refresh the configuration's bearer token
 * periodically.//from ww w .  j ava2 s. c  o m
 */
private void startTokenRefreshTimer() {
    Timer timer = new Timer() {
        @Override
        public void run() {
            GWT.log("Refreshing auth token."); //$NON-NLS-1$

            final String url = GWT.getHostPageBaseURL() + "rest/tokenRefresh"; //$NON-NLS-1$
            RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
            try {
                builder.sendRequest(null, new RequestCallback() {
                    @Override
                    public void onResponseReceived(Request request, Response response) {
                        if (response.getStatusCode() != 200) {
                            GWT.log("[001] Authentication token refresh failure: " + url); //$NON-NLS-1$
                        } else {
                            BearerTokenCredentialsBean bean = new BearerTokenCredentialsBean();
                            JSONObject root = JSONParser.parseStrict(response.getText()).isObject();
                            bean.setToken(root.get("token").isString().stringValue()); //$NON-NLS-1$
                            bean.setRefreshPeriod((int) root.get("refreshPeriod").isNumber().doubleValue()); //$NON-NLS-1$
                            configuration.getApi().getAuth().setBearerToken(bean);
                        }
                        startTokenRefreshTimer();
                    }

                    @Override
                    public void onError(Request request, Throwable exception) {
                        GWT.log("[002] Authentication token refresh failure: " + url); //$NON-NLS-1$
                    }
                });
            } catch (RequestException e) {
                GWT.log("Authentication token refresh failed!"); //$NON-NLS-1$
            }
        }
    };
    timer.schedule(configuration.getApi().getAuth().getBearerToken().getRefreshPeriod() * 1000);
}

From source file:mcamara.client.QwebScormApp.java

License:Open Source License

public void onModuleLoad() {
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, "cuestionario.xml");
    try {/*from   w w  w . ja  v  a  2  s . co m*/
        builder.sendRequest(null, new RequestCallback() {
            public void onResponseReceived(Request request, Response response) {
                cuestionario = Util.XMLtoCuestionario(response.getText());
                m = Util.getMensajes(cuestionario.getIdioma());
                if (cuestionario.getTipo().equals("autoevaluacion")) {
                    DialogBox ppresentacion = new PPresentacion(cuestionario);
                    RootPanel.get().add(ppresentacion);
                } else if (cuestionario.getTipo().equals("tutorial")) {
                    DialogBox ptutorial = new PTutorial(cuestionario, -1);
                    RootPanel.get().add(ptutorial);
                } else
                    Window.alert(m.cuestionarionovalido());
            }

            public void onError(Request request, Throwable exception) {
                Window.alert(m.error());
            }
        });
    } catch (RequestException e) {
        Window.alert(m.error());
    }
}

From source file:n3phele.client.CacheManager.java

License:Open Source License

public void refresh() {
    RequestBuilder builder = AuthenticatedRequestFactory.newCacheManagerRequest(RequestBuilder.GET,
            ServiceAddress + "?summary=false&changeOnly=true&since=" + stamp);
    if (builder == null)
        return;//w w  w.  ja  va  2  s. c  o m
    try {
        GWT.log("Sending request");
        @SuppressWarnings("unused")
        Request request = builder.sendRequest(null, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
                // displayError("Couldn't retrieve JSON "+exception.getMessage());
            }

            public void onResponseReceived(Request request, Response response) {
                if (200 == response.getStatusCode()) {
                    Root root = Root.parse(response.getText());
                    GWT.log(response.getText());
                    GWT.log(root.toString());
                    stamp = root.getStamp();
                    ChangeGroup changes = root.getChangeGroup();
                    if (changes != null) {
                        if (changes.getChange() != null) {
                            for (Change x : changes.getChange()) {
                                List<Registration> item;
                                item = cache.get(x.getUri());
                                GWT.log("Got change URI " + x.getUri() + " item " + item);
                                if (x.getUri().equals(cloudUrl)) {
                                    refreshClouds();
                                }
                                if (item != null) {
                                    fireAll(x.getUri(), item);
                                }
                            }
                            if (changes.getChange().size() != 0) {
                                backoff = 0;
                            }
                        }
                    } else {
                        for (Entry<String, List<Registration>> entry : cache.entrySet()) {
                            fireAll(entry.getKey(), entry.getValue());
                        }
                    }

                } else {
                    // displayError("Couldn't retrieve JSON (" + response.getStatusText() + ")");
                }
            }

        });
    } catch (RequestException e) {
        // displayError("Couldn't retrieve JSON "+e.getMessage());
    }
}

From source file:n3phele.client.CacheManager.java

License:Open Source License

public void test(String username, String password, RequestCallback requestCallback) {

    // Send request to server and catch any errors.
    RequestBuilder builder = AuthenticatedRequestFactory.request(RequestBuilder.GET,
            ServiceAddress + "user/byName?id=" + URL.encodeQueryString(username), username, password);
    GWT.log("Sending authentication test request");
    Request request = null;/*  w ww  .ja  va  2s .c  o  m*/
    try {
        request = builder.sendRequest(null, requestCallback);
    } catch (RequestException e) {
        requestCallback.onError(request, e);
    }

}

From source file:n3phele.client.CacheManager.java

License:Open Source License

protected void refreshClouds() {

    RequestBuilder builder = AuthenticatedRequestFactory.newCacheManagerRequest(RequestBuilder.GET, cloudUrl);
    try {//w  ww.  j  av  a  2  s .c o  m
        builder.sendRequest(null, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
                GWT.log("Couldn't retrieve JSON " + exception.getMessage());
            }

            public void onResponseReceived(Request request, Response response) {
                if (200 == response.getStatusCode()) {
                    Collection<Cloud> p = Cloud.asCollection(response.getText());
                    clouds.clear();
                    clouds.addAll(p.getElements());
                    GWT.log("Got " + clouds.size() + " clouds.");
                    gotClouds = true;
                    eventBus.fireEvent(new CloudListUpdate(cloudUrl));
                } else {
                    GWT.log("Couldn't retrieve JSON (" + response.getStatusText() + ")");
                }
            }
        });
        gotClouds = false;
    } catch (RequestException e) {
        GWT.log("Couldn't retrieve JSON " + e.getMessage());
    }
}