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:org.jboss.bpm.console.client.Authentication.java

License:Open Source License

public void login(String user, String pass) {
    this.username = user;
    this.password = pass;

    String formAction = config.getConsoleServerUrl() + "/rs/identity/secure/j_security_check";
    RequestBuilder rb = new RequestBuilder(RequestBuilder.POST, formAction);
    rb.setHeader("Content-Type", "application/x-www-form-urlencoded");

    try {/*  w  ww .j a va 2  s .  c o  m*/
        rb.sendRequest("j_username=" + user + "&j_password=" + pass, new RequestCallback() {

            public void onResponseReceived(Request request, Response response) {
                ConsoleLog.debug("postLoginCredentials() HTTP " + response.getStatusCode());

                if (response.getText().indexOf("HTTP 401") != -1) // HACK
                {
                    if (callback != null)
                        callback.onLoginFailed(request, new Exception("Authentication failed"));
                    else
                        throw new RuntimeException("Unknown exception upon login attempt");
                } else if (response.getStatusCode() == 200) // it's always 200, even when the authentication fails
                {
                    DeferredCommand.addCommand(new Command() {

                        public void execute() {
                            requestAssignedRoles();
                        }
                    });
                }
            }

            public void onError(Request request, Throwable t) {
                if (callback != null)
                    callback.onLoginFailed(request, new Exception("Authentication failed"));
                else
                    throw new RuntimeException("Unknown exception upon login attempt");
            }
        });
    } catch (RequestException e) {
        ConsoleLog.error("Request error", e);
    }
}

From source file:org.jboss.bpm.console.client.Authentication.java

License:Open Source License

/**
 * Login using specific credentials.//from   ww w.ja  v  a  2  s. c  o m
 * This delegates to {@link com.google.gwt.http.client.RequestBuilder#setUser(String)}
 * and {@link com.google.gwt.http.client.RequestBuilder#setPassword(String)}
 */
private void requestAssignedRoles() {
    RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, rolesUrl);

    ConsoleLog.debug("Request roles: " + rb.getUrl());

    /*if (user != null && pass != null)
    {
      rb.setUser(user);
      rb.setPassword(pass);
            
      if (!GWT.isScript()) // hosted mode only
      {
        rb.setHeader("xtest-user", user);
        rb.setHeader("xtest-pass", pass); // NOTE: This is plaintext, use for testing only
      }
    }*/

    try {
        rb.sendRequest(null, new RequestCallback() {

            public void onResponseReceived(Request request, Response response) {
                ConsoleLog.debug("requestAssignedRoles() HTTP " + response.getStatusCode());

                // parse roles
                if (200 == response.getStatusCode()) {
                    rolesAssigned = Authentication.parseRolesAssigned(response.getText());
                    if (callback != null)
                        callback.onLoginSuccess(request, response);
                } else {
                    onError(request, new Exception(response.getText()));
                }
            }

            public void onError(Request request, Throwable t) {
                // auth failed
                // Couldn't connect to server (could be timeout, SOP violation, etc.)
                if (callback != null)
                    callback.onLoginFailed(request, t);
                else
                    throw new RuntimeException("Unknown exception upon login attempt", t);
            }
        });
    }

    catch (RequestException e1) {
        // Couldn't connect to server
        throw new RuntimeException("Unknown error upon login attempt", e1);
    }
}

From source file:org.jboss.bpm.console.client.Authentication.java

License:Open Source License

public static void logout(final ConsoleConfig conf) {
    RequestBuilder rb = new RequestBuilder(RequestBuilder.POST,
            conf.getConsoleServerUrl() + "/rs/identity/sid/invalidate");

    try {//from   w w  w . j  a  v a  2s . c  om
        rb.sendRequest(null, new RequestCallback() {
            public void onResponseReceived(Request request, Response response) {
                ConsoleLog.debug("logout() HTTP " + response.getStatusCode());

                if (response.getStatusCode() != 200) {
                    ConsoleLog.error(response.getText());
                }
            }

            public void onError(Request request, Throwable t) {
                ConsoleLog.error("Failed to invalidate session", t);
            }
        });
    } catch (RequestException e) {
        ConsoleLog.error("Request error", e);
    }
}

From source file:org.jboss.bpm.console.client.Authentication.java

License:Open Source License

public void logoutAndReload() {
    RequestBuilder rb = new RequestBuilder(RequestBuilder.POST,
            config.getConsoleServerUrl() + "/rs/identity/sid/invalidate");

    try {/*  w w w  .j a  va2  s .c om*/
        rb.sendRequest(null, new RequestCallback() {
            public void onResponseReceived(Request request, Response response) {
                ConsoleLog.debug("logoutAndReload() HTTP " + response.getStatusCode());
                resetState();
                reload();
            }

            public void onError(Request request, Throwable t) {
                ConsoleLog.error("Failed to invalidate session", t);
            }
        });
    } catch (RequestException e) {
        ConsoleLog.error("Request error", e);
    }
}

