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:com.teardrop.client.EditTree.java

License:Apache License

private void doPostURL(String post, String url) {
    RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url));
    try {//from  ww  w  .j ava 2 s.  com
        builder.setHeader("Content-Length", String.valueOf(post.length()));
        builder.sendRequest(post, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
                Window.alert("Couldn't connect to server (could be timeout, SOP violation, etc.)");
            }

            public void onResponseReceived(Request request, Response response) {
                if (200 == response.getStatusCode()) {
                    centerPanel.remove(editPanel);
                    engTree.loadEngineTree();
                } else {
                    Window.alert("Incorrect status: " + response.getStatusText());
                }
            }
        });
    } catch (RequestException e) {
        Window.alert("Couldn't connect to server (could be timeout, SOP violation, etc.)");
    }
}

From source file:com.teardrop.client.EngineTree.java

License:Apache License

public void loadEngineTree() {
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(DEFAULT_SEARCH_URL));
    try {/*  ww w  .j  av  a 2s  .  co m*/
        builder.sendRequest(null, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
                displayError("Couldn't connect to server (could be timeout, SOP violation, etc.)");
            }

            public void onResponseReceived(Request request, Response response) {
                if (200 == response.getStatusCode()) {
                    try {
                        JSONValue jsonValue = JSONParser.parse(response.getText());
                        generateEngineTree(getRootNode(), jsonValue);
                    } catch (JSONException e) {
                        displayError(response.getText());
                    }
                    // Process the response in response.getText()
                } else if (403 == response.getStatusCode()) {
                    new Login(new Login.LoginCallback() {
                        public void onCloseRun() {
                            loadEngineTree();
                        }
                    });
                } else {
                    displayError(response.getStatusText());
                }
            }
        });
    } catch (RequestException e) {
        // Couldn't connect to server        
    }
}

From source file:com.teardrop.client.Login.java

License:Apache License

void doAuthenticate(String post) {
    RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(LOGIN_URL));
    try {/*from ww w  . ja va2s .c o m*/
        builder.setHeader("Content-Length", String.valueOf(post.length()));
        builder.sendRequest(post, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
                // ("Couldn't connect to server (could be timeout, SOP violation, etc.)");     
            }

            public void onResponseReceived(Request request, Response response) {
                lc.onCloseRun();
                loginWindow.close();
            }
        });
    } catch (RequestException e) {
        //setProgessMessage("Couldn't connect to server (could be timeout, SOP violation, etc.)");      
    }
}

From source file:com.teardrop.client.PerformSearch.java

License:Apache License

private void doPostURL(String post, String url) {
    RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url));
    try {//from  www  .j a va  2 s. c  om
        builder.setHeader("Content-Length", String.valueOf(post.length()));
        if (!tdsession.equals("")) {
            builder.setHeader("TDSession", tdsession);
        }
        builder.sendRequest(post, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
                setProgessMessage("Couldn't connect to server (could be timeout, SOP violation, etc.)");
            }

            public void onResponseReceived(Request request, Response response) {
                if (200 == response.getStatusCode()) {
                    parseCookies(response);
                    updateGrid(response.getText());
                } else {
                    setProgessMessage("Incorrect status: " + response.getStatusText());
                }
            }
        });
    } catch (RequestException e) {
        setProgessMessage("Couldn't connect to server (could be timeout, SOP violation, etc.)");
    }
}

From source file:com.textquo.dreamcode.client.publicstores.GlobalStore.java

License:Open Source License

/**
 * Add new object./*from  w  w w  .j ava2  s.co m*/
 * Server stores object with id generated by a sharded counter (if not given)
 *
 * @param callback
 */
