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:ch.unifr.pai.twice.comm.clientServerTime.client.ClientServerTimeOffset.java

License:Apache License

/**
 * The method sends a request asynchronously to the server side ({@link PingServlet}) and measures the time that it takes. The offset is then defined by
 * dividing the resulting round-trip time by two given the theoretical assumption that the connection is symmetrical (identical up- and downstream speed).
 * Although this requirement is almost never the case, it is precise enough for not affecting user experience and allows to establish a consistent event
 * ordering mechanism between distributed systems.
 * /*from   w  w w.  ja  v a2s. c o m*/
 * @param callback
 *            called at the end of the request providing the estimated offset between the server side and the local system clock in milliseconds.
 */
public static void getServerTimeOffset(final AsyncCallback<Long> callback) {
    RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, GWT.getHostPageBaseURL() + "ping");
    final long startTime = getCurrentTime();
    try {
        rb.sendRequest(null, createServerTimeOffsetRequestCallback(callback, startTime));
    } catch (RequestException e) {
        callback.onFailure(e);
    }
}

From source file:ch.unifr.pai.twice.widgets.mpproxy.client.ScreenShotDistributor.java

License:Apache License

/**
 * Send the screenshot to the server//from www . j a  v  a 2s. co m
 */
public void sendScreenShot() {
    String screen = Document.get().getDocumentElement().getInnerHTML();
    if (!screen.equals(lastSent) || lastLeft != Window.getScrollLeft() || lastTop != Window.getScrollTop()) {
        String url = Window.Location.getHref();
        URLParser p = new URLParser(url, Rewriter.getServletPath(Window.Location.getHref()));
        RequestBuilder rb = new RequestBuilder(RequestBuilder.POST,
                GWT.getModuleBaseURL() + "manager?url=" + p.getProxyBasePath() + "&width="
                        + Window.getClientWidth() + "&height=" + Window.getClientHeight() + "&top="
                        + Window.getScrollTop() + "&left=" + Window.getScrollLeft());
        lastSent = screen;
        lastLeft = Window.getScrollLeft();
        lastTop = Window.getScrollTop();
        screen = screen.replace('\n', ' ');
        screen = screen.replaceAll("<body", "<body><div class=\"readOnlyView\" style=\"width:"
                + Window.getClientWidth() + "; height:" + Window.getClientHeight() + ";\"");
        screen = screen.replaceAll("<\\/body>", "</div></body>");
        screen = screen.replaceAll("(<script).*?(\\/script>)", "");
        try {
            rb.sendRequest(screen, new RequestCallback() {

                @Override
                public void onResponseReceived(Request request, Response response) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onError(Request request, Throwable exception) {
                    Window.alert("Screenshot sent");
                }
            });
        } catch (RequestException e) {
            e.printStackTrace();
        }
    }
}

From source file:ch.unifr.pai.twice.widgets.mpProxyScreenShot.client.Viewer.java

License:Apache License

@Override
public void onModuleLoad() {
    Timer t = new Timer() {

        @Override//from www  .j av a 2s.co  m
        public void run() {
            try {
                RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, Window.Location.getProtocol() + "//"
                        + Window.Location.getHost() + "/miceScreenShot/manager");
                rb.sendRequest(null, new RequestCallback() {

                    @Override
                    public void onResponseReceived(Request request, Response response) {
                        RootPanel.getBodyElement().setInnerHTML(response.getText());
                    }

                    @Override
                    public void onError(Request request, Throwable exception) {
                    }
                });
            } catch (RequestException e) {
                e.printStackTrace();
            }
        }
    };
    t.run();
    //      t.scheduleRepeating(1000);

}

From source file:colt.json.gwt.client.JsonClient.java

License:Apache License

public void invoke(final String _url, final String _serviceName, String requestData, final IAsyncJSON result) {
    try {/* w  w w.j av  a2 s.c om*/
        RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST,
                URL.encode(_url + _serviceName));
        requestBuilder.setHeader("content-type", "application/x-www-form-urlencoded");

        Request request = requestBuilder.sendRequest(requestData, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
                result.error(exception);
            }

            public void onResponseReceived(Request request, Response response) {
                if (200 == response.getStatusCode()) {
                    String text = response.getText();
                    JSONValue parser = JSONParser.parse(text);
                    JSONObject jobj = parser.isObject();
                    result.done(jobj);
                } else {
                    result.error(new RuntimeException(_url + _serviceName + " :("));
                }
            }
        });
    } catch (RequestException e) {
        Window.alert(e.getMessage());
        result.error(e);
    }
}

