Example usage for com.google.gwt.http.client Response SC_UNAUTHORIZED

List of usage examples for com.google.gwt.http.client Response SC_UNAUTHORIZED

Introduction

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

Prototype

int SC_UNAUTHORIZED

To view the source code for com.google.gwt.http.client Response SC_UNAUTHORIZED.

Click Source Link

Usage

From source file:com.agnie.gwt.common.client.rpc.LoaderRequestTransport.java

License:Open Source License

protected RequestCallback createRequestCallback(final TransportReceiver receiver) {
    final RequestCallback callback = super.createRequestCallback(receiver);
    RequestCallback newCallback = new RequestCallback() {

        @Override/*from ww w.j a  v a  2  s .c o  m*/
        public void onResponseReceived(Request request, Response response) {
            if (Response.SC_UNAUTHORIZED == response.getStatusCode()) {
                GWT.log("User session timed out or user logged out");
                Window.Location.assign(urlGenerator.getClientSideLoginURL(urlInfo, appDomain,
                        urlInfo.getParameter(QueryString.GWT_DEV_MODE.getKey())));
            } else {
                callback.onResponseReceived(request, response);
            }
        }

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

        }
    };
    return newCallback;
}

From source file:com.google.appinventor.client.Ode.java

License:Open Source License

/**
 * Main entry point for Ode. Setting up the UI and the web service
 * connections.//w  w  w. j  a v  a2s.c  o m
 */
