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.picketlink.test.authentication.web.token.TokenAuthenticationSchemeTestCase.java

@Test
@OperateOnDeployment("default")
public void testSuccessfulAuthentication() throws Exception {
    WebClient client = new WebClient();
    URL protectedServletUrl = new URL(getProtectedResourceURL().toString() + "/servlet");
    WebRequestSettings request = new WebRequestSettings(protectedServletUrl);
    WebResponse response = client.loadWebResponse(request);

    assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusCode());

    String authenticateHeader = response.getResponseHeaderValue("WWW-Authenticate");

    assertNotNull(authenticateHeader);//w w  w . j  a va  2s  . co  m
    assertTrue(authenticateHeader.contains("Token"));

    // we first use BASIC, which is the primary authc scheme, to issue a token
    request.addAdditionalHeader("Authorization", new String("Basic "
            + Base64.encodeBytes(String.valueOf(DEFAULT_USERNAME + ":" + DEFAULT_USER_PASSWD).getBytes())));

    response = client.loadWebResponse(request);

    String responseData = response.getContentAsString();

    assertNotNull(responseData);
    assertNull(client.getCookieManager().getCookie(SESSION_HEADER_NAME.toUpperCase()));

    String token = responseData.substring(responseData.indexOf(":") + 2, responseData.length() - 2);

    // now we can use the token to authenticate every single request
    request.addAdditionalHeader("Authorization", new String("Token " + token));

    response = client.loadWebResponse(request);

    assertEquals(HttpStatus.SC_OK, response.getStatusCode());
    assertTrue(response.getContentAsString().contains("User is john"));
    assertNull(client.getCookieManager().getCookie(SESSION_HEADER_NAME.toUpperCase()));

    request = new WebRequestSettings(protectedServletUrl);
    response = client.loadWebResponse(request);

    assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusCode());

    authenticateHeader = response.getResponseHeaderValue("WWW-Authenticate");

    assertNotNull(authenticateHeader);
    assertTrue(authenticateHeader.contains("Token"));
}

From source file:org.review_board.ereviewboard.core.client.ReviewboardHttpClient.java

public boolean apiEntryPointExist(IProgressMonitor monitor) throws ReviewboardException {
    GetMethod getMethod = new GetMethod(location.getUrl() + "/api/");
    int status = executeRequest(getMethod, monitor);
    return status == HttpStatus.SC_OK || status == HttpStatus.SC_UNAUTHORIZED;
}

From source file:org.review_board.ereviewboard.core.client.ReviewboardHttpClient.java

public String login(String username, String password, IProgressMonitor monitor) throws ReviewboardException {

    GetMethod loginRequest = new GetMethod(location.getUrl() + "/api/info/");
    Credentials credentials = new UsernamePasswordCredentials(username, password);

    monitor = Policy.monitorFor(monitor);

    String foundSessionCookie = null;

    try {//from www. j a  v a 2 s  . com
        monitor.beginTask("Logging in", IProgressMonitor.UNKNOWN);

        // TODO: this will probably affect existing requests, might have ill side-effects
        httpClient.getState().clearCookies();

        // perform authentication
        String authHeader = new BasicScheme().authenticate(credentials, loginRequest);
        loginRequest.addRequestHeader("Authorization", authHeader);

        // execute and validate call
        int requestStatus = executeRequest(loginRequest, monitor);

        switch (requestStatus) {

        case HttpStatus.SC_OK:
            break;
        case HttpStatus.SC_UNAUTHORIZED:
            throw new ReviewboardException("Authentication failed, please check your username and password");
        default:
            throw new ReviewboardException("Request returned unacceptable status code " + requestStatus);
        }

        // look for session cookie
        for (Cookie cookie : httpClient.getState().getCookies())
            if (cookie.getName().equals("rbsessionid"))
                foundSessionCookie = cookie.getValue();

        if (foundSessionCookie == null)
            throw new ReviewboardException("Did not find session cookie in response");

        return foundSessionCookie;

    } catch (AuthenticationException e) {
        throw new ReviewboardException(e.getMessage(), e);
    } finally {
        loginRequest.releaseConnection();
        monitor.done();
    }
}

