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.mule.module.spring.security.AuthenticationAgainstMultipleProvidersTestCase.java

License:asdf

@Test
public void testMultipleProviders() throws Exception {
    HttpClient httpClient = new HttpClient();
    Credentials credentials = new UsernamePasswordCredentials("admin1", "admin1");
    httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    httpClient.getParams().setAuthenticationPreemptive(true);

    PostMethod postMethod = new PostMethod("http://localhost:4447");
    postMethod.setDoAuthentication(true);
    postMethod.setRequestEntity(new StringRequestEntity("hello", "text/html", "UTF-8"));

    assertEquals(HttpStatus.SC_OK, httpClient.executeMethod(postMethod));
    assertEquals("hello", postMethod.getResponseBodyAsString());

    credentials = new UsernamePasswordCredentials("asdf", "asdf");
    httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    assertEquals(HttpStatus.SC_UNAUTHORIZED, httpClient.executeMethod(postMethod));

    credentials = new UsernamePasswordCredentials("admin2", "admin2");
    httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    assertEquals(HttpStatus.SC_OK, httpClient.executeMethod(postMethod));
    assertEquals("hello", postMethod.getResponseBodyAsString());
}

From source file:org.nuxeo.ecm.tokenauth.servlet.TokenAuthenticationServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // Don't provide token for anonymous user unless 'allowAnonymous' parameter is explicitly set to true in
    // the authentication plugin configuration
    Principal principal = req.getUserPrincipal();
    if (principal instanceof NuxeoPrincipal && ((NuxeoPrincipal) principal).isAnonymous()) {
        PluggableAuthenticationService authenticationService = (PluggableAuthenticationService) Framework
                .getRuntime().getComponent(PluggableAuthenticationService.NAME);
        AuthenticationPluginDescriptor tokenAuthPluginDesc = authenticationService
                .getDescriptor(TOKEN_AUTH_PLUGIN_NAME);
        if (tokenAuthPluginDesc == null || !(Boolean
                .valueOf(tokenAuthPluginDesc.getParameters().get(TokenAuthenticator.ALLOW_ANONYMOUS_KEY)))) {
            log.debug("Anonymous user is not allowed to acquire an authentication token.");
            resp.sendError(HttpStatus.SC_UNAUTHORIZED);
            return;
        }/*ww w. j  a v a 2s . c  o  m*/

    }

    // Get request parameters
    String applicationName = req.getParameter(APPLICATION_NAME_PARAM);
    String deviceId = req.getParameter(DEVICE_ID_PARAM);
    String deviceDescription = req.getParameter(DEVICE_DESCRIPTION_PARAM);
    String permission = req.getParameter(PERMISSION_PARAM);
    String revokeParam = req.getParameter(REVOKE_PARAM);
    boolean revoke = Boolean.valueOf(revokeParam);

    // If one of the required parameters is null or empty, send an
    // error with the 400 status
    if (!revoke && (StringUtils.isEmpty(applicationName) || StringUtils.isEmpty(deviceId)
            || StringUtils.isEmpty(permission))) {
        log.error(
                "The following request parameters are mandatory to acquire an authentication token: applicationName, deviceId, permission.");
        resp.sendError(HttpStatus.SC_BAD_REQUEST);
        return;
    }
    if (revoke && (StringUtils.isEmpty(applicationName) || StringUtils.isEmpty(deviceId))) {
        log.error(
                "The following request parameters are mandatory to revoke an authentication token: applicationName, deviceId.");
        resp.sendError(HttpStatus.SC_BAD_REQUEST);
        return;
    }

    // Decode parameters
    applicationName = URIUtil.decode(applicationName);
    deviceId = URIUtil.decode(deviceId);
    if (!StringUtils.isEmpty(deviceDescription)) {
        deviceDescription = URIUtil.decode(deviceDescription);
    }
    if (!StringUtils.isEmpty(permission)) {
        permission = URIUtil.decode(permission);
    }

    // Get user name from request Principal
    if (principal == null) {
        resp.sendError(HttpStatus.SC_UNAUTHORIZED);
        return;
    }
    String userName = principal.getName();

    // Write response
    String response = null;
    int statusCode;
    TokenAuthenticationService tokenAuthService = Framework.getLocalService(TokenAuthenticationService.class);
    try {
        // Token acquisition: acquire token and write it to the response
        // body
        if (!revoke) {
            response = tokenAuthService.acquireToken(userName, applicationName, deviceId, deviceDescription,
                    permission);
            statusCode = 201;
        }
        // Token revocation
        else {
            String token = tokenAuthService.getToken(userName, applicationName, deviceId);
            if (token == null) {
                response = String.format(
                        "No token found for userName %s, applicationName %s and deviceId %s; nothing to do.",
                        userName, applicationName, deviceId);
                statusCode = 400;
            } else {
                tokenAuthService.revokeToken(token);
                response = String.format("Token revoked for userName %s, applicationName %s and deviceId %s.",
                        userName, applicationName, deviceId);
                statusCode = 202;
            }
        }
        sendTextResponse(resp, response, statusCode);
    } catch (TokenAuthenticationException e) {
        // Should never happen as parameters have already been checked
        resp.sendError(HttpStatus.SC_NOT_FOUND);
    }
}