From source file:com.audata.client.json.JSONCall.java

License:Open Source License

public Request asyncPost2(String method, JSONArray params, RequestCallback handler) {
    String msg = this.getJSONMsg(method, params);
    RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, this.url + "WebService_JSON.php");
    Request request = null;/* ww  w  .  j a va2s  .com*/
    try {
        builder.setTimeoutMillis(this.timeout);
        request = builder.sendRequest(msg, handler);
    } catch (RequestException e) {
        SimpleDialog.displayDialog(SimpleDialog.TYPE_ERROR, "Error",
                "Unable to send request to server\n" + e.getMessage());
    }
    return request;
}

From source file:com.badlogic.gdx.backends.gwt.GwtNet.java

License:Apache License

@Override
public void sendHttpRequest(final HttpRequest httpRequest, final HttpResponseListener httpResultListener) {
    if (httpRequest.getUrl() == null) {
        httpResultListener.failed(new GdxRuntimeException("can't process a HTTP request without URL set"));
        return;//from www  . j  a va2  s . c  om
    }

    final String method = httpRequest.getMethod();
    final String value = httpRequest.getContent();
    final boolean valueInBody = method.equalsIgnoreCase(HttpMethods.POST) || method.equals(HttpMethods.PUT);

    RequestBuilder builder;

    String url = httpRequest.getUrl();
    if (method.equalsIgnoreCase(HttpMethods.GET)) {
        if (value != null) {
            url += "?" + value;
        }
        builder = new RequestBuilder(RequestBuilder.GET, url);
    } else if (method.equalsIgnoreCase(HttpMethods.POST)) {
        builder = new RequestBuilder(RequestBuilder.POST, url);
    } else if (method.equalsIgnoreCase(HttpMethods.DELETE)) {
        if (value != null) {
            url += "?" + value;
        }
        builder = new RequestBuilder(RequestBuilder.DELETE, url);
    } else if (method.equalsIgnoreCase(HttpMethods.PUT)) {
        builder = new RequestBuilder(RequestBuilder.PUT, url);
    } else {
        throw new GdxRuntimeException("Unsupported HTTP Method");
    }

    Map<String, String> content = httpRequest.getHeaders();
    Set<String> keySet = content.keySet();
    for (String name : keySet) {
        builder.setHeader(name, content.get(name));
    }

    builder.setTimeoutMillis(httpRequest.getTimeOut());

    builder.setIncludeCredentials(httpRequest.getIncludeCredentials());

    try {
        Request request = builder.sendRequest(valueInBody ? value : null, new RequestCallback() {

            @Override
            public void onResponseReceived(Request request, Response response) {
                httpResultListener.handleHttpResponse(new HttpClientResponse(response));
                requests.remove(httpRequest);
                listeners.remove(httpRequest);
            }

            @Override
            public void onError(Request request, Throwable exception) {
                httpResultListener.failed(exception);
                requests.remove(httpRequest);
                listeners.remove(httpRequest);
            }
        });
        requests.put(httpRequest, request);
        listeners.put(httpRequest, httpResultListener);

    } catch (Throwable e) {
        httpResultListener.failed(e);
    }

}

From source file:com.badlogic.gdx.backends.gwt.preloader.TextLoader.java

License:Apache License

public TextLoader(String url, LoaderCallback<String> callback) {
    this.callback = callback;
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
    try {/* w  w w .  ja  v a  2s.  c o m*/
        builder.sendRequest(null, new RequestCallback() {
            @Override
            public void onResponseReceived(Request request, Response response) {
                TextLoader.this.callback.success(response.getText());
            }

            @Override
            public void onError(Request request, Throwable exception) {
                TextLoader.this.callback.error();
            }
        });
    } catch (RequestException e) {
        callback.error();
    }
}

From source file:com.bramosystems.oss.player.showcase.client.PlaylistPane.java

License:Apache License