From source file:org.jboss.bpm.console.client.common.AbstractRESTAction.java

License:Open Source License

public void execute(final Controller controller, final Object object) {
    final String url = getUrl(object);
    RequestBuilder builder = new RequestBuilder(getRequestMethod(), URL.encode(url));

    ConsoleLog.debug(getRequestMethod() + ": " + url);

    try {/*from ww w  .  j a v a  2s .c om*/
        //controller.handleEvent( LoadingStatusAction.ON );
        if (getDataDriven(controller) != null) {
            getDataDriven(controller).setLoading(true);
        }

        final Request request = builder.sendRequest(null, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
                // Couldn't connect to server (could be timeout, SOP violation, etc.)
                handleError(url, exception);
                controller.handleEvent(LoadingStatusAction.OFF);
            }

            public void onResponseReceived(Request request, Response response) {
                try {
                    if (response.getText().indexOf("HTTP 401") != -1) // HACK
                    {
                        appContext.getAuthentication().handleSessionTimeout();
                    } else if (200 == response.getStatusCode()) {
                        handleSuccessfulResponse(controller, object, response);
                    } else {
                        final String msg = response.getText().equals("") ? "Unknown error" : response.getText();
                        handleError(url, new RequestException("HTTP " + response.getStatusCode() + ": " + msg));
                    }
                } finally {
                    //controller.handleEvent( LoadingStatusAction.OFF );
                    if (getDataDriven(controller) != null) {
                        getDataDriven(controller).setLoading(false);
                    }
                }
            }
        });

        // Timer to handle pending request
        Timer t = new Timer() {

            public void run() {
                if (request.isPending()) {
                    request.cancel();
                    handleError(url, new IOException("Request timeout"));
                }

            }
        };
        t.schedule(20000);

    } catch (RequestException e) {
        // Couldn't connect to server
        handleError(url, e);
        //controller.handleEvent( LoadingStatusAction.OFF );

        if (getDataDriven(controller) != null) {
            getDataDriven(controller).setLoading(false);
        }
    }
}

From source file:org.jboss.bpm.console.client.LoginView.java

License:Open Source License

private void requestSessionID() {
    RequestBuilder rb = new RequestBuilder(RequestBuilder.GET,
            config.getConsoleServerUrl() + "/rs/identity/sid");

    try {/*from w  w  w .j  a  v  a2  s  . c om*/
        rb.sendRequest(null, new RequestCallback() {

            public void onResponseReceived(Request request, Response response) {
                ConsoleLog.debug("SID: " + response.getText());
                ConsoleLog.debug("Cookies: " + Cookies.getCookieNames());
                final String sid = response.getText();

                auth = new Authentication(config, sid, URLBuilder.getInstance().getUserInRoleURL(KNOWN_ROLES));

                auth.setCallback(new Authentication.AuthCallback() {

                    public void onLoginSuccess(Request request, Response response) {
                        // clear the form
                        usernameInput.setText("");
                        passwordInput.setText("");

                        // display main console
                        window.hide();

                        // assemble main layout
                        DeferredCommand.addCommand(new Command() {
                            public void execute() {
                                // move the loading div to foreground
                                DOM.getElementById("splash").getStyle().setProperty("zIndex", "1000");
                                DOM.getElementById("ui_loading").getStyle().setProperty("visibility",
                                        "visible");

                                // launch workspace
                                GWT.runAsync(new RunAsyncCallback() {
                                    public void onFailure(Throwable throwable) {
                                        GWT.log("Code splitting failed", throwable);
                                        MessageBox.error("Code splitting failed", throwable.getMessage());
                                    }

                                    public void onSuccess() {

                                        List<String> roles = auth.getRolesAssigned();
                                        StringBuilder roleString = new StringBuilder();
                                        int index = 1;
                                        for (String s : roles) {
                                            roleString.append(s);
                                            if (index < roles.size())
                                                roleString.append(",");
                                            index++;

                                        }

                                        // populate authentication context
                                        // this will trigger the AuthenticaionModule
                                        // and finally initialize the workspace UI

                                        Registry.get(SecurityService.class).setDeferredNotification(false);

                                        MessageBuilder.createMessage().toSubject("AuthorizationListener")
                                                .signalling().with(SecurityParts.Name, auth.getUsername())
                                                .with(SecurityParts.Roles, roleString.toString())
                                                .noErrorHandling().sendNowWith(ErraiBus.get());

                                        Timer t = new Timer() {

                                            public void run() {
                                                // hide the loading div
                                                DeferredCommand.addCommand(new Command() {
                                                    public void execute() {
                                                        DOM.getElementById("ui_loading").getStyle()
                                                                .setProperty("visibility", "hidden");
                                                        DOM.getElementById("splash").getStyle()
                                                                .setProperty("visibility", "hidden");
                                                    }
                                                });

                                            }
                                        };
                                        t.schedule(2000);

                                    }
                                });

                            }
                        });

                        window = null;
                    }

                    public void onLoginFailed(Request request, Throwable t) {
                        usernameInput.setText("");
                        passwordInput.setText("");
                        messagePanel.setHTML(
                                "<div style='color:#CC0000;'>Authentication failed. Please try again:</div>");
                    }
                });

                Registry.set(Authentication.class, auth);

                createLayoutWindowPanel();
                window.pack();
                window.center();

                // focus
                usernameInput.setFocus(true);

            }

            public void onError(Request request, Throwable t) {
                ConsoleLog.error("Failed to initiate session", t);
            }
        });
    } catch (RequestException e) {
        ConsoleLog.error("Request error", e);
    }
}