From source file:org.rhq.enterprise.server.plugins.url.HttpProvider.java

/**
 * Given any URL, will return a stream to that URL using the HTTP client and GET method
 * for the authentication as defined in this content source's configuration.
 * //w  w w . j  av  a2 s.com
 * @param url the URL whose stream of content is returned
 *
 * @return stream containing the content for the given URL
 *
 * @throws Exception if cannot get the streamed content
 */
protected InputStream getInputStreamForUrl(URL url) throws Exception {
    String fullLocation = url.toString();

    HttpClient client = new HttpClient();
    HttpMethodBase method = new GetMethod(fullLocation);
    prepareHttpClient(client, method);
    int status = client.executeMethod(method);

    switch (status) {
    case HttpStatus.SC_OK: {
        break; // good to go
    }

    case HttpStatus.SC_NOT_FOUND: {
        throw new Exception("Could not find the content at URL [" + fullLocation
                + "]. Make sure the content source defines a valid URL.");
    }

    case HttpStatus.SC_UNAUTHORIZED:
    case HttpStatus.SC_FORBIDDEN: {
        throw new Exception("Invalid login credentials specified for user [" + username + "]. Make sure "
                + "this user is valid and the password specified for this content source is correct.");
    }

    default: {
        throw new Exception("Failed to retrieve content. status code=" + status);
    }
    }

    InputStream stream = method.getResponseBodyAsStream();

    return stream;
}

From source file:org.roda.wui.filter.CasClient.java

/**
 * Get a <strong>Ticket Granting Ticket</strong> from the CAS server for the
 * specified <i>username</i> and <i>password</i>.
 * //from www .ja v  a 2  s .c om
 * @param username
 *          the username.
 * @param password
 *          the password.
 * @return the <strong>Ticket Granting Ticket</strong>
 * @throws AuthenticationDeniedException
 *           if the CAS server rejected the specified credentials.
 * @throws GenericException
 *           if some error occurred.
 */
public String getTicketGrantingTicket(final String username, final String password)
        throws AuthenticationDeniedException, GenericException {
    final HttpClient client = new HttpClient();
    final PostMethod post = new PostMethod(String.format("%s/v1/tickets", this.casServerUrlPrefix));
    post.setRequestBody(new NameValuePair[] { new NameValuePair("username", username),
            new NameValuePair("password", password) });
    try {
        client.executeMethod(post);
        final String response = post.getResponseBodyAsString();
        if (post.getStatusCode() == HttpStatus.SC_CREATED) {
            final Matcher matcher = Pattern.compile(".*action=\".*/(.*?)\".*").matcher(response);
            if (matcher.matches()) {
                return matcher.group(1);
            }
            LOGGER.warn(NO_TICKET);
            throw new GenericException(NO_TICKET);
        } else if (post.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new AuthenticationDeniedException("Could not create ticket: " + post.getStatusText());
        } else {
            LOGGER.warn(invalidResponseMessage(post));
            throw new GenericException(invalidResponseMessage(post));
        }
    } catch (final IOException e) {
        throw new GenericException(e.getMessage(), e);
    } finally {
        post.releaseConnection();
    }
}

From source file:org.sakaiproject.nakamura.grouper.changelog.util.NakamuraHttpUtils.java

/**
 * Prepare an HTTP request to Sakai OAE and parse the response (if JSON).
 * @param client an {@link HttpClient} to execute the request.
 * @param method an HTTP method to send/*ww w . j  a v  a  2  s . c  om*/
 * @return a JSONObject of the response if the request returns JSON
 * @throws GroupModificationException if there was an error updating the group information.
 */
