Example usage for org.apache.commons.httpclient HttpStatus SC_UNAUTHORIZED

List of usage examples for org.apache.commons.httpclient HttpStatus SC_UNAUTHORIZED

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_UNAUTHORIZED.

Prototype

int SC_UNAUTHORIZED

To view the source code for org.apache.commons.httpclient HttpStatus SC_UNAUTHORIZED.

Click Source Link

Document

<tt>401 Unauthorized</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:org.collectionspace.chain.csp.webui.userdetails.UserDetailsCreateUpdate.java

private void store_set(Storage storage, UIRequest request, String path) throws UIException {
    JSONObject data = null;//from w  w  w .  ja  v a  2  s.c  om
    data = request.getJSONBody();

    boolean notfailed = true;
    String msg = "";
    try {
        boolean currentUserPasswordChange = false;
        String newPassword = null;
        boolean absorbedSvcsError = false;
        if (create) {
            path = sendJSON(storage, null, data);
            // assign to default role.
        } else {
            // Check for password update. If doing that, absorb 403 errors and redirect
            // as though we are doing a logout.
            JSONObject fields = data.optJSONObject("fields");
            if (fields != null && fields.has(PASSWORD_FIELD)) {
                String passwd = fields.getString(PASSWORD_FIELD);
                if (passwd != null) {
                    if (passwd.isEmpty()) {
                        fields.remove(PASSWORD_FIELD); // Preclude removl of a password
                    } else {
                        String editedUserId = fields.getString(USER_ID_FIELD);
                        UISession session = request.getSession();
                        if (session != null) {
                            Object currentUserId = session.getValue(UISession.USERID);
                            if (currentUserId != null && currentUserId.equals(editedUserId)) {
                                newPassword = passwd;
                                currentUserPasswordChange = true;
                            }
                        }
                    }
                }
            }
            path = sendJSON(storage, path, data);
            // If that succeeded, and if we updated the current password, set session
            // credentials
            if (currentUserPasswordChange) {
                request.getSession().setValue(UISession.PASSWORD, newPassword);
            }
        }
        if (path == null) {
            throw new UIException("Insufficient data for create (no fields?)");
        }
        data.put("csid", path);
        try {
            assignRole(storage, path, data);
        } catch (UnderlyingStorageException usex) {
            Integer status = usex.getStatus();
            if (status != null && (status == HttpStatus.SC_FORBIDDEN || status == HttpStatus.SC_UNAUTHORIZED)) {
                absorbedSvcsError = true;
                msg = "Cannot update roles for this account.";
                log.warn("UserDetailsCreateUpdate changing roles, and absorbing error returned: "
                        + usex.getStatus());
            } else {
                throw usex; // Propagate
            }
        }
        boolean isError = !notfailed;
        data.put("isError", isError);
        JSONObject messages = new JSONObject();
        messages.put("message", msg);
        messages.put("severity", "info");
        JSONArray arr = new JSONArray();
        arr.put(messages);
        data.put("messages", arr);
        // Elide the value of the password field before returning a response
        data.optJSONObject("fields").remove(PASSWORD_FIELD);
        request.sendJSONResponse(data);
        request.setOperationPerformed(create ? Operation.CREATE : Operation.UPDATE);
        if (create && notfailed)
            request.setSecondaryRedirectPath(new String[] { url_base, path });
    } catch (JSONException x) {
        throw new UIException("Failed to parse json: ", x);
    } catch (ExistException x) {
        throw new UIException("Existence exception: ", x);
    } catch (UnimplementedException x) {
        throw new UIException("Unimplemented exception: ", x);
    } catch (UnderlyingStorageException x) {
        UIException uiexception = new UIException(x.getMessage(), x.getStatus(), x.getUrl(), x);
        request.sendJSONResponse(uiexception.getJSON());
    }

}

From source file:org.collectionspace.services.client.test.ServiceLayerTest.java