From source file:org.jboss.bpm.console.client.LoginView.java

License:Open Source License

/**
 * The j_security_check URL is a kind of temporary resource that only exists
 * if tomcat decided that the login page should be shown.
 *//*from   ww  w .j  av a 2  s . c o  m*/
private void requestProtectedResource() {
    RequestBuilder rb = new RequestBuilder(RequestBuilder.GET,
            config.getConsoleServerUrl() + "/rs/identity/secure/sid");

    try {
        rb.sendRequest(null, new RequestCallback() {

            public void onResponseReceived(Request request, Response response) {
                ConsoleLog.debug("requestProtectedResource() HTTP " + response.getStatusCode());
                auth.login(getUsername(), getPassword());
            }

            public void onError(Request request, Throwable t) {
                ConsoleLog.error("Failed to request protected resource", t);
            }
        });
    } catch (RequestException e) {
        ConsoleLog.error("Request error", e);
    }
}

From source file:org.jboss.bpm.console.client.report.RenderReportAction.java

License:Open Source License

public void execute(final Controller controller, Object object) {
    final RenderDispatchEvent event = (RenderDispatchEvent) object;

    final String url = event.getDispatchUrl();
    RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);

    ConsoleLog.debug(RequestBuilder.POST + ": " + url);
    final ReportLaunchPadView view = (ReportLaunchPadView) controller.getView(ReportLaunchPadView.ID);

    view.reset();/*from w ww .  j  a va  2 s  . c  om*/
    view.setLoading(true);

    try {
        controller.handleEvent(LoadingStatusAction.ON);
        //view.setLoading(true);

        String parameters = event.getParameters();
        final Request request = builder.sendRequest(parameters, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
                // Couldn't connect to server (could be timeout, SOP violation, etc.)
                handleError(controller, url, exception);
                controller.handleEvent(LoadingStatusAction.OFF);
            }

            public void onResponseReceived(Request request, Response response) {
                try {
                    if (response.getText().indexOf("HTTP 401") != -1) // HACK
                    {
                        appContext.getAuthentication().handleSessionTimeout();
                    } else if (200 == response.getStatusCode()) {
                        // update view
                        view.displayReport(event.getTitle(), event.getDispatchUrl());
                    } else {
                        final String msg = response.getText().equals("") ? "Unknown error" : response.getText();
                        handleError(controller, url,
                                new RequestException("HTTP " + response.getStatusCode() + ": " + msg));
                    }
                } finally {
                    controller.handleEvent(LoadingStatusAction.OFF);
                    view.setLoading(false);
                }
            }
        });

        // Timer to handle pending request
        Timer t = new Timer() {

            public void run() {
                if (request.isPending()) {
                    request.cancel();
                    handleError(controller, url, new IOException("Request timeout"));
                }

            }
        };
        t.schedule(20000);

    } catch (Throwable e) {
        // Couldn't connect to server
        controller.handleEvent(LoadingStatusAction.OFF);
        handleError(controller, url, e);
        view.setLoading(false);
    }
}

From source file:org.jboss.errai.bus.client.framework.transports.HttpPollingHandler.java

License:Apache License

/**
 * Sends the given string oon the outbound communication channel (as a POST
 * request to the server)./*w  w  w  . j ava 2 s.  co  m*/
 *
 * @param payload
 *     The message to send. It is sent verbatim.
 * @param callback
 *     The callback to receive success or error notification. Note that
 *     this callback IS NOT CALLED if the request is cancelled.
 * @param extraParameters
 *     Extra paramets to include in the HTTP request (key is parameter name;
 *     value is parameter value).
 *
 * @throws com.google.gwt.http.client.RequestException
 *     if the request cannot be sent at all.
 */
