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:grails.plugin.console.charts.client.application.AbstractApplicationPresenter.java

License:Apache License

@Override
protected void onReset() {
    if (result == null) {
        if (AppUtils.QUERY != null) {
            if (AppUtils.CONNECTION_STRING == null) {
                getView().error("Not connected to server");

                return;
            }// w  w w  .java  2  s. c o  m

            if (AppUtils.CONNECT_STATUS == null) {
                try {
                    String url = AppUtils.getConnectPath() + "?data="
                            + URL.encodePathSegment(AppUtils.CONNECTION_STRING);
                    RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, url);

                    rb.setCallback(new RequestCallback() {
                        @Override
                        public void onResponseReceived(Request request, Response response) {
                            ConnectStatus status = AutoBeanCodex
                                    .decode(AppUtils.BEAN_FACTORY, ConnectStatus.class, response.getText())
                                    .as();

                            if (status.isConnected()) {
                                AppUtils.CONNECT_STATUS = status;

                                ConnectedEvent.fire(AbstractApplicationPresenter.this,
                                        status.getConnectionString(), status.getStatus());

                                loadData();
                            } else {
                                String error = (status.getException() != null
                                        ? " (" + status.getException() + ") "
                                        : "") + status.getError();
                                Window.alert("Error occurred: " + error);
                            }
                        }

                        @Override
                        public void onError(Request request, Throwable exception) {
                            Window.alert("Error occurred: " + exception.getMessage());
                        }
                    });

                    rb.send();
                } catch (RequestException e) {
                    Window.alert("Error occurred: " + e.getMessage());
                }
            } else {
                loadData();
            }
        }
    } else {
        getView().view(AppUtils.VIEW, result);
    }
}

From source file:grails.plugin.console.charts.client.application.AbstractApplicationPresenter.java

License:Apache License

private void loadData() {
    getView().loading();/*from  www  .jav  a2s. c o  m*/

    try {
        RequestBuilder rb = new RequestBuilder(RequestBuilder.GET,
                AppUtils.getDataPath() + "?query="
                        + URL.encodeQueryString(AppUtils.encodeBase64(AppUtils.QUERY)) + "&appearance="
                        + URL.encodePathSegment(AppUtils.encodeBase64(AppUtils.APPEARANCE))
                        + "&connectionString=" + URL.encodePathSegment(AppUtils.CONNECTION_STRING));

        rb.setCallback(new RequestCallback() {
            @Override
            public void onResponseReceived(Request request, Response response) {
                try {
                    JSONValue value = JSONParser.parseStrict(response.getText());
                    result = value.isObject();

                    if (result.get("error") != null) {
                        getView().error(result);
                        return;
                    }

                    getView().view(AppUtils.VIEW, result);
                } catch (Exception exception) {
                    getView().error("Can't parse data JSON: " + exception.getMessage());
                } finally {
                    result = null;
                }
            }

            @Override
            public void onError(Request request, Throwable exception) {
                getView().error("Error occurred: " + exception.getMessage());
            }
        });

        rb.send();
    } catch (RequestException e) {
        getView().error("Error occurred: " + e.getMessage());
    }
}

From source file:grails.plugin.console.charts.client.application.share.AbstractSharePresenter.java

License:Apache License

@Override
public void onGetLinkClicked(String format) {
    ShareDetails details = getView().getEditorDriver().flush();
    details.setConnectionString(AppUtils.CONNECTION_STRING);
    details.setQuery(AppUtils.QUERY);/*from   w w  w  .j a va  2 s.  c  o m*/
    details.setAppearance(AppUtils.APPEARANCE);
    details.setView(AppUtils.VIEW);

    // Retrieve the AutoBean controller
    AutoBean<ShareDetails> bean = AutoBeanUtils.getAutoBean(details);

    String json = AutoBeanCodex.encode(bean).getPayload();

    try {
        RequestBuilder rb = new RequestBuilder(RequestBuilder.POST,
                AppUtils.getLinkPath() + "?format=" + format);

        rb.sendRequest(json, new RequestCallback() {
            @Override
            public void onResponseReceived(Request request, Response response) {
                JSONValue value = JSONParser.parseStrict(response.getText());
                JSONObject result = value.isObject();

                if (result.get("error") != null) {
                    Window.alert("Error occurred: " + result.get("error").isString().stringValue());
                    return;
                }

                getView().setLink(result.get("link").isString().stringValue());
            }

            @Override
            public void onError(Request request, Throwable exception) {
                Window.alert("Error occurred: " + exception.getMessage());
            }
        });
    } catch (RequestException e) {
        Window.alert("Error occurred: " + e.getMessage());
    }

}

