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

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

Introduction

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

Prototype

protected RequestBuilder(String httpMethod, String url) 

Source Link

Document

Creates a builder using the parameters values for configuration.

Usage

From source file:cc.kune.embed.client.EmbedHelper.java

License:GNU Affero Public License

/**
 * Process request.//w  ww .ja va 2s .c om
 *
 * @param url
 *          the url
 * @param callback
 *          the callback
 */
public static void processRequest(final String url, final Callback<Response, Void> callback) {
    try {
        final RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
        // Needed for CORS
        builder.setIncludeCredentials(true);
        @SuppressWarnings("unused")
        final Request request = builder.sendRequest(null, new RequestCallback() {
            @Override
            public void onError(final Request request, final Throwable exception) {
                Log.error("CORS exception: ", exception);
                callback.onFailure(null);
            }

            @Override
            public void onResponseReceived(final Request request, final Response response) {
                if (200 == response.getStatusCode()) {
                    callback.onSuccess(response);
                } else {
                    Log.error("Couldn't retrieve CORS (" + response.getStatusText() + ")");
                    callback.onFailure(null);
                }
            }
        });
    } catch (final RequestException exception) {
        Log.error("CORS exception: ", exception);
        callback.onFailure(null);
    }
}

From source file:ccc.client.gwt.core.GWTRequestExecutor.java

License:Open Source License

/** {@inheritDoc} */
@Override//from   w  w  w  . j a  va2 s . c o  m
public void invokeRequest(final Request request) {

    final ResponseHandler handler = request.getCallback();

    final String url = InternalServices.globals.appURL() + request.getPath();
    final RequestBuilder builder = new RequestBuilder(getMethod(request.getMethod()), url);

    builder.setHeader("Accept", "application/json");
    builder.setHeader(HttpMethod.OVERRIDE_HEADER, request.getMethod().toString());

    if (HttpMethod.POST.equals(request.getMethod()) || HttpMethod.PUT.equals(request.getMethod())) {
        builder.setHeader("Content-Type", "application/json");
        builder.setRequestData(request.getBody());
    }

    builder.setCallback(new GWTRequestCallback(handler));

    try {
        builder.send();
        GWT.log("Sent request: " + request.getMethod() + " " + url, null);
    } catch (final RequestException e) {
        handler.onFailed(e);
    }
}

From source file:ch.sebastienzurfluh.swissmuseum.core.client.model.io.CakeConnector.java

License:Open Source License

private <T> void asyncRequest(final Requests request, final int referenceId, String args,
        final AsyncCallback<T> callback) {

    final StringBuilder url = new StringBuilder(cakePath + request.getURL());

    url.append(CAKE_ARGS_SEPARATOR).append(args);
    url.append(CAKE_ARGS_SEPARATOR).append(referenceId);

    url.append(CAKE_SUFFIX);// w w w  . j a v a  2s . co  m

    System.out.println("Making async request on " + url);

    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url.toString());

    try {
        builder.sendRequest(null, new RequestCallback() {
            public void onError(Request httpRequest, Throwable exception) {
                System.out.println("JSON request failure. " + exception.getLocalizedMessage());
                // we do nothing else than log
                callback.onFailure(exception);
            }

            @SuppressWarnings("unchecked")
            public void onResponseReceived(Request httpRequest, Response response) {
                if (200 == response.getStatusCode()) {
                    System.out.println("Got answer from async request.");

                    JsArray<Entry> entries = evalJson(response.getText().trim());

                    // BLACKBOX!!!
                    DataType dataType = DataType.PAGE;

                    switch (request) {
                    case GETALLGROUPMENUS:
                        dataType = DataType.GROUP;
                    case GETALLPAGEMENUSFROMGROUP:
                        // menu collection
                        LinkedList<MenuData> dataList = new LinkedList<MenuData>();
                        for (int i = 0; i < entries.length(); i++) {
                            Entry entry = entries.get(i);
                            dataList.add(parseMenuData(entry, referenceId, dataType));
                        }
                        // give callback
                        callback.onSuccess((T) dataList);
                        break;
                    case GETDATA:
                    case GETFIRSTDATAOFGROUP:
                        // single data
                        Data parsedData = parseData(entries.get(0), referenceId, DataType.PAGE);
                        callback.onSuccess((T) parsedData);
                        break;
                    case GETRESOURCE:
                        ResourceData parsedData2 = parseResourceData(entries.get(0), referenceId);
                        callback.onSuccess((T) parsedData2);
                    }
                }
            }
        });
    } catch (Exception e) {
        callback.onFailure(e);
    }
}

From source file:ch.sebastienzurfluh.swissmuseum.parcours.client.model.SimpleCakeBridge.java

License:Open Source License

public <ResponseType extends JavaScriptObject> void sendRequest(String requestString,
        final WithResult<ResponseType> withResult) {
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET,
            cakePath + CAKE_ARGS_SEPARATOR + requestString + CAKE_SUFFIX);

    try {//from  ww  w . j  a va 2s .  c om
        builder.sendRequest(null, new RequestCallback() {
            public void onError(Request httpRequest, Throwable exception) {
                System.out.println("JSON request failure. " + exception.getLocalizedMessage());
                // we do nothing else than log
            }

            @SuppressWarnings("unchecked")
            public void onResponseReceived(Request httpRequest, Response response) {
                if (200 == response.getStatusCode()) {
                    System.out.println("Got answer from async request.");

                    withResult.execute((ResponseType) evalJson(response.getText().trim()));
                }
            }
        });
    } catch (Exception e) {
        System.out.println("JSON request error. " + e.getLocalizedMessage());
        // we do nothing else than log
    }
}

