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:com.fredhat.gwt.xmlrpc.client.XmlRpcClient.java

License:Open Source License

/**
 * Executes an asynchronous XMLRPC call to the server with a specified username
 * and password.  If the execution was successful, the callback's {@link AsyncCallback#onSuccess(Object)} 
 * method will be invoked with the return value as the argument.  If the 
 * execution failed for any reason, the callback's {@link AsyncCallback#onFailure(Throwable)} method will 
 * be invoked with an instance of {@link XmlRpcException} instance as it's argument.
 * @param username the username for authentication
 * @param password the password for authentication
 * @param methodName the name of the XMLRPC method
 * @param params the parameters for the XMLRPC method
 * @param callback the logic implementation for handling the XMLRPC responses.
 * @deprecated As of XMLRPC-GWT v1.1,//from w w  w  .  ja  v  a 2s .c om
 * build an {@link XmlRpcRequest} then call {@link XmlRpcRequest#execute()}
 */
@SuppressWarnings("unchecked")
@Deprecated
public void execute(String username, String password, String methodName, Object[] params,
        final AsyncCallback callback) {
    if (methodName == null || methodName.equals("")) {
        callback.onFailure(new XmlRpcException("The method name parameter cannot be null"));
        return;
    }
    if (params == null)
        params = new Object[0];

    Document request = buildRequest(methodName, params);
    if (debugMessages)
        System.out.println("** Request **\n" + request + "\n*************");

    RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST, serverURL);
    requestBuilder.setHeader("Content-Type", "text/xml");
    requestBuilder.setTimeoutMillis(timeout);
    if (username != null)
        requestBuilder.setUser(username);
    if (password != null)
        requestBuilder.setPassword(password);

    try {
        requestBuilder.sendRequest(request.toString(), new RequestCallback() {
            public void onResponseReceived(Request req, Response res) {
                if (res.getStatusCode() != 200) {
                    callback.onFailure(new XmlRpcException("Server returned " + "response code "
                            + res.getStatusCode() + " - " + res.getStatusText()));
                    return;
                }
                Object responseObj = buildResponse(res.getText());
                if (responseObj instanceof XmlRpcException)
                    callback.onFailure((XmlRpcException) responseObj);
                else
                    callback.onSuccess(responseObj);
            }

            public void onError(Request req, Throwable t) {
                callback.onFailure(t);
            }
        });
    } catch (RequestException e) {
        callback.onFailure(new XmlRpcException("Couldn't make server request", e));
    }
}

From source file:com.fredhat.gwt.xmlrpc.client.XmlRpcRequest.java

License:Open Source License

/**
 * Invokes the XML-RPC method asynchronously.  All success and failure logic will
 * be in your {@link AsyncCallback} that you defined in the constructor.
 *///  ww  w .ja v a 2s . c  o  m
public void execute() {
    if (methodName == null || methodName.equals("")) {
        callback.onFailure(new XmlRpcException("The method name parameter cannot be null"));
        return;
    }

    if (params == null)
        params = new Object[] {};

    Document request = buildRequest(methodName, params);
    if (client.getDebugMode())
        System.out.println("** Request **\n" + request + "\n*************");

    RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST, client.getServerURL());
    requestBuilder.setHeader("Content-Type", "text/xml");

    //Ak existuje cookie posli ju v hlavicke
    if (Cookies.getCookie("sessionID") != null) {
        requestBuilder.setHeader("sessionID", Cookies.getCookie("sessionID"));
    }

    requestBuilder.setTimeoutMillis(client.getTimeoutMillis());
    if (client.getUsername() != null)
        requestBuilder.setUser(client.getUsername());
    if (client.getPassword() != null)
        requestBuilder.setPassword(client.getPassword());

    try {

        requestBuilder.sendRequest(request.toString(), new RequestCallback() {
            public void onResponseReceived(Request req, Response res) {
                if (res.getStatusCode() != 200) {
                    callback.onFailure(new XmlRpcException("Server returned " + "response code "
                            + res.getStatusCode() + " - " + res.getStatusText()));
                    return;
                }
                try {
                    T responseObj = buildResponse(res.getText());
                    callback.onSuccess(responseObj);

                } catch (XmlRpcException e) {
                    callback.onFailure(e);
                } catch (ClassCastException e) {
                    callback.onFailure(e);
                }
            }

            public void onError(Request req, Throwable t) {
                callback.onFailure(t);
            }
        });
    } catch (RequestException e) {
        callback.onFailure(new XmlRpcException("Couldn't make server request.  Are you violating the "
                + "Same Origin Policy?  Error: " + e.getMessage(), e));
    }
}

