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:n3phele.client.presenter.helpers.AuthenticatedRequestFactory.java

License:Open Source License

public static RequestBuilder request(Method httpMethod, String url, String user, String secret) {

    RequestBuilder request = new RequestBuilder(httpMethod, url);
    //request.setHeader("Authorization", "Basic " + Base64.encode(user + ":" + secret));
    request.setUser(user.replace("@", ".at-."));
    request.setPassword(secret);/*from w  ww .j  a va 2s. co m*/
    return request;
}

From source file:n3phele.client.view.ForgotPasswordView.java

License:Open Source License

private void createUser(String url, final String email, String firstName, String lastName) {

    // Send request to server and catch any errors.
    RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
    builder.setUser("signup");
    builder.setPassword("newuser");
    builder.setHeader("Content-type", "application/x-www-form-urlencoded");
    StringBuilder args = new StringBuilder();
    args.append("email=");
    args.append(URL.encodeQueryString(email));
    args.append("&firstName=");
    args.append(URL.encodeQueryString(firstName));
    args.append("&lastName=");
    args.append(URL.encodeQueryString(lastName));

    try {//from  w w w  .  j  a  va 2s . c o m
        @SuppressWarnings("unused")
        Request request = builder.sendRequest(args.toString(), new RequestCallback() {
            public void onError(Request request, Throwable exception) {
                Window.alert("User create error " + exception.getMessage());
            }

            public void onResponseReceived(Request request, Response response) {
                GWT.log("Got reply");
                if (201 == response.getStatusCode()) {
                    Window.alert("User " + email + " password reset. Check your email for details.");
                } else {
                    Window.alert("User password reset failure " + response.getStatusText() + "\n"
                            + response.getText());
                }
            }

        });
    } catch (RequestException e) {
        Window.alert("User password reset exception " + e.getMessage());
    }
}

From source file:n3phele.client.view.NewUserView.java

License:Open Source License

private void createUser(String url, final String email, String firstName, String lastName, String password,
        String ec2Id, String ec2Secret) {

    // Send request to server and catch any errors.
    RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
    builder.setUser("signup");
    builder.setPassword("newuser");
    builder.setHeader("Content-type", "application/x-www-form-urlencoded");
    StringBuilder args = new StringBuilder();
    args.append("email=");
    args.append(URL.encodeQueryString(email));
    args.append("&firstName=");
    args.append(URL.encodeQueryString(firstName));
    args.append("&lastName=");
    args.append(URL.encodeQueryString(lastName));
    if (password != null && password.length() > 0) {
        args.append("&secret=");
        args.append(URL.encodeQueryString(password));
    }//from  w w w.  j av a 2s. com
    if (ec2Id != null && ec2Id.length() != 0) {
        args.append("&ec2Id=");
        args.append(URL.encodeQueryString(ec2Id));
        args.append("&ec2Secret=");
        args.append(URL.encodeQueryString(ec2Secret));
    }
    try {
        @SuppressWarnings("unused")
        Request request = builder.sendRequest(args.toString(), new RequestCallback() {
            public void onError(Request request, Throwable exception) {
                Window.alert("User create error " + exception.getMessage());
            }

            public void onResponseReceived(Request request, Response response) {
                GWT.log("Got reply");
                if (201 == response.getStatusCode()) {
                    Window.alert("User " + email + " created.");
                } else {
                    Window.alert("User create failure " + response.getStatusText() + "\n" + response.getText());
                }
            }

        });
    } catch (RequestException e) {
        Window.alert("Account create exception " + e.getMessage());
    }
}

From source file:name.cphillipson.experimental.gwt.client.module.common.widget.suggest.MultivalueSuggestBox.java

License:Apache License

/**
 * Retrieve Options (name-value pairs) that are suggested from the REST endpoint
 * /*  w  ww .j a  v  a2 s .  c  o  m*/
 * @param query
 *            - the String search term
 * @param from
 *            - the 0-based begin index int
 * @param to
 *            - the end index inclusive int
 * @param callback
 *            - the OptionQueryCallback to handle the response
 */