From source file:org.nuxeo.ecm.tokenauth.TestAnonymousTokenAuthenticator.java

@Test
public void testAuthenticatorAsAnonymous() throws Exception {

    // Mock token authentication callback and acquire token for anonymous user directly from token authentication
    // service/*from w w  w . ja v  a2s.c  o m*/
    TokenAuthenticationCallback cb = new TokenAuthenticationCallback("Guest", "myFavoriteApp",
            "Ubuntu box 64 bits", "This is my personal Linux box", "rw");
    String token = cb.getRemoteToken(cb.getTokenParams());
    assertNotNull(token);

    // Check automation call with anonymous user not allowed
    try {
        automationClient.getSession(token);
        fail("Getting an Automation client session with a token as anonymous user should throw a RemoteException with HTTP 401 status code");
    } catch (RemoteException e) {
        assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getStatus());
    }

    // Check automation call with anonymous user allowed
    harness.deployContrib("org.nuxeo.ecm.platform.login.token.test",
            "OSGI-INF/test-token-authentication-allow-anonymous-token-contrib.xml");

    Session clientSession = automationClient.getSession(token);
    assertEquals("Guest", clientSession.getLogin().getUsername());

    harness.undeployContrib("org.nuxeo.ecm.platform.login.token.test",
            "OSGI-INF/test-token-authentication-allow-anonymous-token-contrib.xml");
}

From source file:org.nuxeo.ecm.tokenauth.TestTokenAuthenticator.java

@Test
public void testAuthenticator() throws Exception {

    // Try to get client session using a bad token, should throw a RemoteException with HTTP 401 status code
    try {/*from w  ww .  j a  va2  s . co m*/
        automationClient.getSession("badToken");
        fail("Getting an Automation client session with a bad token should throw a RemoteException with HTTP 401 status code");
    } catch (RemoteException e) {
        assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getStatus());
    }

    // Mock token authentication callback
    TokenAuthenticationCallback cb = new TokenAuthenticationCallback("Administrator", "myFavoriteApp",
            "Ubuntu box 64 bits", "This is my personal Linux box", "rw");
    assertNull(cb.getLocalToken());

    // Get client session using callback, should acquire a remote token,
    // store it locally and return a session as Administrator
    Session clientSession = automationClient.getSession(cb);
    assertNotNull(cb.getLocalToken());
    assertEquals("Administrator", clientSession.getLogin().getUsername());

    // Check automation call
    String testDocId = session.getDocument(new PathRef(TokenAuthenticationRepositoryInit.getTestDocPath()))
            .getId();
    Document testDoc = (Document) clientSession.newRequest(FetchDocument.ID)
            .setHeader("X-NXDocumentProperties", "dublincore").set("value", testDocId).execute();
    assertNotNull(testDoc);
    assertEquals("My test doc", testDoc.getTitle());
    assertEquals("For test purpose.", testDoc.getString("dc:description"));

    // Get client session using callback, should use local token and return
    // a session as Administrator
    clientSession = automationClient.getSession(cb);
    assertEquals("Administrator", clientSession.getLogin().getUsername());
}

From source file:org.obm.caldav.client.AbstractPushTest.java