public static JSONObject http(HttpClient client, HttpMethod method) throws GroupModificationException {

    method.setRequestHeader("User-Agent", HTTP_USER_AGENT);
    method.setRequestHeader("Referer", HTTP_REFERER);

    String errorMessage = null;
    String responseString = null;
    JSONObject responseJSON = null;

    boolean isJSONRequest = !method.getPath().toString().endsWith(".html");

    if (log.isDebugEnabled() && method instanceof PostMethod) {
        log.debug(method.getName() + " " + method.getPath() + " params:");
        for (NameValuePair nvp : ((PostMethod) method).getParameters()) {
            log.debug(nvp.getName() + " = " + nvp.getValue());
        }
    }

    int responseCode = -1;
    try {
        responseCode = client.executeMethod(method);
        responseString = StringUtils.trimToNull(IOUtils.toString(method.getResponseBodyAsStream()));

        if (isJSONRequest) {
            responseJSON = parseJSONResponse(responseString);
        }

        if (log.isDebugEnabled()) {
            log.debug(responseCode + " " + method.getName() + " " + method.getPath());
        }
        if (log.isTraceEnabled()) {
            log.trace("reponse: " + responseString);
        }

        switch (responseCode) {

        case HttpStatus.SC_OK: // 200
        case HttpStatus.SC_CREATED: // 201
            break;
        case HttpStatus.SC_BAD_REQUEST: // 400
        case HttpStatus.SC_UNAUTHORIZED: // 401
        case HttpStatus.SC_NOT_FOUND: // 404
        case HttpStatus.SC_INTERNAL_SERVER_ERROR: // 500
            if (isJSONRequest && responseJSON != null) {
                errorMessage = responseJSON.getString("status.message");
            }
            if (errorMessage == null) {
                errorMessage = "Empty " + responseCode + " error. Check the logs on the Sakai OAE server.";
            }
            break;
        default:
            errorMessage = "Unknown HTTP response " + responseCode;
            break;
        }
    } catch (Exception e) {
        errorMessage = "An exception occurred communicatingSakai OAE. " + e.toString();
    } finally {
        method.releaseConnection();
    }

    if (errorMessage != null) {
        log.error(errorMessage);
        errorToException(responseCode, errorMessage);
    }
    return responseJSON;
}

From source file:org.sonatype.nexus.proxy.storage.remote.commonshttpclient.CommonsHttpClientRemoteStorage.java

/**
 * Execute method. In case of any exception thrown by HttpClient, it will release the connection. In other cases it
 * is the duty of caller to do it, or process the input stream.
 * /*from   w  w w. ja va 2 s.c o m*/
 * @param method the method
 * @return the int
 */