public void serviceSecure() {
    if (logger.isDebugEnabled()) {
        logger.debug(BaseServiceTest.testBanner("serviceSecure", CLASS_NAME));
    }/*  ww  w. ja va2s .c o m*/
    String url = serviceClient.getBaseURL() + "collectionobjects";
    GetMethod method = new GetMethod(url);
    // This vanilla HTTP client does not contain credentials or any other
    // properties of the serviceClient.
    HttpClient noCredentialsHttpClient = new HttpClient();
    try {
        int statusCode = noCredentialsHttpClient.executeMethod(method);
        if (logger.isDebugEnabled()) {
            logger.debug("serviceSecure url=" + url + " status=" + statusCode);
        }
        //due to anonymous support, the service returns 200 instead of 401
        //            Assert.assertEquals(statusCode, HttpStatus.SC_UNAUTHORIZED,
        //                    "expected " + HttpStatus.SC_UNAUTHORIZED);
        Assert.assertEquals(statusCode, HttpStatus.SC_UNAUTHORIZED, "expected " + HttpStatus.SC_UNAUTHORIZED);
    } catch (HttpException e) {
        logger.error("Fatal protocol violation: ", e);
    } catch (IOException e) {
        logger.error("Fatal transport error", e);
    } catch (Exception e) {
        logger.error("unknown exception ", e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:org.devproof.portal.module.bookmark.panel.DeliciousSyncPanel.java

private ProgressBar createProgressBar() {
    ProgressionModel progressionModel = createProgressionModel();
    progressBar = new ProgressBar("bar", progressionModel) {
        private static final long serialVersionUID = 1L;

        @Override//  www  . j  av a  2  s .  co m
        protected void onFinished(AjaxRequestTarget target) {
            if (deliciousBean != null && deliciousBean.hasError()) {
                if (deliciousBean.getHttpCode() == HttpStatus.SC_UNAUTHORIZED) {
                    error(getString("loginFailed"));
                } else if (deliciousBean.getHttpCode() == HttpStatus.SC_SERVICE_UNAVAILABLE) {
                    error(getString("serviceNotAvailable"));
                } else {
                    error(deliciousBean.getErrorMessage());
                }
            } else {
                info(new StringResourceModel("syncFinished", this, null,
                        new Object[] { newBookmarksCount, modifiedBookmarksCount, deletedBookmarksCount })
                                .getString());
            }
            target.addComponent(feedbackPanel);
        }
    };
    return progressBar;
}

From source file:org.eclipse.andmore.android.common.utilities.HttpUtils.java

private InputStream getInputStreamForUrl(String url, IProgressMonitor monitor, boolean returnStream)
        throws IOException {
    SubMonitor subMonitor = SubMonitor.convert(monitor);

    subMonitor.beginTask(UtilitiesNLS.HttpUtils_MonitorTask_PreparingConnection, 300);

    AndmoreLogger.debug(HttpUtils.class, "Verifying proxy usage for opening http connection"); //$NON-NLS-1$

    // Try to retrieve proxy configuration to use if necessary
    IProxyService proxyService = ProxyManager.getProxyManager();
    IProxyData proxyData = null;/*from   w w w  .  j  ava  2  s. com*/
    if (proxyService.isProxiesEnabled() || proxyService.isSystemProxiesEnabled()) {
        Authenticator.setDefault(new NetAuthenticator());
        if (url.startsWith("https")) {
            proxyData = proxyService.getProxyData(IProxyData.HTTPS_PROXY_TYPE);
            AndmoreLogger.debug(HttpUtils.class, "Using https proxy"); //$NON-NLS-1$
        } else if (url.startsWith("http")) {
            proxyData = proxyService.getProxyData(IProxyData.HTTP_PROXY_TYPE);
            AndmoreLogger.debug(HttpUtils.class, "Using http proxy"); //$NON-NLS-1$
        } else {
            AndmoreLogger.debug(HttpUtils.class, "Not using any proxy"); //$NON-NLS-1$
        }
    }

    // Creates the http client and the method to be executed
    HttpClient client = null;
    client = new HttpClient();

    // If there is proxy data, work with it
    if (proxyData != null) {
        if (proxyData.getHost() != null) {
            // Sets proxy host and port, if any
            client.getHostConfiguration().setProxy(proxyData.getHost(), proxyData.getPort());
        }

        if ((proxyData.getUserId() != null) && (proxyData.getUserId().trim().length() > 0)) {
            // Sets proxy user and password, if any
            Credentials cred = new UsernamePasswordCredentials(proxyData.getUserId(),
                    proxyData.getPassword() == null ? "" : proxyData.getPassword()); //$NON-NLS-1$
            client.getState().setProxyCredentials(AuthScope.ANY, cred);
        }
    }

    InputStream streamForUrl = null;
    getMethod = new GetMethod(url);
    getMethod.setFollowRedirects(true);

    // set a 30 seconds timeout
    HttpMethodParams params = getMethod.getParams();
    params.setSoTimeout(15 * ONE_SECOND);
    getMethod.setParams(params);

    boolean trying = true;
    Credentials credentials = null;
    subMonitor.worked(100);
    subMonitor.setTaskName(UtilitiesNLS.HttpUtils_MonitorTask_ContactingSite);
    do {
        AndmoreLogger.info(HttpUtils.class, "Attempting to make a connection"); //$NON-NLS-1$

        // retry to connect to the site once, also set the timeout for 5
        // seconds
        HttpClientParams clientParams = client.getParams();
        clientParams.setIntParameter(HttpClientParams.MAX_REDIRECTS, 1);
        clientParams.setSoTimeout(5 * ONE_SECOND);
        client.setParams(clientParams);

        client.executeMethod(getMethod);
        if (subMonitor.isCanceled()) {
            break;
        } else {
            AuthState authorizationState = getMethod.getHostAuthState();
            String authenticationRealm = authorizationState.getRealm();

            if (getMethod.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
                AndmoreLogger.debug(HttpUtils.class, "Client requested authentication; retrieving credentials"); //$NON-NLS-1$

                credentials = authenticationRealmCache.get(authenticationRealm);

                if (credentials == null) {
                    AndmoreLogger.debug(HttpUtils.class,
                            "Credentials not found; prompting user for login/password"); //$NON-NLS-1$

                    subMonitor.setTaskName(UtilitiesNLS.HttpUtils_MonitorTask_WaitingAuthentication);

                    LoginPasswordDialogCreator dialogCreator = new LoginPasswordDialogCreator(url);
                    if (dialogCreator.openLoginPasswordDialog() == LoginPasswordDialogCreator.OK) {

                        credentials = new UsernamePasswordCredentials(dialogCreator.getTypedLogin(),
                                dialogCreator.getTypedPassword());
                    } else {
                        // cancel pressed; stop trying
                        trying = false;

                        // set the monitor canceled to be able to stop
                        // process
                        subMonitor.setCanceled(true);
                    }

                }

                if (credentials != null) {
                    AuthScope scope = new AuthScope(null, -1, authenticationRealm);
                    client.getState().setCredentials(scope, credentials);
                }

                subMonitor.worked(100);
            } else if (getMethod.getStatusCode() == HttpStatus.SC_OK) {
                AndmoreLogger.debug(HttpUtils.class, "Http connection suceeded"); //$NON-NLS-1$

                subMonitor.setTaskName(UtilitiesNLS.HttpUtils_MonitorTask_RetrievingSiteContent);
                if ((authenticationRealm != null) && (credentials != null)) {
                    authenticationRealmCache.put(authenticationRealm, credentials);
                } else {
                    // no authentication was necessary, just work the
                    // monitor
                    subMonitor.worked(100);
                }

                AndmoreLogger.info(HttpUtils.class, "Retrieving site content"); //$NON-NLS-1$

                // if the stream should not be returned (ex: only testing
                // the connection is
                // possible), then null will be returned
                if (returnStream) {
                    streamForUrl = getMethod.getResponseBodyAsStream();
                }

                // succeeded; stop trying
                trying = false;

                subMonitor.worked(100);
            } else {
                // unhandled return status code
                trying = false;

                subMonitor.worked(200);
            }
        }
    } while (trying);

    subMonitor.done();

    return streamForUrl;
}

From source file:org.eclipse.lyo.testsuite.oslcv2.cm.ChangeRequestJsonTests.java

public ChangeRequestJsonTests(String thisUrl) throws IOException, ParserConfigurationException, SAXException,
        XPathExpressionException, NullPointerException, JSONException {
    super(thisUrl);

    // If currentUrl is null, it means that the query didn't match any
    // records. This isn't exactly a failure, but there's nothing more we
    // can test./*w w w .jav a 2  s. c  o  m*/
    assumeNotNull(currentUrl);
    response = OSLCUtils.getResponseFromUrl(setupBaseUrl, currentUrl, basicCreds, OSLCConstants.CT_JSON,
            headers);
    responseBody = EntityUtils.toString(response.getEntity());
    int sc = response.getStatusLine().getStatusCode();

    // Some records in the system might not be accessible to this user. This
    // isn't a failure, but there's nothing more we can test.
    assumeTrue(sc != HttpStatus.SC_FORBIDDEN && sc != HttpStatus.SC_UNAUTHORIZED);

    // Make sure the request succeeded before continuing.
    assertEquals(HttpStatus.SC_OK, sc);

    //Get JSON doc from response
    JSONArtifact userData = JSON.parse(responseBody);

    if (userData instanceof JSONArtifact) {
        doc = (JSONObject) userData;
    }

}

From source file:org.eclipse.lyo.testsuite.oslcv2.cm.ChangeRequestRdfXmlTests.java

public ChangeRequestRdfXmlTests(String url)
        throws IOException, ParserConfigurationException, SAXException, XPathExpressionException {
    super(url);/* w ww.j  av  a  2  s  .c o  m*/
    // If currentUrl is null, it means that the query didn't match any
    // records. This isn't exactly a failure, but there's nothing more we
    // can test.
    assumeNotNull(currentUrl);
    response = OSLCUtils.getResponseFromUrl(setupBaseUrl, currentUrl, basicCreds, OSLCConstants.CT_RDF,
            headers);
    // Some records in the system might not be accessible to this user. This
    // isn't a failure, but there's nothing more we can test.
    int sc = response.getStatusLine().getStatusCode();
    assumeTrue(sc != HttpStatus.SC_FORBIDDEN && sc != HttpStatus.SC_UNAUTHORIZED);
    // Make sure the request succeeded before continuing.
    assertEquals(HttpStatus.SC_OK, sc);

    fRdfModel.read(response.getEntity().getContent(),
            OSLCUtils.absoluteUrlFromRelative(setupBaseUrl, currentUrl), OSLCConstants.JENA_RDF_XML);
    RDFUtils.validateModel(fRdfModel);

    fResource = (Resource) fRdfModel.getResource(currentUrl);
    assumeTrue(fRdfModel.contains(fResource, RDF.type,
            fRdfModel.createResource(OSLCConstants.CM_CHANGE_REQUEST_TYPE)));
}

From source file:org.eclipse.lyo.testsuite.oslcv2.cm.ChangeRequestXmlTests.java

public ChangeRequestXmlTests(String thisUrl)
        throws IOException, ParserConfigurationException, SAXException, XPathExpressionException {
    super(thisUrl);

    // If currentUrl is null, it means that the query didn't match any
    // records. This isn't exactly a failure, but there's nothing more we
    // can test./*from w ww  . j  a  v  a  2 s  .co m*/
    assumeNotNull(currentUrl);
    response = OSLCUtils.getResponseFromUrl(setupBaseUrl, currentUrl, basicCreds, OSLCConstants.CT_XML,
            headers);
    responseBody = EntityUtils.toString(response.getEntity());
    int sc = response.getStatusLine().getStatusCode();

    // Some records in the system might not be accessible to this user. This
    // isn't a failure, but there's nothing more we can test.
    assumeTrue(sc != HttpStatus.SC_FORBIDDEN && sc != HttpStatus.SC_UNAUTHORIZED);

    // Make sure the request succeeded before continuing.
    assertEquals(HttpStatus.SC_OK, sc);

    //Get XML Doc from response
    doc = OSLCUtils.createXMLDocFromResponseBody(responseBody);
}

From source file:org.eclipse.lyo.testsuite.oslcv2.CoreResourceJsonTests.java

public CoreResourceJsonTests(String thisUrl) throws IOException, ParserConfigurationException, SAXException,
        XPathExpressionException, NullPointerException, JSONException {
    super(thisUrl);

    // If currentUrl is null, it means that the query didn't match any
    // records. This isn't exactly a failure, but there's nothing more we
    // can test./*from   ww  w .j a va 2s  . c o  m*/
    assumeNotNull(currentUrl);
    response = OSLCUtils.getResponseFromUrl(setupBaseUrl, currentUrl, creds, OSLCConstants.CT_JSON, headers);
    responseBody = EntityUtils.toString(response.getEntity());
    int sc = response.getStatusLine().getStatusCode();

    // Some records in the system might not be accessible to this user. This
    // isn't a failure, but there's nothing more we can test.
    assumeTrue(sc != HttpStatus.SC_FORBIDDEN && sc != HttpStatus.SC_UNAUTHORIZED);

    // Make sure the request succeeded before continuing.
    assertEquals(HttpStatus.SC_OK, sc);

    //Get JSON doc from response
    JSONArtifact userData = JSON.parse(responseBody);

    if (userData instanceof JSONArtifact) {
        doc = (JSONObject) userData;
    }
}

From source file:org.eclipse.lyo.testsuite.oslcv2.CoreResourceRdfXmlTests.java

public CoreResourceRdfXmlTests(String thisUrl) throws IOException, ParserConfigurationException, SAXException,
        XPathExpressionException, NullPointerException {

    super(thisUrl);

    // If currentUrl is null, it means that the query didn't match any
    // records. This isn't exactly a failure, but there's nothing more we
    // can test.//from   w  ww . j  av a 2s.c om
    assumeNotNull(currentUrl);
    response = OSLCUtils.getResponseFromUrl(setupBaseUrl, currentUrl, creds, OSLCConstants.CT_RDF, headers);
    // Some records in the system might not be accessible to this user. This
    // isn't a failure, but there's nothing more we can test.
    int sc = response.getStatusLine().getStatusCode();
    assumeTrue(sc != HttpStatus.SC_FORBIDDEN && sc != HttpStatus.SC_UNAUTHORIZED);
    // Make sure the request succeeded before continuing.
    assertEquals(HttpStatus.SC_OK, sc);

    fRdfModel.read(response.getEntity().getContent(),
            OSLCUtils.absoluteUrlFromRelative(setupBaseUrl, currentUrl), OSLCConstants.JENA_RDF_XML);
    RDFUtils.validateModel(fRdfModel);

    fResource = (Resource) fRdfModel.getResource(currentUrl);
    if (logger.isDebugEnabled()) {
        StringWriter w = new StringWriter();
        fRdfModel.write(w, "TURTLE");
        logger.debug(String.format("Testing Resource <%s> with type <%s>", currentUrl, getResourceType()));
        logger.debug(w.toString());
    }

    String resourceType = getResourceType();
    if (resourceType != null && !"".equals(resourceType)) {
        assumeTrue(fRdfModel.contains(fResource, RDF.type, fRdfModel.createResource(getResourceType())));
    }

}

From source file:org.eclipse.lyo.testsuite.oslcv2.CoreResourceXmlTests.java

public CoreResourceXmlTests(String thisUrl)
        throws IOException, ParserConfigurationException, SAXException, XPathExpressionException {
    super(thisUrl);

    // If currentUrl is null, it means that the query didn't match any
    // records. This isn't exactly a failure, but there's nothing more we
    // can test.//from   ww w  .  jav  a  2  s  .  com
    assumeNotNull(currentUrl);
    response = OSLCUtils.getResponseFromUrl(setupBaseUrl, currentUrl, creds, OSLCConstants.CT_XML, headers);
    responseBody = EntityUtils.toString(response.getEntity());
    int sc = response.getStatusLine().getStatusCode();

    // Some records in the system might not be accessible to this user. This
    // isn't a failure, but there's nothing more we can test.
    assumeTrue(sc != HttpStatus.SC_FORBIDDEN && sc != HttpStatus.SC_UNAUTHORIZED);

    // Make sure the request succeeded before continuing.
    assertEquals(HttpStatus.SC_OK, sc);

    //Get XML Doc from response
    doc = OSLCUtils.createXMLDocFromResponseBody(responseBody);
}