private void loadList(String provider) {
    String spf = GWT.getHostPageBaseURL() + "media/jspf-core.json";
    if (provider.equals("bst.vimeo")) {
        spf = GWT.getHostPageBaseURL() + "media/jspf-vimeo.json";
    } else if (provider.equals("bst.youtube")) {
        spf = GWT.getHostPageBaseURL() + "media/jspf-youtube.json";
    }//from  w w w  . j a v a 2  s  .c  o m

    try {
        RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, spf);
        rb.sendRequest(null, new RequestCallback() {
            @Override
            public void onResponseReceived(Request request, Response response) {
                try {
                    SPFPlaylist spf = PlaylistFactory.parseJspfPlaylist(response.getText());
                    entries = spf.toPlaylist();
                    refreshView();
                } catch (ParseException ex) {
                    GWT.log("Parse Exception", ex);
                }
            }

            @Override
            public void onError(Request request, Throwable exception) {
            }
        });
    } catch (RequestException ex) {
        GWT.log("Request Exception", ex);
    }
}

From source file:com.brentryan.client.widgets.dialogs.AboutDialog.java

public AboutDialog() {

    aboutDialog.addButton(new Button("aboutOk", new ButtonConfig() {

        {//  w  w  w.  ja v  a 2  s .  com
            setText(DIALOG_CONSTANTS.Ok());
            setButtonListener(new ButtonListenerAdapter() {

                public void onClick(Button button, EventObject e) {
                    aboutDialog.destroy(true);
                }
            });
        }
    }));

    RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, "License.html");
    rb.setTimeoutMillis(30000);

    try {
        rb.sendRequest(null, new RequestCallback() {

            public void onError(Request request, Throwable exception) {
                aboutDialog.destroy(true);
                MessageBox.alert(DIALOG_CONSTANTS.ErrorTitle(), CONSTANTS.LicenseError());
            }

            public void onResponseReceived(Request request, Response response) {
                // add content to the center region
                BorderLayout layout = aboutDialog.getLayout();
                ContentPanel contentPanel = new ContentPanel();
                contentPanel.add(new HTML(response.getText()));
                layout.add(contentPanel);
                aboutDialog.show();
            }
        });
    } catch (RequestException e) {
        GWT.log("Error while retrieving BrentRyan license", e);
    }

    initWidget(aboutDialog);
}

From source file:com.calclab.emite.base.util.Platform.java

License:Open Source License

/**
 * Send a BOSH HTTP request to a server.
 * //  w w  w.  java 2s  .  c  om
 * @param httpBase the base URL to send the request
 * @param request the request contents
 * @param callback a callback to process the response
 */
public static final void sendXML(final String httpBase, final XMLPacket request,
        final AsyncResult<XMLPacket> callback) {
    final RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, httpBase);
    builder.setHeader(HttpHeaders.CONTENT_TYPE, "text/xml; charset=utf-8");
    //builder.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache");
    //builder.setHeader(HttpHeaders.PRAGMA, "no-cache");
    // TODO : Hard coded timeout to 6s, but we should set it to the wait + a delta
    // builder.setTimeoutMillis(6000);
    try {
        final Request req = builder.sendRequest(request.toString(), new RequestCallback() {
            @Override
            public void onResponseReceived(@Nullable final Request req, @Nullable final Response res) {
                requests.remove(req);
                if (res.getStatusCode() != Response.SC_OK) {
                    callback.onError(new RequestException(
                            "Invalid status " + res.getStatusCode() + ": " + res.getStatusText()));
                    return;
                }

                final XMLPacket response = XMLBuilder.fromXML(res.getText());
                if (response == null || !"body".equals(response.getTagName())) {
                    callback.onError(new RequestException("Bad response: " + res.getText()));
                    return;
                }

                callback.onSuccess(response);
            }

            @Override
            public void onError(@Nullable final Request req, @Nullable final Throwable throwable) {
                logger.severe("GWT CONNECTOR ERROR: " + throwable.getMessage());
                requests.remove(req);
                callback.onError(throwable);
            }
        });
        requests.add(req);
    } catch (final RequestException e) {
        callback.onError(e);
    } catch (final Exception e) {
        logger.severe("Some GWT connector exception: " + e.getMessage());
        callback.onError(e);
    }
}