protected int doExecuteMethod(ProxyRepository repository, ResourceStoreRequest request, HttpMethod method,
        URL remoteUrl) throws RemoteStorageException {
    URI methodURI = null;

    try {
        methodURI = method.getURI();
    } catch (URIException e) {
        getLogger().debug("Could not format debug log message", e);
    }

    if (getLogger().isDebugEnabled()) {
        getLogger().debug("Invoking HTTP " + method.getName() + " method against remote location " + methodURI);
    }

    RemoteStorageContext ctx = getRemoteStorageContext(repository);

    HttpClient httpClient = (HttpClient) ctx.getContextObject(CTX_KEY_CLIENT);

    HostConfiguration httpConfiguration = (HostConfiguration) ctx.getContextObject(CTX_KEY_HTTP_CONFIGURATION);

    method.setRequestHeader(new Header("user-agent", formatUserAgentString(ctx, repository)));
    method.setRequestHeader(new Header("accept", "*/*"));
    method.setRequestHeader(new Header("accept-language", "en-us"));
    method.setRequestHeader(new Header("accept-encoding", "gzip, identity"));
    method.setRequestHeader(new Header("cache-control", "no-cache"));

    // HTTP keep alive should not be used, except when NTLM is used
    Boolean isNtlmUsed = (Boolean) ctx.getContextObject(HttpClientProxyUtil.NTLM_IS_IN_USE_KEY);

    if (isNtlmUsed == null || !isNtlmUsed) {
        method.setRequestHeader(new Header("Connection", "close"));
        method.setRequestHeader(new Header("Proxy-Connection", "close"));
    }

    method.setFollowRedirects(true);

    if (StringUtils.isNotBlank(ctx.getRemoteConnectionSettings().getQueryString())) {
        method.setQueryString(ctx.getRemoteConnectionSettings().getQueryString());
    }

    int resultCode;

    try {
        resultCode = httpClient.executeMethod(httpConfiguration, method);

        final Header httpServerHeader = method.getResponseHeader("server");
        checkForRemotePeerAmazonS3Storage(repository,
                httpServerHeader == null ? null : httpServerHeader.getValue());

        Header proxyReturnedErrorHeader = method.getResponseHeader(NEXUS_MISSING_ARTIFACT_HEADER);
        boolean proxyReturnedError = proxyReturnedErrorHeader != null
                && Boolean.valueOf(proxyReturnedErrorHeader.getValue());

        if (resultCode == HttpStatus.SC_FORBIDDEN) {
            throw new RemoteAccessDeniedException(repository, remoteUrl,
                    HttpStatus.getStatusText(HttpStatus.SC_FORBIDDEN));
        } else if (resultCode == HttpStatus.SC_UNAUTHORIZED) {
            throw new RemoteAuthenticationNeededException(repository,
                    HttpStatus.getStatusText(HttpStatus.SC_UNAUTHORIZED));
        } else if (resultCode == HttpStatus.SC_OK && proxyReturnedError) {
            throw new RemoteStorageException(
                    "Invalid artifact found, most likely a proxy redirected to an HTML error page.");
        }
    } catch (RemoteStorageException e) {
        method.releaseConnection();

        throw e;
    } catch (HttpException ex) {
        method.releaseConnection();

        throw new RemoteStorageException("Protocol error while executing " + method.getName()
                + " method. [repositoryId=\"" + repository.getId() + "\", requestPath=\""
                + request.getRequestPath() + "\", remoteUrl=\"" + methodURI + "\"]", ex);
    } catch (IOException ex) {
        method.releaseConnection();

        throw new RemoteStorageException("Transport error while executing " + method.getName()
                + " method [repositoryId=\"" + repository.getId() + "\", requestPath=\""
                + request.getRequestPath() + "\", remoteUrl=\"" + methodURI + "\"]", ex);
    }

    return resultCode;
}

From source file:org.wso2.am.integration.tests.other.InvalidAuthTokenLargePayloadTestCase.java

@Test(groups = { "wso2.am" }, description = "Subscribe and invoke api", dependsOnMethods = "testApiCreation")
public void testApiInvocation() throws Exception {
    apiStore = new APIStoreRestClient(storeURLHttp);
    apiStore.login(user.getUserName(), String.valueOf(user.getPassword()));
    //add a application
    HttpResponse serviceResponse = apiStore.addApplication(APP_NAME, APIThrottlingTier.UNLIMITED.getState(), "",
            "this-is-test");
    verifyResponse(serviceResponse);//from  www  .  j  a  v  a  2  s .c  om

    //subscribe to the api
    SubscriptionRequest subscriptionRequest = new SubscriptionRequest(API_NAME, user.getUserName());
    subscriptionRequest.setApplicationName(APP_NAME);
    subscriptionRequest.setTier(APIMIntegrationConstants.API_TIER.GOLD);
    serviceResponse = apiStore.subscribe(subscriptionRequest);
    verifyResponse(serviceResponse);

    //invoke api
    requestHeaders.put(APIMIntegrationConstants.AUTHORIZATION_HEADER, "Bearer invalid_token_key");
    requestHeaders.put("Content-Type", ContentType.APPLICATION_JSON.toString());
    String invokeURL = getAPIInvocationURLHttp(API_CONTEXT, API_VERSION) + "/post";

    HttpResponse response;
    //first test for small payload
    try {
        response = uploadFile(invokeURL, new File(testFile1KBFilePath), requestHeaders);
        Assert.fail("Resource cannot be access with wrong access token");
    } catch (IOException e) {
        Assert.assertTrue(e.getMessage().contains(String.valueOf(HttpStatus.SC_UNAUTHORIZED)));
    }

    //test for medium payload
    try {
        response = uploadFile(invokeURL, new File(testFile100KBFilePath), requestHeaders);
        Assert.fail("Resource cannot be access with wrong access token");
    } catch (IOException e) {
        Assert.assertTrue(e.getMessage().contains(String.valueOf(HttpStatus.SC_UNAUTHORIZED)));
    }

    //test for large payload
    try {
        response = uploadFile(invokeURL, new File(testFile1MBFilePath), requestHeaders);
        Assert.fail("Resource cannot be access with wrong access token");
    } catch (IOException e) {
        Assert.assertTrue(e.getMessage().contains(String.valueOf(HttpStatus.SC_UNAUTHORIZED)));
    }
}