From source file:com.fullmetalgalaxy.client.widget.HTMLInclude.java

License:Open Source License

public HTMLInclude(final String url) {
    super();//  w ww .  ja  v a 2  s  .c o m
    final HTMLInclude widget = this;
    try {
        new RequestBuilder(RequestBuilder.GET, url).sendRequest("", new RequestCallback() {
            @Override
            public void onError(Request request, Throwable exception) {
                GWT.log("HTMLInclude: error fetching " + url, exception);
            }

            @Override
            public void onResponseReceived(Request request, Response response) {
                if (response.getStatusCode() == 200) {
                    widget.setHTML(response.getText());
                } else {
                    GWT.log("HTMLInclude: bad code when fetching " + url + "[" + response.getStatusCode() + "]",
                            null);
                }
            }
        });
    } catch (RequestException e) {
        GWT.log("HTMLInclude: exception thrown fetching " + url, e);
    }
}

From source file:com.github.gwtbootstrap.showcase.client.AsyncCodeBlock.java

License:Apache License

public void setUrl(String url) {
    ProgressBar progressBar = new ProgressBar(ProgressBarBase.Style.ANIMATED);
    progressBar.setPercent(100);/*from w  w  w.j a  v  a  2 s .c  o m*/
    codePanel.setWidget(progressBar);

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

    builder.setCallback(new RequestCallback() {

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

            String text = response.getText();

            CodeBlock block = new CodeBlock(text);

            block.setLinenums(true);

            codePanel.setWidget(block);
        }

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

        }
    });
}

From source file:com.github.tdesjardins.ol3.demo.client.example.WfsExample.java

License:Apache License

@Override
public void show(String exampleId) {

    // create a vector layer
    Vector vectorSource = new Vector();
    VectorLayerOptions vectorLayerOptions = new VectorLayerOptions();
    vectorLayerOptions.setSource(vectorSource);
    ol.layer.Vector wfsLayer = new ol.layer.Vector(vectorLayerOptions);

    // create a view
    View view = new View();

    Coordinate centerCoordinate = new Coordinate(-8908887.277395891, 5381918.072437216);
    view.setCenter(centerCoordinate);/*from www  . j a  va2  s .c  om*/
    view.setZoom(12);
    view.setMaxZoom(19);

    // create the map
    MapOptions mapOptions = OLFactory.createOptions();
    mapOptions.setTarget(exampleId);
    mapOptions.setView(view);

    Map map = new Map(mapOptions);

    map.addLayer(DemoUtils.createOsmLayer());
    map.addLayer(wfsLayer);

    Wfs wfs = new Wfs();
    WfsWriteFeatureOptions wfsWriteFeatureOptions = new WfsWriteFeatureOptions();

    String[] featureTypes = { "water_areas" };
    wfsWriteFeatureOptions.setSrsName(DemoConstants.EPSG_3857);
    wfsWriteFeatureOptions.setFeaturePrefix("osm");
    wfsWriteFeatureOptions.setFeatureNS("http://openstreemap.org");
    wfsWriteFeatureOptions.setFeatureTypes(featureTypes);

    // set a filter
    wfsWriteFeatureOptions.setFilter(new IsLike("name", "Mississippi*"));
    wfsWriteFeatureOptions.setOutputFormat("application/json");

    // create WFS-XML node
    Node wfsNode = wfs.writeGetFeature(wfsWriteFeatureOptions);

    RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST,
            "https://ahocevar.com/geoserver/wfs");
    requestBuilder.setRequestData(new XMLSerializer().serializeToString(wfsNode));
    requestBuilder.setCallback(new RequestCallback() {

        @Override
        public void onResponseReceived(com.google.gwt.http.client.Request request, Response response) {

            GeoJson geoJson = new GeoJson();
            Feature[] features = geoJson.readFeatures(response.getText());

            vectorSource.addFeatures(features);
            map.getView().fit(vectorSource.getExtent());
        }

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

    });

    try {
        requestBuilder.send();
    } catch (RequestException e) {
        Window.alert(e.getMessage());
    }

}