@Override
public void onModuleLoad() {
    Tracking.trackPageview();

    // Handler for any otherwise unhandled exceptions
    GWT.setUncaughtExceptionHandler(new GWT.UncaughtExceptionHandler() {
        @Override
        public void onUncaughtException(Throwable e) {
            OdeLog.xlog(e);

            if (AppInventorFeatures.sendBugReports()) {
                if (Window.confirm(MESSAGES.internalErrorReportBug())) {
                    Window.open(BugReport.getBugReportLink(e), "_blank", "");
                }
            } else {
                // Display a confirm dialog with error msg and if 'ok' open the debugging view
                if (Window.confirm(MESSAGES.internalErrorClickOkDebuggingView())) {
                    Ode.getInstance().switchToDebuggingView();
                }
            }
        }
    });

    // Define bridge methods to Javascript
    JsonpConnection.defineBridgeMethod();

    // Initialize global Ode instance
    instance = this;

    // Let's see if we were started with a repo= parameter which points to a template
    templatePath = Window.Location.getParameter("repo");
    if (templatePath != null) {
        OdeLog.wlog("Got a template path of " + templatePath);
        templateLoadingFlag = true;
    }

    // Let's see if we were started with a galleryId= parameter which points to a template
    galleryId = Window.Location.getParameter("galleryId");
    if (galleryId != null) {
        OdeLog.wlog("Got a galleryId of " + galleryId);
        galleryIdLoadingFlag = true;
    }

    // Get user information.
    OdeAsyncCallback<Config> callback = new OdeAsyncCallback<Config>(
            // failure message
            MESSAGES.serverUnavailable()) {

        @Override
        public void onSuccess(Config result) {
            config = result;
            user = result.getUser();
            isReadOnly = user.isReadOnly();

            // If user hasn't accepted terms of service, ask them to.
            if (!user.getUserTosAccepted() && !isReadOnly) {
                // We expect that the redirect to the TOS page should be handled
                // by the onFailure method below. The server should return a
                // "forbidden" error if the TOS wasn't accepted.
                ErrorReporter.reportError(MESSAGES.serverUnavailable());
                return;
            }

            splashConfig = result.getSplashConfig();

            if (result.getRendezvousServer() != null) {
                setRendezvousServer(result.getRendezvousServer());
            } else {
                setRendezvousServer(YaVersion.RENDEZVOUS_SERVER);
            }

            userSettings = new UserSettings(user);

            // Gallery settings
            gallerySettings = new GallerySettings();
            //gallerySettings.loadGallerySettings();
            loadGallerySettings();

            // Initialize project and editor managers
            // The project manager loads the user's projects asynchronously
            projectManager = new ProjectManager();
            projectManager.addProjectManagerEventListener(new ProjectManagerEventAdapter() {
                @Override
                public void onProjectsLoaded() {
                    projectManager.removeProjectManagerEventListener(this);

                    // This handles any built-in templates stored in /war
                    // Retrieve template data stored in war/templates folder and
                    // and save it for later use in TemplateUploadWizard
                    OdeAsyncCallback<String> templateCallback = new OdeAsyncCallback<String>(
                            // failure message
                            MESSAGES.createProjectError()) {
                        @Override
                        public void onSuccess(String json) {
                            // Save the templateData
                            TemplateUploadWizard.initializeBuiltInTemplates(json);
                            // Here we call userSettings.loadSettings, but the settings are actually loaded
                            // asynchronously, so this loadSettings call will return before they are loaded.
                            // After the user settings have been loaded, openPreviousProject will be called.
                            // We have to call this after the builtin templates have been loaded otherwise
                            // we will get a NPF.
                            userSettings.loadSettings();
                        }
                    };
                    Ode.getInstance().getProjectService().retrieveTemplateData(
                            TemplateUploadWizard.TEMPLATES_ROOT_DIRECTORY, templateCallback);
                }
            });
            editorManager = new EditorManager();

            // Initialize UI
            initializeUi();

            topPanel.showUserEmail(user.getUserEmail());
        }

        @Override
        public void onFailure(Throwable caught) {
            if (caught instanceof StatusCodeException) {
                StatusCodeException e = (StatusCodeException) caught;
                int statusCode = e.getStatusCode();
                switch (statusCode) {
                case Response.SC_UNAUTHORIZED:
                    // unauthorized => not on whitelist
                    // getEncodedResponse() gives us the message that we wrote in
                    // OdeAuthFilter.writeWhitelistErrorMessage().
                    Window.alert(e.getEncodedResponse());
                    return;
                case Response.SC_FORBIDDEN:
                    // forbidden => need tos accept
                    Window.open("/" + ServerLayout.YA_TOS_FORM, "_self", null);
                    return;
                case Response.SC_PRECONDITION_FAILED:
                    String locale = Window.Location.getParameter("locale");
                    if (locale == null || locale.equals("")) {
                        Window.Location.replace("/login/");
                    } else {
                        Window.Location.replace("/login/?locale=" + locale);
                    }
                    return; // likely not reached
                }
            }
            super.onFailure(caught);
        }
    };

    // The call below begins an asynchronous read of the user's settings
    // When the settings are finished reading, various settings parsers
    // will be called on the returned JSON object. They will call various
    // other functions in this module, including openPreviousProject (the
    // previous project ID is stored in the settings) as well as the splash
    // screen displaying functions below.
    //
    // TODO(user): ODE makes too many RPC requests at startup time. Currently
    // we do 3 RPCs + 1 per project + 1 per open file. We should bundle some of
    // those with each other or with the initial HTML transfer.
    //
    // This call also stores our sessionId in the backend. This will be checked
    // when we go to save a file and if different file saving will be disabled
    // Newer sessions invalidate older sessions.

    userInfoService.getSystemConfig(sessionId, callback);

    History.addValueChangeHandler(new ValueChangeHandler<String>() {
        @Override
        public void onValueChange(ValueChangeEvent<String> event) {
            openProject(event.getValue());
        }
    });

    // load project based on current url
    // TODO(sharon): Seems like a possible race condition here if the onValueChange
    // handler defined above gets called before the getSystemConfig call sets
    // userSettings.
    // The following line causes problems with GWT debugging, and commenting
    // it out doesn't seem to break things.
    //History.fireCurrentHistoryState();
}

From source file:com.google.collide.client.communication.FrontendRestApi.java

License:Open Source License

