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

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

Introduction

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

Prototype

public void setCallback(RequestCallback callback) 

Source Link

Document

Sets the response handler for this request.

Usage

From source file:io.fns.calculator.client.XSRFTokenCallbackDispatcherFilter.java

License:Apache License

@Override
public boolean filter(Method method, RequestBuilder builder) {
    XSRFTokenCallbackFilter filter = new XSRFTokenCallbackFilter(xsrf);
    RetryingCallbackFactory factory = new RetryingCallbackFactory(filter);
    FilterawareRequestCallback callback = factory.createCallback(method);
    builder.setCallback(callback);
    return true;/* ww  w .  j a  va 2  s  .c om*/
}

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
 * /*from  w ww  .j  ava 2  s  .  co  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.s17fabu.vip.gwt.showcase.client.ContentWidget.java

License:Apache License

/**
 * Load the contents of a remote file into the specified widget.
 * /*from   w ww .  j  a  v  a  2 s  . c  om*/
 * @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);
    }
}

From source file:nl.strohalm.cyclos.mobile.client.utils.RestRequest.java

License:Open Source License

/**
 * Sends a request using the given callback to notify the results. 
 * This method does not uses authentication, to perform authenticated 
 * requests see {@link #sendAuthenticated(AsyncCallback)}
 *//*  w  w  w .  j  a va 2 s .c o m*/
public Request send(AsyncCallback<T> callback) {

    // Start loading progress
    CyclosMobile.get().getMainLayout().startLoading();

    String url = "";

    // Append parameters as GET
    if (httpMethod == RequestBuilder.GET) {
        url = Configuration.get().getServiceUrl(this.path, parameters);
    } else {
        url = Configuration.get().getServiceUrl(this.path);
    }

    RequestBuilder request = new RequestBuilder(httpMethod, url);
    request.setTimeoutMillis(20 * 1000); // 20 seconds
    request.setHeader("Accept", "application/json");
    request.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");

    if (httpMethod == RequestBuilder.POST) {
        request.setHeader("Content-Type", "application/json");

        // Send post body parameters
        if (parameters != null) {
            String json = parameters.toJSON();
            request.setRequestData(json);
        } else {
            // Send post without data
            request.setRequestData("");
        }
    }
    // Send a JSON post object
    if (postObject != null) {
        request.setHeader("Content-Type", "application/json");
        request.setRequestData(new JSONObject(postObject).toString());
    }
    if (username != null && !username.isEmpty()) {
        request.setHeader("Authorization", "Basic " + Base64.encode(username + ":" + password));
    }
    request.setCallback(new RequestCallbackAdapter(callback));
    try {
        // Send request
        return request.send();
    } catch (RequestException e) {
        callback.onFailure(e);

        // Stop loading progress
        CyclosMobile.get().getMainLayout().stopLoading();

        // Returns an emulated request, which does nothing
        return new Request() {
            @Override
            public void cancel() {
            }

            @Override
            public boolean isPending() {
                return false;
            }
        };
    }
}

From source file:org.abondar.industrial.videorouterdemo.client.MainEntryPoint.java

public void getMonitorsByRest() {

    try {/*from  www. j a  v a2  s.  c  o  m*/
        String url = URL.encode("http://localhost:8084/VideoRestService/vrService/monitors");

        RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);

        builder.setRequestData(parseCredentialsToJSON());
        builder.setHeader("Content-type", "application/json");

        RequestCallback rc = new RequestCallback() {

            @Override
            public void onResponseReceived(Request request, Response response) {

                try {

                    MonitorRootObjectAutoBeanFactory factory = GWT
                            .create(MonitorRootObjectAutoBeanFactory.class);
                    MonitorReader mr = new MonitorReader(factory, MonitorRootObject.class);
                    ListLoadResult<Device> mons = mr.read(null, response.getText());
                    List<Device> monList = mons.getData();

                    for (Device mn : monList) {
                        monitorData.add(mn.getName());
                    }

                } catch (Exception e) {
                    Window.alert("Parsing error " + e.toString());

                }

                getSourcesByRest();
                getConnected();

            }

            @Override
            public void onError(Request request, Throwable exception) {
                Window.alert("Connection failed  " + exception.toString() + " " + showTime());
            }

        };

        builder.setCallback(rc);
        builder.send();

    } catch (RequestException ex) {

        Window.alert("Connection failed  " + ex.toString() + " " + showTime());

    }

}

From source file:org.abondar.industrial.videorouterdemo.client.MainEntryPoint.java

public void getConnected() {
    try {/*from   w w  w  .j a v a 2  s  . c  o m*/
        String url = URL.encode("http://localhost:8084/VideoRestService/vrService/rules");

        RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);

        builder.setRequestData(parseCredentialsToJSON());
        builder.setHeader("Content-type", "application/json");
        builder.setIncludeCredentials(true);

        RequestCallback rc = new RequestCallback() {

            @Override
            public void onResponseReceived(Request request, Response response) {

                RuleRootObjectAutoBeanFactory factory = GWT.create(RuleRootObjectAutoBeanFactory.class);
                RuleReader rr = new RuleReader(factory, RuleRootObject.class);
                ListLoadResult<Rule> rll = rr.read(null, response.getText());
                List<Rule> ruleList = rll.getData();

                for (Rule r : ruleList) {
                    ConnectionBean cb = new ConnectionBean();

                    cb.setDestnation(r.getDevice());
                    cb.setSourceID(r.getSourcePort());
                    cb.setName(r.getName());
                    connections.add(cb);
                }

            }

            @Override
            public void onError(Request request, Throwable exception) {

                Window.alert("Can't get data  " + exception.toString() + " " + showTime());
            }

        };
        builder.setCallback(rc);
        builder.send();

    } catch (RequestException ex) {
        Window.alert("Can't get data  " + ex.toString() + " " + showTime());

    }

}