From source file:com.google.appinventor.client.wizards.TemplateUploadWizard.java

License:Open Source License

/**
 * Creates a new project from a Zip file and lists it in the ProjectView.
 *
 * @param projectName project name/*from   ww w .j av a  2s.  c om*/
 * @param onSuccessCommand command to be executed after process creation
 *   succeeds (can be {@code null})
 */
public void createProjectFromExistingZip(final String projectName, final NewProjectCommand onSuccessCommand) {

    // Callback for updating the project explorer after the project is created on the back-end
    final Ode ode = Ode.getInstance();
    final OdeAsyncCallback<UserProject> callback = new OdeAsyncCallback<UserProject>(
            // failure message
            MESSAGES.createProjectError()) {
        @Override
        public void onSuccess(UserProject projectInfo) {
            // Update project explorer -- i.e., display in project view
            if (projectInfo == null) {

                Window.alert(
                        "This template has no aia file. Creating a new project with name = " + projectName);
                ode.getProjectService().newProject(YoungAndroidProjectNode.YOUNG_ANDROID_PROJECT_TYPE,
                        projectName, new NewYoungAndroidProjectParameters(projectName), this);
                return;
            }
            Project project = ode.getProjectManager().addProject(projectInfo);
            if (onSuccessCommand != null) {
                onSuccessCommand.execute(project);
            }
        }
    };

    // Use project RPC service to create the project on back end using
    String pathToZip = "";
    if (usingExternalTemplate) {
        String zipUrl = templateHostUrl + TEMPLATES_ROOT_DIRECTORY + projectName + "/" + projectName
                + PROJECT_ARCHIVE_ENCODED_EXTENSION;
        RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, zipUrl);
        try {
            Request response = builder.sendRequest(null, new RequestCallback() {
                @Override
                public void onError(Request request, Throwable exception) {
                    Window.alert("Unable to load Project Template Data");
                }

                @Override
                public void onResponseReceived(Request request, Response response) {
                    ode.getProjectService().newProjectFromExternalTemplate(projectName, response.getText(),
                            callback);
                }

            });
        } catch (RequestException e) {
            Window.alert("Error fetching project zip file template.");
        }
    } else {
        pathToZip = TEMPLATES_ROOT_DIRECTORY + projectName + "/" + projectName + PROJECT_ARCHIVE_EXTENSION;
        ode.getProjectService().newProjectFromTemplate(projectName, pathToZip, callback);
    }
}

From source file:com.google.appinventor.client.wizards.TemplateUploadWizard.java

License:Open Source License

/**
 * Helper method for opening a project given its Url
 * @param url A string of the form "http://... .asc
 * @param onSuccessCommand/*  w ww.j a  v  a2 s  .c om*/
 */
private static void openTemplateProject(String url, final NewProjectCommand onSuccessCommand) {
    final Ode ode = Ode.getInstance();

    // This Async callback is called after the project is input and created
    final OdeAsyncCallback<UserProject> callback = new OdeAsyncCallback<UserProject>(
            // failure message
            MESSAGES.createProjectError()) {
        @Override
        public void onSuccess(UserProject projectInfo) {
            // This just adds the new project to the project manager, not to AppEngine
            Project project = ode.getProjectManager().addProject(projectInfo);
            // And this opens the project
            if (onSuccessCommand != null) {
                onSuccessCommand.execute(project);
            }
        }
    };

    final String projectName;
    if (url.endsWith(".asc")) {
        projectName = url.substring(1 + url.lastIndexOf("/"), url.lastIndexOf("."));
    } else {
        return;
    }

    // If project of the same name already exists, just open it
    if (!TextValidators.checkNewProjectName(projectName)) {
        Project project = ode.getProjectManager().getProject(projectName);
        if (onSuccessCommand != null) {
            onSuccessCommand.execute(project);
        }
        return; // Don't retrieve the template if the project is a duplicate
    }

    // Here's where we retrieve the template data
    // Do a GET to retrieve data at url
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
    try {
        Request response = builder.sendRequest(null, new RequestCallback() {
            @Override
            public void onError(Request request, Throwable exception) {
                Window.alert("Unable to load Project Template Data");
            }

            // Response received from the GET
            @Override
            public void onResponseReceived(Request request, Response response) {
                // The response.getText is the zip data used to create a new project.
                // The callback opens the project
                ode.getProjectService().newProjectFromExternalTemplate(projectName, response.getText(),
                        callback);
            }
        });
    } catch (RequestException e) {
        Window.alert("Error fetching template file.");
    }
}