private static FailureReason getFailureReason(Response response, ServerError responseData) {
    switch (response.getStatusCode()) {
    case Response.SC_OK:
        return null;
    case Response.SC_UNAUTHORIZED:
        if (responseData != null) {
            return responseData.getFailureReason();
        }//w  w  w. ja v  a 2s . c  om
        return FailureReason.UNAUTHORIZED;
    // TODO: Make this a server dto error.
    case Response.SC_CONFLICT:
        return FailureReason.STALE_CLIENT;
    case Response.SC_NOT_FOUND:
        if (responseData != null) {
            return responseData.getFailureReason();
        }
        return FailureReason.UNKNOWN;
    case Response.SC_NOT_IMPLEMENTED:
        if (responseData != null) {
            return responseData.getFailureReason();
        }
        return FailureReason.UNKNOWN;
    default:
        return FailureReason.SERVER_ERROR;
    }
}

From source file:com.google.gerrit.client.rpc.RestApi.java

License:Apache License

/** True if err is describing a user that is currently anonymous. */
public static boolean isNotSignedIn(Throwable err) {
    if (err instanceof StatusCodeException) {
        StatusCodeException sce = (StatusCodeException) err;
        if (sce.getStatusCode() == Response.SC_UNAUTHORIZED) {
            return true;
        }/* ww  w.  j a  v  a 2s  .  c  om*/
        return sce.getStatusCode() == Response.SC_FORBIDDEN
                && (sce.getEncodedResponse().equals("Authentication required")
                        || sce.getEncodedResponse().startsWith("Must be signed-in"));
    }
    return false;
}

From source file:com.google.gwt.sample.authrequest.client.SampleAuthRequestTransport.java

License:Apache License

@Override
protected RequestCallback createRequestCallback(final TransportReceiver receiver) {
    final RequestCallback superCallback = super.createRequestCallback(receiver);

    return new RequestCallback() {
        @Override/*from   w w  w . j a  v  a2s.co  m*/
        public void onError(Request request, Throwable exception) {
            superCallback.onError(request, exception);
        }

        @Override
        public void onResponseReceived(Request request, Response response) {
            /*
             * The GaeAuthFailure filter responds with Response.SC_UNAUTHORIZED and
             * adds a "login" url header if the user is not logged in. When we
             * receive that combo, post an event so that the app can handle things
             * as it sees fit.
             */
            if (Response.SC_UNAUTHORIZED == response.getStatusCode()) {
                String loginUrl = response.getHeader("login");
                if (loginUrl != null) {
                    /*
                     * Hand the receiver a non-fatal callback, so that
                     * com.google.web.bindery.requestfactory.shared.Receiver will not
                     * post a runtime exception.
                     */
                    receiver.onTransportFailure(new ServerFailure("Unauthenticated user", null, null, false));
                    eventBus.fireEvent(new SampleAuthenticationFailureEvent(loginUrl));
                    return;
                }
            }
            superCallback.onResponseReceived(request, response);
        }
    };
}

From source file:com.google.gwt.sample.gaerequest.client.GaeAuthRequestTransport.java

License:Apache License

@Override
protected RequestCallback createRequestCallback(final TransportReceiver receiver) {
    final RequestCallback superCallback = super.createRequestCallback(receiver);

    return new RequestCallback() {
        @Override/*  w ww  . j a v  a  2  s  .co  m*/
        public void onError(Request request, Throwable exception) {
            superCallback.onError(request, exception);
        }

        @Override
        public void onResponseReceived(Request request, Response response) {
            /*
             * The GaeAuthFailure filter responds with Response.SC_UNAUTHORIZED and
             * adds a "login" url header if the user is not logged in. When we
             * receive that combo, post an event so that the app can handle things
             * as it sees fit.
             */
            if (Response.SC_UNAUTHORIZED == response.getStatusCode()) {
                String loginUrl = response.getHeader("login");
                if (loginUrl != null) {
                    /*
                     * Hand the receiver a non-fatal callback, so that
                     * com.google.web.bindery.requestfactory.shared.Receiver will not
                     * post a runtime exception.
                     */
                    receiver.onTransportFailure(new ServerFailure("Unauthenticated user", null, null, false));
                    eventBus.fireEvent(new GaeAuthenticationFailureEvent(loginUrl));
                    return;
                }
            }
            superCallback.onResponseReceived(request, response);
        }
    };
}