public Request sendPollingRequest(final String payload, final Map<String, String> extraParameters,
        final RequestCallback callback) throws RequestException {

    // LogUtil.log("[bus] sendPollingRequest(" + payload + ")");

    final String serviceEntryPoint;
    final Map<String, String> parmsMap;
    final boolean waitChannel;
    boolean activeWaitChannel = false;

    final Iterator<RxInfo> iterator = pendingRequests.iterator();
    while (iterator.hasNext()) {
        final RxInfo pendingRx = iterator.next();
        if (pendingRx.getRequest().isPending() && pendingRx.isWaiting()) {
            //  LogUtil.log("[bus] ABORT SEND: " + pendingRx + " is waiting" );
            // return null;
            activeWaitChannel = true;
        }

        if (!pendingRx.getRequest().isPending()) {
            iterator.remove();
        }
    }

    if (!activeWaitChannel && receiveCommCallback.canWait() && !rxActive) {
        parmsMap = new HashMap<String, String>(extraParameters);
        parmsMap.put("wait", "1");
        serviceEntryPoint = messageBus.getInServiceEntryPoint();
        waitChannel = true;
    } else {
        parmsMap = extraParameters;
        serviceEntryPoint = messageBus.getOutServiceEntryPoint();
        waitChannel = false;
    }

    rxActive = true;

    final StringBuilder extraParmsString = new StringBuilder();
    for (final Map.Entry<String, String> entry : parmsMap.entrySet()) {
        extraParmsString.append("&").append(URL.encodePathSegment(entry.getKey())).append("=")
                .append(URL.encodePathSegment(entry.getValue()));
    }

    final long latencyTime = System.currentTimeMillis();

    final RequestBuilder builder = new RequestBuilder(RequestBuilder.POST,
            URL.encode(messageBus.getApplicationLocation(serviceEntryPoint)) + "?z=" + getNextRequestNumber()
                    + "&clientId=" + URL.encodePathSegment(messageBus.getClientId())
                    + extraParmsString.toString());
    builder.setHeader("Content-Type", "application/json; charset=utf-8");

    final RxInfo rxInfo = new RxInfo(System.currentTimeMillis(), waitChannel);

    try {
        // LogUtil.log("[bus] TX: " + payload);
        final Request request = builder.sendRequest(payload, new RequestCallback() {
            @Override
            public void onResponseReceived(final Request request, final Response response) {
                if (!waitChannel) {
                    measuredLatency = (int) (System.currentTimeMillis() - latencyTime);
                }

                pendingRequests.remove(rxInfo);
                callback.onResponseReceived(request, response);
                rxNumber++;
                rxActive = false;
            }

            @Override
            public void onError(final Request request, final Throwable exception) {
                pendingRequests.remove(rxInfo);
                callback.onError(request, exception);
                rxActive = false;
            }
        });

        rxInfo.setRequest(request);
        pendingRequests.add(rxInfo);

        return request;
    } catch (RequestException e) {
        throw e;
    }
}

From source file:org.jboss.errai.enterprise.client.jaxrs.AbstractJaxrsProxy.java

License:Apache License

@SuppressWarnings({ "rawtypes", "unchecked" })
protected void sendRequest(final RequestBuilder requestBuilder, final String body,
        final ResponseDemarshallingCallback demarshallingCallback) {

    final RemoteCallback remoteCallback = getRemoteCallback();
    try {/*from w  w w .  j a va2s.  c  o  m*/
        requestBuilder.sendRequest(body, new RequestCallback() {
            @Override
            public void onError(Request request, Throwable throwable) {
                handleError(throwable, request, null);
            }

            @Override
            public void onResponseReceived(Request request, Response response) {
                int statusCode = response.getStatusCode();
                if ((successCodes == null || successCodes.contains(statusCode))
                        && (statusCode >= 200 && statusCode < 300)) {

                    if (remoteCallback instanceof ResponseCallback) {
                        ((ResponseCallback) getRemoteCallback()).callback(response);
                    } else if (response.getStatusCode() == 204) {
                        remoteCallback.callback(null);
                    } else {
                        remoteCallback.callback(demarshallingCallback.demarshallResponse(response.getText()));
                    }
                } else {
                    ResponseException throwable = new ResponseException(response.getStatusText(), response);
                    handleError(throwable, request, response);
                }
            }
        });
    } catch (RequestException throwable) {
        handleError(throwable, null, null);
    }
}