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

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

Introduction

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

Prototype

RequestCallback

Source Link

Usage

From source file:ca.upei.ic.timetable.client.FindCourseViewController.java

License:Apache License

public SemesterModelView getSemesterModel() {
    if (!semesterLoaded_) {
        Service.defaultInstance().askSemesters(new RequestCallback() {

            public void onError(Request request, Throwable exception) {
                app_.error(ApplicationController.OOPS, exception);
            }/* ww  w.j  a  va  2 s. c o m*/

            public void onResponseReceived(Request request, Response response) {
                try {
                    String text = response.getText();
                    JSONValue value = JSONParser.parse(text);
                    semester_.loadJSON(value);
                    semesterLoaded_ = true;
                } catch (Exception e) {
                    app_.error("Error: " + response.getText(), e);
                }
            }

        });
    }

    return semester_;
}

From source file:cc.kune.core.client.actions.xml.XMLActionsParser.java

License:GNU Affero Public License

/**
 * Instantiates a new xML actions parser.
 *
 * @param errHandler/* w  ww. ja  v  a  2s  .  co m*/
 *          the err handler
 * @param contentViewer
 *          the content viewer
 * @param actionRegistry
 *          the action registry
 * @param contentService
 *          the content service
 * @param session
 *          the session
 * @param stateManager
 *          the state manager
 * @param i18n
 *          the i18n
 * @param newMenusRegistry
 *          the new menus registry
 * @param services
 *          the services
 */
@Inject
public XMLActionsParser(final ErrorHandler errHandler, final ContentViewerPresenter contentViewer,
        final ActionRegistryByType actionRegistry, final Provider<ContentServiceAsync> contentService,
        final Session session, final StateManager stateManager, final I18nTranslationService i18n,
        final NewMenusForTypeIdsRegistry newMenusRegistry, final Services services) {
    this.errHandler = errHandler;
    this.contentViewer = contentViewer;
    this.actionRegistry = actionRegistry;
    this.contentService = contentService;
    this.session = session;
    this.stateManager = stateManager;
    this.i18n = i18n;
    this.newMenusRegistry = newMenusRegistry;
    submenus = new HashMap<String, SubMenuDescriptor>();
    // Based on:
    // http://www.roseindia.net/tutorials/gwt/retrieving-xml-data.shtml
    final RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET,
            XMLActionsConstants.ACTIONS_XML_LOCATION_PATH_ABS);
    session.onAppStart(false, new AppStartHandler() {
        @Override
        public void onAppStart(final AppStartEvent event) {
            try {
                requestBuilder.sendRequest(null, new RequestCallback() {
                    @Override
                    public void onError(final Request request, final Throwable ex) {
                        onFailed(ex);
                    }

                    @Override
                    public void onResponseReceived(final Request request, final Response response) {
                        parse(new XMLKuneClientActions(services, response.getText()));
                    }
                });
            } catch (final RequestException ex) {
                onFailed(ex);
            }
        }
    });
}

From source file:cc.kune.core.client.auth.WaveClientSimpleAuthenticator.java

License:GNU Affero Public License

/**
 * Do login./*from   w w  w  .  j a  v a 2 s . com*/
 * 
 * @param userWithoutDomain
 *          the user without domain
 * @param passwd
 *          the passwd
 * @param callback
 *          the callback
 */
public void doLogin(final String userWithoutDomain, final String passwd, final AsyncCallback<Void> callback) {
    final RequestBuilder request = new RequestBuilder(RequestBuilder.POST, "/auth/signin");
    final StringBuffer params = new StringBuffer();
    params.append("address=");
    params.append(URL.encodeQueryString(userWithoutDomain));
    params.append("&password=");
    params.append(URL.encodeQueryString(passwd));
    params.append("&signIn=");
    params.append(URL.encodeQueryString("Sign in"));
    try {
        request.setHeader("Content-Type", "application/x-www-form-urlencoded");
        request.sendRequest(params.toString(), new RequestCallback() {
            @Override
            public void onError(final Request request, final Throwable exception) {
                StackErrorEvent.fire(eventBus, exception);
                callback.onFailure(exception);
            }

            @Override
            public void onResponseReceived(final Request request, final Response response) {
                callback.onSuccess(null);
            }
        });
    } catch (final RequestException e) {
        StackErrorEvent.fire(eventBus, e);
    }
}