public void add(String type, String id, String jsonObject, final DreamcodeCallback callback) {
    String url = Routes.DREAMCODE + Routes.COLLECTIONS + "?type=" + type + "&id=" + id;
    RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
    try {
        builder.setHeader("content-type", "application/json");
        builder.sendRequest(jsonObject, new RequestCallback() {
            public void onResponseReceived(com.google.gwt.http.client.Request request,
                    com.google.gwt.http.client.Response response) {
                String jsonResponse = response.getText();
                if (response.getStatusCode() == com.google.gwt.http.client.Response.SC_OK) {
                    callback.success(jsonResponse);
                } else {
                    callback.failure(new Throwable("Error: " + response.getStatusCode()));
                }
            }

            public void onError(com.google.gwt.http.client.Request request, Throwable throwable) {
                callback.failure(throwable);
            }
        });
    } catch (RequestException e) {
        callback.failure(new Throwable(e.getMessage()));
    }
    // TODO: Make this code below work:
    //        ClientResource resource = new ClientResource(Routes.DREAMCODE + Routes.COLLECTIONS);
    //        resource.setOnResponse(new Uniform() {
    //            public void handle(Request request, Response response) {
    //                try {
    //                    Status status = response.getStatus();
    //                    if (!Status.isError(status.getCode())) {
    //                        String jsonResponse = response.getEntity().getText();
    //                        callback.success(jsonResponse);
    //                    } else {
    //                        callback.failure(new Throwable("Error: " + status.getCode()));
    //                    }
    //                } catch (Exception e) {
    //                    callback.failure(new Throwable(e.getMessage()));
    //                }
    //            }
    //        });
    //        JsniHelper.consoleLog("Adding object id=" + id + " type=" + type + " data=" + jsonObject);
    //        if(JsonHelper.isValid(jsonObject)){
    //            resource.getReference().addQueryParameter("type", type);
    //            resource.getReference().addQueryParameter("id",id);
    //            resource.post(jsonObject, MediaType.APPLICATION_JSON);
    //        } else {
    //            callback.failure(new Throwable("Invalid JSON object"));
    //        }
}

From source file:de.eckhartarnold.client.ImageCollectionReader.java

License:Apache License

private void readJSON(String url, JSONDelegate task, IMessage error) {
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
    JSONReceiver receiver = new JSONReceiver(url, task, error);
    if (!receiver.extractJSONfromHTML()) {
        try {// w  ww .ja  v a  2  s  .com
            builder.sendRequest(null, receiver);
        } catch (RequestException e) {
            error.message("Couldn't retrieve JSON: " + url + "<br />" + e.getMessage());
        }
    }
}

From source file:de.lilawelt.zmachine.client.machine.Memory.java

License:Open Source License

public void initialize(ZUserInterface ui, String storyFile) {
    Log.debug("Trying to load story from " + storyFile);

    final PopupPanel p = new PopupPanel();
    p.add(new HTML("Please wait, loading game..."));
    p.center();/*from   ww  w.jav a  2s.c  o m*/
    p.show();

    zui = ui;
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(storyFile));

    try {
        builder.sendRequest(null, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
                // Couldn't connect to server (could be timeout, SOP violation, etc.)
                Log.debug("Server connect failed");
                zui.fatal("Could not connect to server: " + exception.getMessage());
            }

            public void onResponseReceived(Request request, Response response) {
                if (200 == response.getStatusCode()) {
                    String story = response.getText();
                    Log.debug("Text length: " + story.length());

                    //String[] tokens = story.split(" ");

                    dataLength = story.length();
                    Log.debug("Initial length: " + dataLength);
                    data = new byte[dataLength];
                    int count = 0;
                    for (int i = 0; i < dataLength - 3; i++) {
                        char e1 = story.charAt(i++);
                        //if ( i < 100 )
                        //Log.debug("Charvalue at pos "+i+": "+e1);
                        if (e1 == '\n' || e1 == '\r') {
                            e1 = story.charAt(i++);
                            if (e1 == '\n' || e1 == '\r') {
                                e1 = story.charAt(i++);
                            }
                        }
                        e1 = (char) tab.indexOf(e1);
                        char e2 = story.charAt(i++);
                        if (e2 == '\n') {
                            e2 = story.charAt(i++);
                        }
                        e2 = (char) tab.indexOf(e2);
                        char e3 = story.charAt(i++);
                        if (e3 == '\n') {
                            e3 = story.charAt(i++);
                        }
                        e3 = (char) tab.indexOf(e3);
                        char e4 = story.charAt(i);
                        if (e4 == '\n') {
                            e4 = story.charAt(++i);
                        }
                        e4 = (char) tab.indexOf(e4);

                        //Log.debug("Values: "+e1+" "+e2+" "+e3+" "+e4);

                        byte c1 = (byte) ((e1 << 2) + (e2 >> 4));
                        byte c2 = (byte) (((e2 & 15) << 4) + (e3 >> 2));
                        byte c3 = (byte) (((e3 & 3) << 6) + e4);

                        //c1 =  (byte) ( e2 >> 4);

                        data[count++] = c1;
                        if (e3 != 64)
                            data[count++] += c2;
                        if (e4 != 64)
                            data[count++] += c3;

                    }
                    /* data = new byte[dataLength];
                    int count = 0;
                    for ( int i = 0; i < dataLength; i++ ) {
                       char c = story.charAt(i);
                       if ( (int) c == 127 ) {
                          i++;
                          if ( (int) story.charAt(i) == 127 ) {
                             i++;
                             data[count] = 127;
                             data[count] += 127;
                          } else {
                             data[count] = 127;
                          }
                          data[count] += story.charAt(i);
                       }  else {
                          data[count] = (byte) c;
                       }
                       //Log.debug("Text item: "+(int)c);
                       count++;
                    }  */

                    dataLength = count;
                    Log.debug("Loaded " + count + " bytes of story.");
                    /* Log.debug("byte0: "+fetchByte(0));
                    Log.debug("byte1: "+fetchByte(1));
                    for ( int i = 0; i < dataLength; i++ ) {
                    if ( i != fetchByte(i))
                       Log.debug("Data "+i+": "+fetchByte(i));
                    } */
                    p.hide();
                    Machine.get().start();
                } else {
                    Log.debug("Server returned error on load: " + response.getText());
                    zui.fatal("Server returned error on load: " + response.getText());
                }
            }

        });
    } catch (RequestException e) {
        // Couldn't connect to server   
        zui.fatal("I/O error loading storyfile.");
    }

    Log.debug("Initialized memory");

}