private void queryOptions(final String query, final int from, final int to,
        final OptionQueryCallback callback) {
    final RequestBuilder builder = new RequestBuilder(RequestBuilder.GET,
            URL.encode(m_restEndpointUrl + "?q=" + query + "&indexFrom=" + from + "&indexTo=" + to));

    // Set our headers
    builder.setHeader("Accept", "application/json");
    builder.setHeader("Accept-Charset", "UTF-8");

    builder.setCallback(new RequestCallback() {

        @Override
        public void onResponseReceived(com.google.gwt.http.client.Request request, Response response) {
            final JSONValue val = JSONParser.parse(response.getText());
            final JSONObject obj = val.isObject();
            final int totSize = (int) obj.get(OptionResultSet.TOTAL_SIZE).isNumber().doubleValue();
            final OptionResultSet options = new OptionResultSet(totSize);
            final JSONArray optionsArray = obj.get(OptionResultSet.OPTIONS).isArray();

            if (options.getTotalSize() > 0 && optionsArray != null) {

                for (int i = 0; i < optionsArray.size(); i++) {
                    if (optionsArray.get(i) == null) {
                        /*
                         * This happens when a JSON array has an invalid trailing comma
                         */
                        continue;
                    }

                    final JSONObject jsonOpt = optionsArray.get(i).isObject();
                    final Option option = new Option();
                    option.setName(jsonOpt.get(OptionResultSet.DISPLAY_NAME).isString().stringValue());
                    option.setValue(jsonOpt.get(OptionResultSet.VALUE).isString().stringValue());
                    options.addOption(option);
                }
            }
            callback.success(options);
        }

        @Override
        public void onError(com.google.gwt.http.client.Request request, Throwable exception) {
            callback.error(exception);
        }
    });

    try {
        builder.send();
    } catch (final RequestException e) {
        updateFormFeedback(FormFeedback.ERROR, "Error: " + e.getMessage());
    }
}

From source file:net.autosauler.ballance.client.gui.ChangeLogPanel.java

License:Apache License

/**
 * Instantiates a new change log panel.//from  w w  w.j a  v a 2  s. c  o  m
 */
private ChangeLogPanel() {

    MainPanel.setCommInfo(true);
    try {
        new RequestBuilder(RequestBuilder.GET, "CHANGELOG").sendRequest("", new RequestCallback() {
            @Override
            public void onError(Request res, Throwable throwable) {
                MainPanel.setCommInfo(false);
                Log.error(throwable.getMessage());
            }

            @Override
            public void onResponseReceived(Request request, Response response) {
                MainPanel.setCommInfo(false);
                String text = response.getText();
                HTML w = new HTML("<p>" + text + "</p>");
                d.setWidget(w);

            }
        });
    } catch (RequestException e) {
        MainPanel.setCommInfo(false);
        Log.error(e.getMessage());
    }

    d = new DecoratorPanel();
    d.setWidth("100%");

    initWidget(d);
}

From source file:net.dancioi.jcsphotogallery.client.model.ReadXMLGeneric.java

License:Open Source License

/**
 * Gets the XML file from http server./*from  w  w  w. j av  a  2s .  c  om*/
 */
public void readXmlFile(final String file, final int flag) {
    RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, file);
    try {
        requestBuilder.sendRequest(null, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
                showException("Error sending request");
            }

            public void onResponseReceived(Request request, Response response) {
                if (200 == response.getStatusCode()) {
                    parseXMLString(response.getText(), flag); // careful here, this is an asynchronous callback.
                } else if (404 == response.getStatusCode()) {
                    showException("File " + file + " not found on server. Wrong name or missing.");
                } else {
                    showException("Other exception on GET the " + file + " file");
                }
            }
        });
    } catch (RequestException ex) {
        new ReadException("Error sending request");
    }
}

From source file:net.ffxml.gwt.json.client.JsonRpc.java

License:Apache License

/**
 * Executes a json-rpc request.//w w w .ja  v a 2s. 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 {//from w  w  w.j  a v a2  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  av  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

/**
 * Load the contents of a remote file into the specified widget.
 * // w  w w.j  av a  2 s . com
 * @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("&nbsp;&nbsp;" + 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);
    }
}