From source file:org.bonitasoft.console.client.user.process.action.ProcessInstantiationCallbackBehavior.java

License:Open Source License

public void onError(final String responseContent, final int errorCode) {
    if (errorCode == Response.SC_BAD_REQUEST) {
        GWT.log("Error while instantiating process : " + responseContent);
        final String errorMessage = _(
                "Error while trying to start the case. Some required information is missing (contract not fulfilled).");
        ViewController.closePopup();/*w w  w  . j  a  va  2  s  .  co  m*/
        showError(errorMessage);
    } else if (errorCode == Response.SC_UNAUTHORIZED) {
        Window.Location.reload();
    } else {
        showError(_("Error while trying to start the case."));
    }
}

From source file:org.fusesource.restygwt.client.callback.FilterawareRetryingCallback.java

License:Apache License

@Override
public final void onResponseReceived(Request request, Response response) {
    if (response.getStatusCode() == Response.SC_UNAUTHORIZED) {
        if (LogConfiguration.loggingIsEnabled()) {
            Logger.getLogger(FilterawareRetryingCallback.class.getName())
                    .severe("Unauthorized: " + method.builder.getUrl());
            // HACK TODO handle this via a callbackfilter
            Window.Location.assign("login.html" + Window.Location.getQueryString());
        }/*from   ww w  .  jav a  2  s. com*/
    } else if (!(response.getStatusCode() < 300 && response.getStatusCode() >= 200)) {
        /*
         * retry only on GET requests that are no redirects (301, 302)
         */
        if (response.getStatusCode() != 301 && response.getStatusCode() != 302
                && response.getStatusCode() != 404
                && method.builder.getHTTPMethod().equals(RequestBuilder.GET.toString())) {
            handleErrorGracefully(request, response, requestCallback);
        } else {
            if (LogConfiguration.loggingIsEnabled()) {
                Logger.getLogger(FilterawareRetryingCallback.class.getName())
                        .severe("ERROR with non-GET method: " + method.builder.getHTTPMethod() + " "
                                + method.builder.getUrl() + ", " + response.getStatusText());
            }

            /*
             *  RuntimeException token from
             *  com.google.gwt.http.client.Request#fireOnResponseReceived()
             */
            requestCallback.onError(request, new RuntimeException("Response " + response.getStatusCode()
                    + " for " + method.builder.getHTTPMethod() + " " + method.builder.getUrl()));
        }
        return;
    } else {
        // filter only in success case for now
        for (CallbackFilter f : callbackFilters) {
            requestCallback = f.filter(method, response, requestCallback);
        }
        requestCallback.onResponseReceived(request, response);
    }
}

From source file:org.fusesource.restygwt.client.callback.UnauthorizedCallbackFilter.java

License:Apache License

@Override
public boolean canHandle(final String method, final int code) {
    return code == Response.SC_UNAUTHORIZED;
}

From source file:org.fusesource.restygwt.client.dispatcher.CachingRetryingCallback.java

License:Apache License

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

    if (response.getStatusCode() == Response.SC_UNAUTHORIZED) {
        //FIXME: to be removed...
        Window.Location.replace("login.html");

    } else if (response.getStatusCode() != Response.SC_OK) {

        handleErrorGracefully();//from ww w .  java 2  s.c o m

    } else {

        CacheKey cacheKey = new CacheKey(requestBuilder);
        CachingRetryingDispatcher.getCacheStorage().putResult(cacheKey, response);

        requestCallback.onResponseReceived(request, response);
    }
}