From source file:cc.kune.core.client.auth.WaveClientSimpleAuthenticator.java

License:GNU Affero Public License

/**
 * Do logout./*from  w  ww.j a  va2 s.co  m*/
 * 
 * @param callback
 *          the callback
 */
public void doLogout(final AsyncCallback<Void> callback) {
    // Original: <a href=\"/auth/signout?r=/\">"
    final RequestBuilder request = new RequestBuilder(RequestBuilder.GET, "/auth/signout");
    try {
        request.setHeader("Content-Type", "application/x-www-form-urlencoded");
        final StringBuffer params = new StringBuffer();
        request.sendRequest(params.toString(), new RequestCallback() {
            @Override
            public void onError(final Request request, final Throwable exception) {
                StackErrorEvent.fire(eventBus, exception);
                callback.onFailure(exception);
            }

            @Override
            public void onResponseReceived(final Request request, final Response response) {
                callback.onSuccess(null);
            }
        });
    } catch (final RequestException e) {
        StackErrorEvent.fire(eventBus, e);
    }
}

From source file:cc.kune.core.client.sitebar.search.MultivalueSuggestBox.java

License:GNU Affero Public License

/**
 * Retrieve Options (name-value pairs) that are suggested from the REST
 * endpoint//www .j av a2s. 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(mrestEndpointUrl + "?" + SearcherConstants.QUERY_PARAM + "=" + query + "&"
                    + SearcherConstants.START_PARAM + "=" + from + "&" + SearcherConstants.LIMIT_PARAM + "="
                    + PAGE_SIZE));

    // Set our headers
    builder.setHeader("Accept", "application/json; charset=utf-8");

    // Fails on chrome
    // builder.setHeader("Accept-Charset", "UTF-8");

    builder.setCallback(new RequestCallback() {

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

        @Override
        public void onResponseReceived(final com.google.gwt.http.client.Request request,
                final 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();

                    final String longName = jsonOpt.get(OptionResultSet.DISPLAY_NAME).isString().stringValue();
                    final String shortName = jsonOpt.get(OptionResultSet.VALUE).isString().stringValue();
                    final JSONValue groupTypeJsonValue = jsonOpt.get("groupType");
                    final String prefix = groupTypeJsonValue.isString() == null ? ""
                            : GroupType.PERSONAL.name().equals(groupTypeJsonValue.isString().stringValue())
                                    ? I18n.t("User") + ": "
                                    : I18n.t("Group") + ": ";
                    option.setName(prefix
                            + (!longName.equals(shortName) ? longName + " (" + shortName + ")" : shortName));
                    option.setValue(jsonOpt.get(OptionResultSet.VALUE).isString().stringValue());
                    options.addOption(option);
                }
            }
            callback.success(options);
        }
    });

    try {
        if (lastQuery != null && lastQuery.isPending()) {
            lastQuery.cancel();
        }
        lastQuery = builder.send();
    } catch (final RequestException e) {
        updateFormFeedback(FormFeedback.ERROR, "Error: " + e.getMessage());
    }

}

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

License:GNU Affero Public License

/**
 * Process request./*from   w w w.j  av  a  2  s.  c o m*/
 *
 * @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: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);/*from  w w w. j  a  v  a  2  s .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 {// w  w  w.  j  a  v  a2  s  .co  m
        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.unifr.pai.twice.comm.clientServerTime.client.ClientServerTimeOffset.java

License:Apache License

static RequestCallback createServerTimeOffsetRequestCallback(final AsyncCallback<Long> callback,
        final long startTime) {
    return new RequestCallback() {

        @Override//from www  .  j  a  v a 2 s .  c o  m
        public void onResponseReceived(Request request, Response response) {
            long endTime = getCurrentTime();
            long duration = endTime - startTime;
            String result = response.getText();
            if (result != null) {
                long serverTime = Long.parseLong(result);
                // We assume that the upload and download for a very small request are the same (50% of the request duration for upload, 50% for
                // download)
                long difference = serverTime - (endTime - (duration / 2));
                callback.onSuccess(difference);
            }
        }

        @Override
        public void onError(Request request, Throwable exception) {
            callback.onFailure(exception);

        }
    };
}

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

License:Apache License

/**
 * starts the execution of the component
 *///from w w w  . jav  a 2s.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();
                }
            }
        });
    }
}