From source file:ch.systemsx.cisd.openbis.generic.client.web.client.application.framework.HtmlPage.java

License:Apache License

public HtmlPage(final String widgetId) {
    final RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, pageUrl = createUrl(widgetId));
    try {/*www.  j a v a 2  s  .  c  om*/
        requestBuilder.sendRequest(null, new HelpRequestCallback());
    } catch (final RequestException ex) {
        displayException(ex);
    }
}

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 va2  s.  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.mousecontrol.client.TouchPadWidget.java

License:Apache License

/**
 * starts the execution of the component
 *//*from  w w  w  .  j a va 2 s. c o m*/
public void start() {
    if (!running) {
        label.setText("looking for available remote-clients");
        getAvailableClients(new Command() {

            @Override
            public void execute() {
                label.setText((availableClients == null ? "0" : availableClients.length) + " clients found");
                if (getCurrentClient() != null) {
                    label.setText("looking for cursor on client " + getCurrentClient());
                    lookForCursor = new Timer() {

                        @Override
                        public void run() {
                            try {
                                new RequestBuilder(RequestBuilder.GET, GWT.getHostPageBaseURL() + controlServlet
                                        + "?a=x"
                                        + (getCurrentClient() != null ? "&targetUUID=" + getCurrentClient()
                                                : "")
                                        + (uuid != null ? "&uuid=" + uuid : "")
                                        + (host != null ? "&host=" + host : "")
                                        + (port != null ? "&port=" + port : "")).sendRequest(null,
                                                new RequestCallback() {

                                                    @Override
                                                    public void onResponseReceived(Request request,
                                                            Response response) {
                                                        if (response.getStatusCode() > 400)
                                                            onError(request, null);
                                                        label.setText("GOT DATA: " + response.getText());
                                                        String color = extractColor(response);
                                                        if (color == null || color.isEmpty()
                                                                || color.equals("#null"))
                                                            color = null;
                                                        extractLastAction(response);

                                                        setScreenDimension(extractScreenDimensions(response));
                                                        if (color != null) {
                                                            setColor(color);
                                                            cursorAssigned();
                                                        } else {
                                                            noCursorAvailable();
                                                        }
                                                    }

                                                    @Override
                                                    public void onError(Request request, Throwable exception) {
                                                        noCursorAvailable();
                                                    }
                                                });
                            } catch (RequestException e) {
                                noCursorAvailable();
                            }
                        }
                    };
                    lookForCursor.run();
                }
            }
        });
    }
}

From source file:ch.unifr.pai.twice.mousecontrol.client.TouchPadWidget.java

License:Apache License

/**
 * Sends the given query to the mouse pointer controller servlet
 * //from w ww .  j  a  va 2  s.  c om
 * @param query
 * @param callback
 */
protected void send(String query, final Command callback) {
    try {
        if (active) {

            new RequestBuilder(RequestBuilder.GET,
                    GWT.getHostPageBaseURL() + controlServlet + "?" + (query != null ? query : "a=x")
                            + (getCurrentClient() != null ? "&targetUUID=" + getCurrentClient() : "")
                            + (uuid != null ? "&uuid=" + uuid : "") + (host != null ? "&host=" + host : "")
                            + (port != null ? "&port=" + port : "") + ("&user=" + Authentication.getUserName()))
                                    .sendRequest(null, new RequestCallback() {

                                        @Override
                                        public void onResponseReceived(Request request, Response response) {
                                            if (response.getStatusCode() > 400)
                                                onError(request, null);
                                            String color = extractColor(response);
                                            if (response.getText().trim().isEmpty()) {
                                                label.setText("No connection available");
                                                noConnection = true;
                                            } else {
                                                if (noConnection) {
                                                    label.setText("");
                                                    noConnection = false;
                                                }

                                                if (color == null || color.isEmpty() || color.equals("#null"))
                                                    color = null;
                                                extractLastAction(response);
                                                setColor(color);
                                                setScreenDimension(extractScreenDimensions(response));
                                                if (callback != null)
                                                    callback.execute();
                                            }
                                        }

                                        @Override
                                        public void onError(Request request, Throwable exception) {
                                            setActive(false);
                                        }
                                    });
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ch.unifr.pai.twice.mousecontrol.client.TouchPadWidget.java

License:Apache License

/**
 * Request the server for available shared devices
 * //  w  w w.  j  a v a  2 s .  c om
 * @param callback
 */
private void getAvailableClients(final Command callback) {
    try {
        new RequestBuilder(RequestBuilder.GET, GWT.getHostPageBaseURL() + controlServlet + "?a=g")
                .sendRequest(null, new RequestCallback() {

                    @Override
                    public void onResponseReceived(Request request, Response response) {
                        if (response.getText() != null && !response.getText().isEmpty()) {
                            availableClients = response.getText().split("\n");
                        }
                        if (callback != null)
                            callback.execute();
                    }

                    @Override
                    public void onError(Request request, Throwable exception) {
                        GWT.log("Available clients request", exception);
                        if (callback != null)
                            callback.execute();
                    }
                });
    } catch (RequestException e) {
        GWT.log("Request Exception", e);
        if (callback != null)
            callback.execute();

    }
}

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

License:Apache License

/**
 * Send the screenshot to the server//from  w  w  w . j  a v  a2 s . c om
 */
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();
        }
    }
}