From source file:gwt.dojo.showcase.client.Showcase.java

License:Apache License

private void loadAndSwitchView(final ListItem listItem) {

    final RequestCallback requestCallback = new RequestCallback() {
        @Override/*  w w w .j av  a 2s.  c om*/
        public void onResponseReceived(Request request, Response response) {
            if (200 == response.getStatusCode()) {
                try {
                    // Process the response in response.getText()

                    // fillInDemoSource();
                    DivElement rightPane = Document.get().getElementById("rightPane").cast();
                    DivElement tmpContainer = Document.get().createDivElement();
                    tmpContainer.setInnerHTML(response.getText());
                    rightPane.appendChild(tmpContainer);
                    JsArray ws = MobileParser.parse(tmpContainer);
                    for (int i = 0, n = ws.length(); i < n; i++) {
                        if (ws.getJsObject(i).hasProperty("startup")) {
                            _WidgetBase w = ws.getJsObject(i);
                            w.startup();
                        }
                    }

                    // reparent
                    rightPane.removeChild(tmpContainer);
                    NodeList<Node> children = tmpContainer.getChildNodes();
                    for (int i = 0, n = children.getLength(); i < n; i++) {
                        Element elem = tmpContainer.getChild(i).cast();
                        rightPane.appendChild(elem);
                    }

                    showProgressIndicator(false);
                    Scheduler.get().scheduleDeferred(new ScheduledCommand() {
                        @Override
                        public void execute() {
                            initView(listItem);
                            listItem.transitionTo(listItem.getString("viewId"));
                            // triggreTransition(listItem,
                            // listItem.getString("id"));
                        }
                    });
                } catch (Exception e) {
                    Window.alert("Error: " + e);
                }
            } else {
                // Handle the error. Can get the status text from
                // response.getStatusText()
                onError(request, new RequestException("HTTP Error: " + response.getStatusCode()));
            }
        }

        @Override
        public void onError(Request request, Throwable exception) {
            Window.alert("Failed to load demo.");
            showProgressIndicator(false);
            inTransitionOrLoading = false;
        }
    };

    showProgressIndicator(true);

    String url = listItem.getString("demourl");
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));

    Request request = null;
    try {
        request = builder.sendRequest(null, requestCallback);
    } catch (RequestException e) {
        requestCallback.onError(request, e);
    }
}

From source file:gwt.g3d.resources.client.impl.AbstractExternalMeshResource.java

License:Apache License

/**
 * Helper method for loading a mesh./*  ww  w  . j a va2  s.  c  o  m*/
 * 
 * @param externalImageResource
 * @param textureResource
 */
protected void getMesh(String url, final MeshDataInfo meshDataInfo,
        final ResourceCallback<MeshResource> callback) {
    RequestBuilder request = new RequestBuilder(RequestBuilder.POST, url);
    request.setCallback(new RequestCallback() {
        @Override
        public void onResponseReceived(Request request, Response response) {
            callback.onSuccess(new AbstractMeshResource(meshDataInfo, JSONParser.parse(response.getText())) {
                @Override
                public String getName() {
                    return AbstractExternalMeshResource.this.getName();
                }
            });
        }

        @Override
        public void onError(Request request, Throwable exception) {
            callback.onError(new ResourceException(AbstractExternalMeshResource.this, exception.getMessage()));
        }
    });
    try {
        request.send();
    } catch (RequestException e) {
        callback.onError(new ResourceException(AbstractExternalMeshResource.this, e.getMessage()));
    }
}

From source file:ibeans.client.IBeansConsole2.java

License:Open Source License