From source file:ecc.gwt.warning.client.JsonRpc.java

License:Apache License

/**
 * Executes a json-rpc request.// w w  w  .ja  v a  2 s  .  c  o m
 * 
 * @param url
 *            The location of the service
 * @param username
 *            The username for basic authentification
 * @param password
 *            The password for basic authentification
 * @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, Map paramMap, boolean isStream,
        final AsyncCallback callback) {

    HashMap request = new HashMap();
    request.putAll(paramMap);
    //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);

    String body = "";
    if (isStream) {
        builder.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        body = new String(encode(request));
    } else {
        builder.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        StringBuffer sb = new StringBuffer();
        for (Iterator iterator = request.entrySet().iterator(); iterator.hasNext();) {
            Map.Entry<String, Object> entry = (Map.Entry<String, Object>) iterator.next();
            sb.append(entry.getKey()).append("=").append(String.valueOf(entry.getValue())).append("&");

        }
        body = sb.toString();
        if (body.endsWith("&"))
            body = body.substring(0, body.length() - 1);
    }
    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:edu.caltech.ipac.firefly.core.HtmlRegionLoader.java

public void load(String url, final String regionName) {
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
    try {//from  w w  w  .  j  av  a  2 s  . c  o m
        builder.sendRequest(null, new RequestCallback() {
            public void onResponseReceived(com.google.gwt.http.client.Request req, Response res) {
                updateHtml(res.getText(), regionName);
            }

            public void onError(com.google.gwt.http.client.Request request, Throwable exception) {
            }
        });
    } catch (RequestException e) {
        e.printStackTrace();
    }

}

From source file:edu.cudenver.bios.glimmpse.client.panels.ResultsDisplayPanel.java

License:Open Source License

private void sendPowerRequest() {
    showWorkingDialog();/*  www  . ja v  a2 s .  co m*/
    String requestEntityBody = manager.getPowerRequestXML();
    matrixDisplayPanel.loadFromXML(requestEntityBody);
    RequestBuilder builder = null;
    switch (solutionType) {
    case POWER:
        builder = new RequestBuilder(RequestBuilder.POST, POWER_URL);
        break;
    case TOTAL_N:
        builder = new RequestBuilder(RequestBuilder.POST, SAMPLE_SIZE_URL);
        break;
    }

    try {
        builder.setHeader("Content-Type", "text/xml");
        builder.sendRequest(requestEntityBody, new RequestCallback() {

            public void onError(Request request, Throwable exception) {
                showError("Calculation failed: " + exception.getMessage());
            }

            public void onResponseReceived(Request request, Response response) {
                if (STATUS_CODE_OK == response.getStatusCode()
                        || STATUS_CODE_CREATED == response.getStatusCode()) {
                    showResults(response.getText());
                } else {
                    showError("Calculation failed: [HTTP STATUS " + response.getStatusCode() + "] "
                            + response.getText());
                }
            }
        });
    } catch (Exception e) {
        showError("Failed to send the request: " + e.getMessage());
    }
}