From source file:com.google.appinventor.client.wizards.TemplateUploadWizard.java

License:Open Source License

/**
 * Called from ProjectToolbar when user selects a set of external templates. It uses
 *  JsonP to retrieve a json file from an external server.
 *
 * @param hostUrl, Url of the host -- e.g., http://localhost:85/
 *///  w w  w .j  a va  2  s .  co  m
public static void retrieveExternalTemplateData(final String hostUrl) {
    String url = hostUrl + TEMPLATES_ROOT_DIRECTORY + EXTERNAL_JSON_FILE;

    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
    try {
        Request response = builder.sendRequest(null, new RequestCallback() {
            @Override
            public void onError(Request request, Throwable exception) {
                Window.alert("Unable to load Project Template Data.");
                if (instance != null) {
                    instance.populateTemplateDialog(null);
                }
            }

            @Override
            public void onResponseReceived(Request request, Response response) {
                if (response.getStatusCode() != Response.SC_OK) {
                    Window.alert("Unable to load Project Template Data.");
                    return;
                }

                ArrayList<TemplateInfo> externalTemplates = new ArrayList<TemplateInfo>();

                JSONValue jsonVal = JSONParser.parseLenient(response.getText());
                JSONArray jsonArr = jsonVal.isArray();

                for (int i = 0; i < jsonArr.size(); i++) {
                    JSONValue entry1 = jsonArr.get(i);
                    JSONObject entry = entry1.isObject();
                    externalTemplates.add(new TemplateInfo(entry.get("name").isString().stringValue(),
                            entry.get("subtitle").isString().stringValue(),
                            entry.get("description").isString().stringValue(),
                            entry.get("screenshot").isString().stringValue(),
                            entry.get("thumbnail").isString().stringValue()));
                }
                if (externalTemplates.size() == 0) {
                    Window.alert("Unable to retrieve templates for host = " + hostUrl + ".");
                    return;
                }
                addNewTemplateHost(hostUrl, externalTemplates);
            }
        });
    } catch (RequestException e) {
        Window.alert("Error fetching external template.");
    }
}

From source file:com.google.gerrit.client.account.NewAgreementScreen.java

License:Apache License

private void showCLA(final ContributorAgreement cla) {
    current = cla;//ww w .  ja va 2  s . com
    String url = cla.getAgreementUrl();
    if (url != null && url.length() > 0) {
        agreementGroup.setVisible(true);
        agreementHtml.setText(Gerrit.C.rpcStatusWorking());
        if (!url.startsWith("http:") && !url.startsWith("https:")) {
            url = GWT.getHostPageBaseURL() + url;
        }
        final RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, url);
        rb.setCallback(new RequestCallback() {
            public void onError(Request request, Throwable exception) {
                new ErrorDialog(exception).center();
            }

            public void onResponseReceived(Request request, Response response) {
                final String ct = response.getHeader("Content-Type");
                if (response.getStatusCode() == 200 && ct != null
                        && (ct.equals("text/html") || ct.startsWith("text/html;"))) {
                    agreementHtml.setHTML(response.getText());
                } else {
                    new ErrorDialog(response.getStatusText()).center();
                }
            }
        });
        try {
            rb.send();
        } catch (RequestException e) {
            new ErrorDialog(e).show();
        }
    } else {
        agreementGroup.setVisible(false);
    }

    if (contactPanel == null && cla.isRequireContactInformation()) {
        contactPanel = new ContactPanelFull();
        contactGroup.add(contactPanel);
        contactPanel.hideSaveButton();
    }
    contactGroup.setVisible(cla.isRequireContactInformation() && cla.getAutoVerify() != null);
    finalGroup.setVisible(cla.getAutoVerify() != null);
    yesIAgreeBox.setText("");
    submit.setEnabled(false);
}

From source file:com.google.gwt.examples.http.client.GetExample.java

public static void doGet(String url) {
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);

    try {/* w ww.  j a va  2s.  c  om*/
        Request response = builder.sendRequest(null, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
                // Code omitted for clarity
            }

            public void onResponseReceived(Request request, Response response) {
                // Code omitted for clarity
            }
        });
    } catch (RequestException e) {
        // Code omitted for clarity
    }
}