private synchronized Document doRequest(HttpMethod hm) {
    Document xml = null;/* w  w w  .ja  va 2 s. co m*/
    try {
        int ret = hc.executeMethod(hm);
        Header[] hs = hm.getResponseHeaders();
        for (Header h : hs) {
            System.err.println("head[" + h.getName() + "] => " + h.getValue());
        }
        if (ret == HttpStatus.SC_UNAUTHORIZED) {
            UsernamePasswordCredentials upc = new UsernamePasswordCredentials(login, password);
            authenticate = hm.getHostAuthState().getAuthScheme().authenticate(upc, hm);
            return null;
        } else if (ret == HttpStatus.SC_OK || ret == HttpStatus.SC_MULTI_STATUS) {
            InputStream is = hm.getResponseBodyAsStream();
            if (is != null) {
                if ("text/xml".equals(hm.getRequestHeader("Content-Type"))) {
                    xml = DOMUtils.parse(is);
                    DOMUtils.logDom(xml);
                } else {
                    System.out.println(FileUtils.streamString(is, false));
                }
            }
        } else {
            System.err.println("method failed:\n" + hm.getStatusLine() + "\n" + hm.getResponseBodyAsString());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        hm.releaseConnection();
    }
    return xml;
}

From source file:org.opencastproject.kernel.rest.RestPublisher.java

/** Activates this rest publisher */
@SuppressWarnings("unchecked")
protected void activate(ComponentContext componentContext) {
    logger.debug("activate()");
    this.baseServerUri = componentContext.getBundleContext().getProperty("org.opencastproject.server.url");
    this.componentContext = componentContext;
    this.fourOhFour = "The resource you requested does not exist."; // TODO: Replace this with something a little nicer
    this.servletRegistrationMap = new ConcurrentHashMap<String, ServiceRegistration>();
    this.providers = new ArrayList();

    JSONProvider jsonProvider = new MatterhornJSONProvider();
    jsonProvider.setIgnoreNamespaces(true);
    jsonProvider.setNamespaceMap(NAMESPACE_MAP);

    providers.add(jsonProvider);/*from   ww w  . j  a va  2 s  .c  o m*/
    providers.add(new ExceptionMapper<NotFoundException>() {
        public Response toResponse(NotFoundException e) {
            return Response.status(404).entity(fourOhFour).type(MediaType.TEXT_PLAIN).build();
        }
    });
    providers.add(new ExceptionMapper<UnauthorizedException>() {
        public Response toResponse(UnauthorizedException e) {
            return Response.status(HttpStatus.SC_UNAUTHORIZED).entity("unauthorized").type(MediaType.TEXT_PLAIN)
                    .build();
        };
    });
    providers.add(new RestDocRedirector());

    try {
        jaxRsTracker = new JaxRsServiceTracker();
        bundleTracker = new StaticResourceBundleTracker(componentContext.getBundleContext());
    } catch (InvalidSyntaxException e) {
        throw new IllegalStateException(e);
    }
    jaxRsTracker.open();
    bundleTracker.open();
}

From source file:org.opens.tanaguru.util.http.HttpRequestHandler.java

private int computeStatus(int status) {
    switch (status) {
    case HttpStatus.SC_FORBIDDEN:
    case HttpStatus.SC_METHOD_NOT_ALLOWED:
    case HttpStatus.SC_BAD_REQUEST:
    case HttpStatus.SC_UNAUTHORIZED:
    case HttpStatus.SC_PAYMENT_REQUIRED:
    case HttpStatus.SC_NOT_FOUND:
    case HttpStatus.SC_NOT_ACCEPTABLE:
    case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
    case HttpStatus.SC_REQUEST_TIMEOUT:
    case HttpStatus.SC_CONFLICT:
    case HttpStatus.SC_GONE:
    case HttpStatus.SC_LENGTH_REQUIRED:
    case HttpStatus.SC_PRECONDITION_FAILED:
    case HttpStatus.SC_REQUEST_TOO_LONG:
    case HttpStatus.SC_REQUEST_URI_TOO_LONG:
    case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE:
    case HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE:
    case HttpStatus.SC_EXPECTATION_FAILED:
    case HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE:
    case HttpStatus.SC_METHOD_FAILURE:
    case HttpStatus.SC_UNPROCESSABLE_ENTITY:
    case HttpStatus.SC_LOCKED:
    case HttpStatus.SC_FAILED_DEPENDENCY:
    case HttpStatus.SC_INTERNAL_SERVER_ERROR:
    case HttpStatus.SC_NOT_IMPLEMENTED:
    case HttpStatus.SC_BAD_GATEWAY:
    case HttpStatus.SC_SERVICE_UNAVAILABLE:
    case HttpStatus.SC_GATEWAY_TIMEOUT:
    case HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED:
    case HttpStatus.SC_INSUFFICIENT_STORAGE:
        return 0;
    case HttpStatus.SC_CONTINUE:
    case HttpStatus.SC_SWITCHING_PROTOCOLS:
    case HttpStatus.SC_PROCESSING:
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
    case HttpStatus.SC_ACCEPTED:
    case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION:
    case HttpStatus.SC_NO_CONTENT:
    case HttpStatus.SC_RESET_CONTENT:
    case HttpStatus.SC_PARTIAL_CONTENT:
    case HttpStatus.SC_MULTI_STATUS:
    case HttpStatus.SC_MULTIPLE_CHOICES:
    case HttpStatus.SC_MOVED_PERMANENTLY:
    case HttpStatus.SC_MOVED_TEMPORARILY:
    case HttpStatus.SC_SEE_OTHER:
    case HttpStatus.SC_NOT_MODIFIED:
    case HttpStatus.SC_USE_PROXY:
    case HttpStatus.SC_TEMPORARY_REDIRECT:
        return 1;
    default://from w w  w .  j  a  v  a  2 s. c  o  m
        return 1;
    }
}

From source file:org.paxle.filter.robots.impl.RobotsTxtManager.java

/**
 * Downloads a <i>robots.txt</i> file from the given url and parses it
 * @param robotsUrlStr the URL to the robots.txt. This must be a http(s) resource
 * @return the parsed robots.txt file as a {@link RobotsTxt}-object
 * @throws IOException/* w  w w .  ja  v a 2  s  .co m*/
 * @throws URISyntaxException 
 */
RobotsTxt getFromWeb(URI robotsURL) throws IOException, URISyntaxException {
    String hostPort = this.getHostPort(robotsURL);

    String statusLine = null;
    if (!robotsURL.getScheme().startsWith("http")) {
        throw new IOException(String.format("Unsupported protocol: %s", robotsURL.getScheme()));
    }

    InputStream inputStream = null;
    HttpMethod getMethod = null;
    try {
        getMethod = new GetMethod(robotsURL.toASCIIString());
        int code = this.httpClient.executeMethod(getMethod);
        statusLine = getMethod.getStatusLine().toString();

        if (code == HttpStatus.SC_UNAUTHORIZED || code == HttpStatus.SC_FORBIDDEN) {
            // access to the whole website is restricted
            return new RobotsTxt(hostPort, RobotsTxt.RELOAD_INTERVAL_DEFAULT, statusLine, true);
        } else if (code == HttpStatus.SC_NOT_FOUND) {
            // no robots.txt provided
            return new RobotsTxt(hostPort, RobotsTxt.RELOAD_INTERVAL_DEFAULT, statusLine);
        } else if (code != HttpStatus.SC_OK) {
            // the robots.txt seems not to be deliverable
            return new RobotsTxt(hostPort, RobotsTxt.RELOAD_INTERVAL_DEFAULT, statusLine);
        }

        Header contentTypeHeader = getMethod.getResponseHeader("Content-Type");
        if (contentTypeHeader != null && !contentTypeHeader.getValue().startsWith("text/plain")) {
            // the robots.txt seems not to be available
            return new RobotsTxt(hostPort, RobotsTxt.RELOAD_INTERVAL_ERROR,
                    "Wrong mimeType " + contentTypeHeader.getValue());
        }

        inputStream = getMethod.getResponseBodyAsStream();
        RobotsTxt robotsTxt = new RobotsTxt(hostPort, RobotsTxt.RELOAD_INTERVAL_DEFAULT, statusLine);
        return this.parseRobotsTxt(robotsTxt, inputStream);
    } catch (IOException e) {
        long reloadInterval = RobotsTxt.RELOAD_INTERVAL_TEMP_ERROR;
        String status = e.getMessage();

        if (e instanceof UnknownHostException) {
            reloadInterval = RobotsTxt.RELOAD_INTERVAL_ERROR;
            status = "Unknown host";
            logger.info(String.format("Unknown host '%s'.", robotsURL.getHost()));
        } else if (e instanceof CircularRedirectException || e instanceof RedirectException
                || e instanceof InvalidRedirectLocationException) {
            reloadInterval = RobotsTxt.RELOAD_INTERVAL_ERROR;
            logger.info(String.format("Invalid redirection on host '%s'.", hostPort));
        } else if (e instanceof SocketTimeoutException || e instanceof ConnectTimeoutException
                || e instanceof NoHttpResponseException) {
            logger.debug(String.format("TimeOut while loading robots.txt from host '%s'.", hostPort));
        } else if (!(e instanceof ConnectException || e instanceof SocketException)) {
            logger.error("Exception while loading robots.txt from " + hostPort, e);
        }

        return new RobotsTxt(hostPort, reloadInterval, status);
    } catch (IllegalArgumentException e) {
        // occurs if redirected to an invalid URI, see https://bugs.pxl.li/view.php?id=172
        // we treat it like a 404, see above
        logger.info(String.format("Invalid redirection URI on host '%s'.", hostPort));
        return new RobotsTxt(hostPort, RobotsTxt.RELOAD_INTERVAL_DEFAULT, "Redirected to illegal URI");
    } catch (IllegalStateException e) {
        // occurs if redirected to an URI with an invalid protocol, see https://bugs.pxl.li/view.php?id=169
        // we treat it like a 404, see above
        logger.info(String.format("Invalid redirection URI on host '%s'.", hostPort));
        return new RobotsTxt(hostPort, RobotsTxt.RELOAD_INTERVAL_DEFAULT, "Redirected to illegal URI");

    } finally {
        if (inputStream != null)
            try {
                inputStream.close();
            } catch (Exception e) {
                this.logger.error(e);
            }
        if (getMethod != null)
            getMethod.releaseConnection();
    }
}

From source file:org.pengyou.ooo.utils.WebDavStore.java

private void handleException(Exception ex) {
    if (ex instanceof HttpException) {
        if (((HttpException) ex).getReasonCode() == HttpStatus.SC_METHOD_NOT_ALLOWED) {
            log.error("Not WebDAV-enabled?");
        } else if (((HttpException) ex).getReasonCode() == HttpStatus.SC_UNAUTHORIZED) {
            log.error("Unauthorized");
        } else {/*from   w  ww. j  a va 2  s  . c  o  m*/
            log.error(ex.getMessage(), ex);
        }
    } else if (ex instanceof IOException) {
        log.error(ex.getMessage(), ex);
    } else {
        log.error(ex.getMessage(), ex);
    }
}

From source file:org.pentaho.di.baserver.utils.widgets.callEndpointTabs.ServerTab.java

public boolean testConnection(boolean showDialogOnSuccess) {
    String serverUrl = getServerUrl();
    String userName = getUserName();
    String password = getPassword();
    int serverStatus = Inspector.getInstance().checkServerStatus(serverUrl, userName, password);
    MessageBox messageBox = new MessageBox(getShell());
    switch (serverStatus) {
    case HttpStatus.SC_OK:
        if (!showDialogOnSuccess) {
            return true;
        }/*from   www  . j  ava2 s .  com*/
        messageBox
                .setText(BaseMessages.getString(PKG, "CallEndpointDialog.TabItem.Server.Test.Success.Header"));
        messageBox.setMessage(
                BaseMessages.getString(PKG, "CallEndpointDialog.TabItem.Server.Test.Success.Message"));
        break;
    case HttpStatus.SC_UNAUTHORIZED:
        messageBox.setText(
                BaseMessages.getString(PKG, "CallEndpointDialog.TabItem.Server.Test.UnableLogin.Header"));
        messageBox.setMessage(
                BaseMessages.getString(PKG, "CallEndpointDialog.TabItem.Server.Test.UnableLogin.Message"));
        break;
    default:
        messageBox.setText(
                BaseMessages.getString(PKG, "CallEndpointDialog.TabItem.Server.Test.UnableConnect.Header"));
        messageBox.setMessage(
                BaseMessages.getString(PKG, "CallEndpointDialog.TabItem.Server.Test.UnableConnect.Message"));
        break;
    }
    messageBox.open();
    return serverStatus == HttpStatus.SC_OK;
}