From source file:org.wso2.carbon.appfactory.s4.integration.StratosRestService.java

private void subscribeCartridge(CartridgeInfoBean cartridgeInfoBean)
        throws CommandException, AppFactoryException {
    String completeJsonSubscribeString;

    GsonBuilder gsonBuilder = new GsonBuilder();
    Gson gson = gsonBuilder.create();//from w  ww. java2s . c  o  m
    completeJsonSubscribeString = gson.toJson(cartridgeInfoBean, CartridgeInfoBean.class);

    HttpClient httpClient = getNewHttpClient();

    DomainMappingResponse response = doPost(httpClient,
            this.stratosManagerURL + this.SUBSCRIBE_CARTRIDGE_REST_END_POINT, completeJsonSubscribeString);

    if (response.getStatusCode() == HttpStatus.SC_OK) {

        if (log.isDebugEnabled()) {
            log.debug(" Status 200 returned when subsctibing to cartridge "
                    + cartridgeInfoBean.getCartridgeType());
        }

        String subscriptionOutput = response.getResponse();

        if (subscriptionOutput == null) {
            log.error("Error occurred while getting response. Response is null");
            return;
        }

        String subscriptionOutputJSON = subscriptionOutput.substring(20, subscriptionOutput.length() - 1);
        SubscriptionInfo subcriptionInfo = gson.fromJson(subscriptionOutputJSON, SubscriptionInfo.class);

        log.info(String.format("Successfully subscribed to %s cartridge with alias %s with repo url %s" + ".%n",
                cartridgeInfoBean.getCartridgeType(), cartridgeInfoBean.getAlias(),
                subcriptionInfo.getRepositoryURL()));
    } else if (response.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
        log.error("Authorization failed when subsctibing to cartridge " + cartridgeInfoBean.getCartridgeType());
        return;
    } else {
        log.error("Error occurred while subscribing to cartdridge," + "server returned  "
                + response.getStatusCode() + " " + response.getResponse());
        return;
    }
}

From source file:org.wso2.carbon.appfactory.s4.integration.StratosRestService.java

public void addTenant(String admin, String firstName, String lastName, String password, String domain,
        String email) throws AppFactoryException {
    HttpClient httpClient = getNewHttpClient();
    try {/*from w  w w. j  a v  a 2s  .  co  m*/
        TenantInfoBean tenantInfo = new TenantInfoBean();
        tenantInfo.setAdmin(admin);
        tenantInfo.setFirstname(firstName);
        tenantInfo.setLastname(lastName);
        tenantInfo.setAdminPassword(password);
        tenantInfo.setTenantDomain(domain);
        tenantInfo.setEmail(email);

        GsonBuilder gsonBuilder = new GsonBuilder();
        Gson gson = gsonBuilder.create();

        String jsonString = gson.toJson(tenantInfo, TenantInfoBean.class);
        String completeJsonString = "{\"tenantInfoBean\":" + jsonString + "}";

        DomainMappingResponse response = doPost(httpClient, this.stratosManagerURL + ADD_TENANT_END_POINT,
                completeJsonString);

        if (response.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            log.error("Authorization failed for the operation");
            return;
        } else if (response.getStatusCode() == HttpStatus.SC_NO_CONTENT) {
            log.debug("Tenant added successfully");
            return;
        } else if (response.getStatusCode() != HttpStatus.SC_NO_CONTENT) {
            log.error("Error occurred while adding tenant," + "server returned  " + response.getStatusCode());
            return;
        } else {
            System.out.println("Unhandle error");
            return;
        }

    } catch (Exception e) {
        log.error(e);
        handleException("Exception in creating tenant", e);
    }
}