protected void loadTabs(final IBeansConsole2 console) {
    if (user.isShowWelcome()) {
        final TabItem welcomeTab = new TabItem();
        welcomeTab.setText("Welcome");
        welcomeTab.setScrollMode(Style.Scroll.AUTOX);
        RequestBuilder req = new RequestBuilder(RequestBuilder.GET,
                GWT.getHostPageBaseURL() + "welcome-beta.html");
        req.setCallback(new RequestCallback() {
            public void onResponseReceived(Request request, Response response) {
                welcomeTab.add(new Html(response.getText()));
                //                    final CheckBox box = new CheckBox(" Do not show this screen in future");
                //                    //box.setStyleName("welcome-check");
                //                    box.addClickHandler(new ClickHandler()
                //                    {
                //                        public void onClick(ClickEvent event)
                //                        {
                //                            user.setShowWelcome(box.getValue());
                //                            saveUserInfo(user);
                //                        }
                //                    });
                //                    welcomeTab.add(box);
                welcomeTab.layout();/*from   ww w . j a va  2s  . co m*/
            }

            public void onError(Request request, Throwable exception) {
                errorStatus(exception);
            }
        });
        try {
            req.send();
        } catch (RequestException e) {
            errorStatus(e);
        }
        tabPanel.add(welcomeTab);
    }

    TabItem configTab = new TabItem();
    configTab.setText("Configure");
    configTab.setLayout(new FlowLayout());
    configTab.add(new InstalledPluginsPanel(console));
    configTab.layout();

    TabItem storeTab = new TabItem();
    storeTab.setText("iBeans Central");
    storeTab.add(new IBeansCentralPanel(console));

    TabItem examplesTab = new TabItem();
    examplesTab.setText("Examples");
    examplesTab.add(new ExamplesPanel(console));

    tabPanel.add(examplesTab);
    tabPanel.add(configTab);
    tabPanel.add(storeTab);
}

From source file:io.apiman.manager.ui.client.local.pages.ImportServicesPage.java

License:Apache License

/**
 * Called when the user clicks Next on the wadl page of the wizard.
 * @param event/*from w  w  w.  jav  a 2s . c  om*/
 */
@EventHandler("wadlNext")
public void onWadlNext(ClickEvent event) {
    wadlNext.onActionStarted();
    if (wadlUrl.getValue() != null && !wadlUrl.getValue().isEmpty()) {
        String proxyUrl = GWT.getHostPageBaseURL();
        if (!proxyUrl.endsWith("/")) { //$NON-NLS-1$
            proxyUrl = proxyUrl + "/"; //$NON-NLS-1$
        }
        proxyUrl = proxyUrl + "proxies/fetch"; //$NON-NLS-1$
        final String url = wadlUrl.getValue();
        RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, proxyUrl);
        builder.setHeader("X-Apiman-Url", url); //$NON-NLS-1$
        builder.setCallback(new RequestCallback() {
            @Override
            public void onResponseReceived(Request request, Response response) {
                if (response.getStatusCode() == 200) {
                    String wadlData = response.getText();
                    List<ServiceVersionBean> servicesToImport = new ArrayList<ServiceVersionBean>();
                    processWadl(wadlData, servicesToImport, url);
                    wadlNext.onActionComplete();
                    services.setValue(servicesToImport);
                    servicesSelectAll.setValue(Boolean.TRUE);
                    if (servicesToImport.isEmpty()) {
                        yesButton.setEnabled(false);
                    }
                    showConfirmationPage("wadlPage"); //$NON-NLS-1$
                } else {
                    try {
                        throw new Exception(i18n.format(AppMessages.WADL_FETCH_FAIL,
                                String.valueOf(response.getStatusCode()), response.getStatusText()));
                    } catch (Exception e) {
                        dataPacketError(e);
                    }
                }
            }

            @Override
            public void onError(Request request, Throwable exception) {
                dataPacketError(exception);
            }
        });
        try {
            builder.send();
        } catch (RequestException e) {
            dataPacketError(e);
        }
    } else if (!wadlFile.getValue().isEmpty() || !wadlDropZone.getValue().isEmpty()) {
        final List<JavaScriptFile> files = new ArrayList<JavaScriptFile>();
        if (!wadlFile.getValue().isEmpty()) {
            files.addAll(wadlFile.getValue());
        } else {
            files.addAll(wadlDropZone.getValue());
        }
        final List<JavaScriptFile> loadedFiles = new ArrayList<JavaScriptFile>();
        final List<ServiceVersionBean> servicesToImport = new ArrayList<ServiceVersionBean>();
        for (final JavaScriptFile file : files) {
            logger.info("Loading data from WADL: " + file.getName()); //$NON-NLS-1$
            file.readAsText(new IDataReadHandler() {
                @Override
                public void onDataLoaded(String data) {
                    processWadl(data, servicesToImport, file.getName());
                    loadedFiles.add(file);
                    if (loadedFiles.size() == files.size()) {
                        wadlNext.onActionComplete();
                        services.setValue(servicesToImport);
                        servicesSelectAll.setValue(Boolean.TRUE);
                        if (servicesToImport.isEmpty()) {
                            yesButton.setEnabled(false);
                        }
                        showConfirmationPage("wadlPage"); //$NON-NLS-1$
                    }
                }
            });
        }
    }
}