From source file:org.abondar.industrial.videorouterdemo.client.MainEntryPoint.java

public void getSourcesByRest() {

    try {// ww  w  .  j ava 2s. c  o m
        String url = URL.encode("http://localhost:8084/VideoRestService/vrService/sources");

        RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);

        builder.setRequestData(parseCredentialsToJSON());
        builder.setHeader("Content-type", "application/json");
        builder.setIncludeCredentials(true);

        RequestCallback rc = new RequestCallback() {

            @Override
            public void onResponseReceived(Request request, Response response) {

                hp.add(conTime);
                conTime.setText("Connection time  " + showTime());

                try {
                    SourcesRootObjectAutoBeanFactory factory = GWT
                            .create(SourcesRootObjectAutoBeanFactory.class);
                    SourceReader sr = new SourceReader(factory, SourcesRootObject.class);
                    ListLoadResult<Source> src = sr.read(null, response.getText());
                    List<Source> srcList = src.getData();

                    for (Source sc : srcList) {
                        SourceBean sb = new SourceBean();
                        sb.setId(sc.getNodeConnector());
                        if (sc.getMonitorPortType().equals("Edge-SPAN")) {
                            if (sc.getDescription().equals("") || sc.getDescription() == null) {
                                sb.setName("Undefined Source");

                            } else {
                                sb.setName(sc.getDescription());

                            }
                        }
                        sourcesData.add(sb);

                    }
                } catch (Exception e) {
                    Window.alert("Parsing error " + e.toString());

                }

                showSourcesMonitors();

                monitorData.clear();
                sourcesData.clear();

            }

            @Override
            public void onError(Request request, Throwable exception) {

                Window.alert("Connection failed  " + exception.toString() + " " + showTime());
            }

        };
        builder.setCallback(rc);
        builder.send();

    } catch (RequestException ex) {
        Window.alert("Connection failed  " + ex.toString() + " " + showTime());

    }

}

From source file:org.abondar.industrial.videorouterdemo.client.MainEntryPoint.java

public void establishConnection(String sourceID, String source) {

    try {/*from w w w.  j a v a 2 s  . c om*/

        String url = URL.encode("http://localhost:8084/VideoRestService/vrService/connect");

        RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);

        builder.setRequestData(parseRuleToJSON(sourceID, source));
        builder.setHeader("Content-type", "application/json");

        RequestCallback rc = new RequestCallback() {

            @Override
            public void onResponseReceived(Request request, Response response) {
                if (response.getStatusCode() == 200 || response.getStatusCode() == 201) {
                    Window.alert("Connection established " + showTime() + "\n" + response.getText());

                } else {
                    Window.alert(
                            "Can't establish a connection due to " + response.getText() + " " + showTime());

                }
            }

            @Override
            public void onError(Request request, Throwable exception) {

                Window.alert("Can't establish a connection  " + exception.toString());

            }

        };

        builder.setCallback(rc);
        builder.send();

    } catch (RequestException ex) {

        Window.alert("Can't establish a connection  " + ex.toString());

    }
}

From source file:org.abondar.industrial.videorouterdemo.client.MainEntryPoint.java

public void deleteConnection(String srcNameTODelete, final String sourceID, final String srcnameToConnect) {

    try {/*from  w  w w .j ava  2  s.com*/
        String url = URL.encode("http://localhost:8084/VideoRestService/vrService/delete");

        RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);

        builder.setRequestData(parseRuleNameToJSON(srcNameTODelete));
        builder.setHeader("Content-type", "application/json");

        RequestCallback rc = new RequestCallback() {

            @Override
            public void onResponseReceived(Request request, Response response) {
                establishConnection(sourceID, srcnameToConnect);
            }

            @Override
            public void onError(Request request, Throwable exception) {

                Window.alert("Can't delete a connection  " + exception.toString());

            }

        };

        builder.setCallback(rc);
        builder.send();

    } catch (RequestException ex) {

        Window.alert("Can't delete a connection  " + ex.toString());

    }
}

From source file:org.activityinfo.ui.client.component.report.editor.map.symbols.AdminGeometryProvider.java

License:Open Source License

private void fetchGeometry(final int levelId, final AsyncCallback<AdminGeometry> callback) {
    RequestBuilder request = new RequestBuilder(RequestBuilder.GET,
            "/resources/adminLevel/" + levelId + "/entities/polylines");
    request.setCallback(new RequestCallback() {

        @Override/*from ww w.j  av  a 2s  .  c  o  m*/
        public void onResponseReceived(Request request, Response response) {
            try {
                AdminGeometry geometry = AdminGeometry.fromJson(response.getText());
                cache.put(levelId, geometry);
                callback.onSuccess(geometry);
            } catch (Exception e) {
                callback.onFailure(e);
            }
        }

        @Override
        public void onError(Request request, Throwable exception) {
            callback.onFailure(exception);
        }
    });
    try {
        request.send();
    } catch (RequestException e) {
        callback.onFailure(e);
    }
}