From source file:io.apiman.manager.ui.client.local.services.ConfigurationService.java

License:Apache License

/**
 * Starts a timer that will refresh the configuration's bearer token
 * periodically./*  w ww.  j a  v  a2s  .c  o  m*/
 */
private void startTokenRefreshTimer() {
    Timer timer = new Timer() {
        @Override
        public void run() {
            GWT.log("Refreshing auth token."); //$NON-NLS-1$

            final String url = GWT.getHostPageBaseURL() + "rest/tokenRefresh"; //$NON-NLS-1$
            RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
            try {
                builder.sendRequest(null, new RequestCallback() {
                    @Override
                    public void onResponseReceived(Request request, Response response) {
                        if (response.getStatusCode() != 200) {
                            GWT.log("[001] Authentication token refresh failure: " + url); //$NON-NLS-1$
                        } else {
                            BearerTokenCredentialsBean bean = new BearerTokenCredentialsBean();
                            JSONObject root = JSONParser.parseStrict(response.getText()).isObject();
                            bean.setToken(root.get("token").isString().stringValue()); //$NON-NLS-1$
                            bean.setRefreshPeriod((int) root.get("refreshPeriod").isNumber().doubleValue()); //$NON-NLS-1$
                            configuration.getApi().getAuth().setBearerToken(bean);
                        }
                        startTokenRefreshTimer();
                    }

                    @Override
                    public void onError(Request request, Throwable exception) {
                        GWT.log("[002] Authentication token refresh failure: " + url); //$NON-NLS-1$
                    }
                });
            } catch (RequestException e) {
                GWT.log("Authentication token refresh failed!"); //$NON-NLS-1$
            }
        }
    };
    timer.schedule(configuration.getApi().getAuth().getBearerToken().getRefreshPeriod() * 1000);
}

From source file:io.reinert.requestor.RequestDispatcherImpl.java

License:Apache License

private <D> RequestCallback getRequestCallback(final Request request, final XMLHttpRequest xhr,
        final Deferred<D> deferred, final Class<D> resolveType, final Class<?> parametrizedType) {
    return new RequestCallback() {
        public void onResponseReceived(com.google.gwt.http.client.Request gwtRequest,
                com.google.gwt.http.client.Response gwtResponse) {
            final String responseType = xhr.getResponseType();

            final Payload payload = responseType.isEmpty() || responseType.equalsIgnoreCase("text")
                    ? new Payload(xhr.getResponseText())
                    : new Payload(xhr.getResponse());

            final RawResponseImpl response = new RawResponseImpl(gwtResponse.getStatusCode(),
                    gwtResponse.getStatusText(), new Headers(gwtResponse.getHeaders()),
                    ResponseType.of(responseType), payload);

            evalResponse(request, deferred, resolveType, parametrizedType, response);
        }/*from   w ww. ja  va  2s.c o  m*/

        public void onError(com.google.gwt.http.client.Request gwtRequest, Throwable exception) {
            if (exception instanceof com.google.gwt.http.client.RequestTimeoutException) {
                // reject as timeout
                com.google.gwt.http.client.RequestTimeoutException e = (com.google.gwt.http.client.RequestTimeoutException) exception;
                deferred.reject(new RequestTimeoutException(request, e.getTimeoutMillis()));
            } else {
                // reject as generic request exception
                deferred.reject(new RequestException(exception));
            }
        }
    };
}

From source file:mcamara.client.QwebScormApp.java

License:Open Source License

public void onModuleLoad() {
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, "cuestionario.xml");
    try {//from w  w  w  .  j  a va 2s  .  co m
        builder.sendRequest(null, new RequestCallback() {
            public void onResponseReceived(Request request, Response response) {
                cuestionario = Util.XMLtoCuestionario(response.getText());
                m = Util.getMensajes(cuestionario.getIdioma());
                if (cuestionario.getTipo().equals("autoevaluacion")) {
                    DialogBox ppresentacion = new PPresentacion(cuestionario);
                    RootPanel.get().add(ppresentacion);
                } else if (cuestionario.getTipo().equals("tutorial")) {
                    DialogBox ptutorial = new PTutorial(cuestionario, -1);
                    RootPanel.get().add(ptutorial);
                } else
                    Window.alert(m.cuestionarionovalido());
            }

            public void onError(Request request, Throwable exception) {
                Window.alert(m.error());
            }
        });
    } catch (RequestException e) {
        Window.alert(m.error());
    }
}