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:com.thoughtworks.twist.mingle.core.MingleClient.java

public TaskDataList getAllTaskData(String queryUrl) {
    HttpMethod method = getMethod(queryUrl(queryUrl));
    try {/*from w w w .j a  va 2s.  co m*/
        switch (executeMethod(method)) {
        case HttpStatus.SC_OK:
            return new TaskDataList((List) parse(getResponse(method)));
        case HttpStatus.SC_UNAUTHORIZED:
            throw new MingleAuthenticationException(
                    "Could not authenticate user. Check username and password.");
        }
        return new TaskDataList();
    } finally {
        if (method != null)
            method.releaseConnection();
    }
}

From source file:com.cubeia.backoffice.users.client.UserServiceClientHTTP.java

@Override
public AuthenticationResponse authenticate(Long operatorId, String username, String password) {
    PostMethod method = new PostMethod(baseUrl + AUTHENTICATE);
    AuthenticationRequest request = new AuthenticationRequest();
    request.setOperatorId(operatorId);// www. j  av  a2  s . co m
    request.setUserName(username);
    request.setPassword(password);

    try {
        String data = serialize(request);
        method.setRequestEntity(new StringRequestEntity(data, "application/json", "UTF-8"));

        // Execute the HTTP Call
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return null;
        }
        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            AuthenticationResponse response = new AuthenticationResponse();
            response.setAuthenticated(false);
            return response;

        } else if (statusCode == HttpStatus.SC_OK) {
            InputStream body = method.getResponseBodyAsStream();
            return parseJson(body, AuthenticationResponse.class);

        } else {
            throw new RuntimeException("Failed to authenticate user, RESPONSE CODE: " + statusCode);
        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.thoughtworks.twist.mingle.core.MingleClient.java

public TaskData getTaskData(String taskId) {
    HttpMethod method = getMethod(cardUrl(taskId));
    try {// w  w  w.  j  a va2 s  .  c  o m
        switch (executeMethod(method)) {
        case HttpStatus.SC_OK:
            return (TaskData) parse(getResponse(method));
        case HttpStatus.SC_UNAUTHORIZED:
            throw new MingleAuthenticationException(
                    "Could not authenticate user. Check username and password.");
        default:
            throw new RuntimeException("Got an http response that I do not know how to handle");
        }
    } finally {
        if (method != null)
            method.releaseConnection();
    }
}

From source file:com.motorola.studio.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);

    StudioLogger.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;/*  ww w .  j a  v a  2  s . co  m*/
    if (proxyService.isProxiesEnabled() || proxyService.isSystemProxiesEnabled()) {
        Authenticator.setDefault(new NetAuthenticator());
        if (url.startsWith("https")) {
            proxyData = proxyService.getProxyData(IProxyData.HTTPS_PROXY_TYPE);
            StudioLogger.debug(HttpUtils.class, "Using https proxy"); //$NON-NLS-1$
        } else if (url.startsWith("http")) {
            proxyData = proxyService.getProxyData(IProxyData.HTTP_PROXY_TYPE);
            StudioLogger.debug(HttpUtils.class, "Using http proxy"); //$NON-NLS-1$
        } else {
            StudioLogger.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 {
        StudioLogger.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) {
                StudioLogger.debug(HttpUtils.class, "Client requested authentication; retrieving credentials"); //$NON-NLS-1$

                credentials = authenticationRealmCache.get(authenticationRealm);

                if (credentials == null) {
                    StudioLogger.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) {
                StudioLogger.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);
                }

                StudioLogger.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:com.kagilum.plugins.icescrum.IceScrumSession.java

private void checkServerStatus(int code) throws IOException {
    switch (code) {
    case HttpStatus.SC_SERVICE_UNAVAILABLE:
        throw new IOException(Messages.IceScrumSession_icescrum_http_unavailable());
    case HttpStatus.SC_UNAUTHORIZED:
        throw new IOException(Messages.IceScrumSession_icescrum_http_unauthorized());
    case HttpStatus.SC_FORBIDDEN:
        throw new IOException(Messages.IceScrumSession_icescrum_http_forbidden());
    case HttpStatus.SC_NOT_FOUND:
        throw new IOException(Messages.IceScrumSession_icescrum_http_notfound());
    default:/*ww w.  ja v a2  s. c o m*/
        throw new IOException(
                Messages.IceScrumSession_icescrum_http_error() + " (" + HttpStatus.getStatusText(code) + ")");
    }
}

From source file:com.cubeia.backoffice.users.client.UserServiceClientHTTP.java

@Override
public AuthenticationResponse authenticateSessionToken(String sessionToken) {
    PostMethod method = new PostMethod(baseUrl + AUTHENTICATE_TOKEN);
    AuthenticationTokenRequest request = new AuthenticationTokenRequest();
    request.setSessionToken(sessionToken);

    try {/* w w w. ja v  a  2  s.c  om*/
        String data = serialize(request);
        method.setRequestEntity(new StringRequestEntity(data, "application/json", "UTF-8"));

        // Execute the HTTP Call
        int statusCode = getClient().executeMethod(method);

        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            AuthenticationResponse response = new AuthenticationResponse();
            response.setAuthenticated(false);
            return response;

        } else if (statusCode == HttpStatus.SC_OK) {
            InputStream body = method.getResponseBodyAsStream();
            return parseJson(body, AuthenticationResponse.class);

        } else {
            throw new RuntimeException("Failed to authenticate user, RESPONSE CODE: " + statusCode);
        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.dtolabs.client.utils.BaseFormAuthenticator.java

/**
 * Authenticate the client http state so that the colony requests can be made.
 *
 * @param baseURL URL requested for colony
 * @param client  HttpClient instance/*from   ww  w  . j  a v  a 2 s  .  c o m*/
 *
 * @return true if authentication succeeded.
 *
 * @throws com.dtolabs.client.utils.HttpClientException
 *
 */
public boolean authenticate(final URL baseURL, final HttpClient client) throws HttpClientException {
    final HttpState state = client.getState();
    if (hasSessionCookie(baseURL, state, basePath)) {
        return true;
    }
    final byte[] buffer = new byte[1024];

    boolean doPostLogin = false;
    boolean isLoginFormContent = false;
    logger.debug("No session found, must login...");
    try {
        final URL newUrl = new URL(baseURL.getProtocol(), baseURL.getHost(), baseURL.getPort(),
                basePath + getInitialPath());

        //load welcome page, which should forward to form based logon page.
        final GetMethod get = new GetMethod(newUrl.toExternalForm());
        get.setDoAuthentication(false);
        get.setFollowRedirects(false);
        logger.debug("Requesting: " + newUrl);
        int res = client.executeMethod(get);
        logger.debug("Result is: " + res);

        /*
          Tomcat container auth behaves differently than Jetty.  Tomcat will respond 200 OK and include the login form
          when auth is required, as well as on auth failure, it will also require complete GET of original URL after
          successful auth.
          Jetty will redirect to login page when auth is required, and will redirect to error page on failure.
         */

        String body = get.getResponseBodyAsString();
        if (null != body && body.contains(J_SECURITY_CHECK) && body.contains(JAVA_USER_PARAM)
                && body.contains(JAVA_PASS_PARAM)) {
            isLoginFormContent = true;
        }
        get.releaseConnection();

        if ((res == HttpStatus.SC_UNAUTHORIZED)) {
            if (get.getResponseHeader("WWW-Authenticate") != null
                    && get.getResponseHeader("WWW-Authenticate").getValue().matches("^Basic.*")) {
                logger.warn("Form-based login received UNAUTHORIZED, trying to use Basic authentication");
                final BasicAuthenticator auth = new BasicAuthenticator(username, password);
                return auth.authenticate(baseURL, client);
            } else {
                throw new HttpClientException(
                        "Form-based login received UNAUTHORIZED, but didn't recognize it as Basic authentication: unable to get a session");
            }

        }
        //should now have the proper session cookie
        if (!hasSessionCookie(baseURL, state, basePath)) {
            throw new HttpClientException("Unable to get a session from URL : " + newUrl);
        }
        if (res == HttpStatus.SC_OK && isLoginFormContent) {
            doPostLogin = true;
        } else if ((res == HttpStatus.SC_MOVED_TEMPORARILY) || (res == HttpStatus.SC_MOVED_PERMANENTLY)
                || (res == HttpStatus.SC_SEE_OTHER) || (res == HttpStatus.SC_TEMPORARY_REDIRECT)) {
            Header locHeader = get.getResponseHeader("Location");
            if (locHeader == null) {
                throw new HttpClientException("Redirect with no Location header, request URL: " + newUrl);
            }
            String location = locHeader.getValue();
            if (!isValidLoginRedirect(get)) {
                //unexpected response
                throw new HttpClientException("Unexpected redirection when getting session: " + location);
            }
            logger.debug("Follow redirect: " + res + ": " + location);

            final GetMethod redir = new GetMethod(location);
            redir.setFollowRedirects(true);
            res = client.executeMethod(redir);
            InputStream ins = redir.getResponseBodyAsStream();
            while (ins.available() > 0) {
                //read and discard response body
                ins.read(buffer);
            }
            redir.releaseConnection();

            if (res != HttpStatus.SC_OK) {
                throw new HttpClientException("Login page status was not OK: " + res);
            }
            logger.debug("Result: " + res);

            doPostLogin = true;
        } else if (res != HttpStatus.SC_OK) {
            //if request to welcome page was OK, we figure that the session is already set
            throw new HttpClientException("Request to welcome page returned error: " + res + ": " + get);
        }
        if (doPostLogin) {
            //now post login
            final URL loginUrl = new URL(baseURL.getProtocol(), baseURL.getHost(), baseURL.getPort(),
                    basePath + JAVA_AUTH_PATH);

            final PostMethod login = new PostMethod(loginUrl.toExternalForm());
            login.setRequestBody(new NameValuePair[] { new NameValuePair(JAVA_USER_PARAM, getUsername()),
                    new NameValuePair(JAVA_PASS_PARAM, getPassword()) });

            login.setFollowRedirects(false);
            logger.debug("Post login info to URL: " + loginUrl);

            res = client.executeMethod(login);

            final InputStream ins = login.getResponseBodyAsStream();
            while (ins.available() > 0) {
                //read and discard response body
                ins.read(buffer);
            }
            login.releaseConnection();

            Header locHeader = login.getResponseHeader("Location");
            String location = null != locHeader ? locHeader.getValue() : null;
            if (isLoginError(login)) {
                logger.error("Form-based auth failed");
                return false;
            } else if (null != location && !location.equals(newUrl.toExternalForm())) {

                logger.warn("Form-based auth succeeded, but last URL was unexpected");
            }
            if (isFollowLoginRedirect()
                    && ((res == HttpStatus.SC_MOVED_TEMPORARILY) || (res == HttpStatus.SC_MOVED_PERMANENTLY)
                            || (res == HttpStatus.SC_SEE_OTHER) || (res == HttpStatus.SC_TEMPORARY_REDIRECT))) {

                if (location == null) {
                    throw new HttpClientException("Redirect with no Location header, request URL: " + newUrl);
                }
                final GetMethod get2 = new GetMethod(location);
                //                    logger.debug("Result: " + res + ": " + location + ", following redirect");
                res = client.executeMethod(get2);
            } else if (res != HttpStatus.SC_OK) {
                throw new HttpClientException(
                        "Login didn't seem to work: " + res + ": " + login.getResponseBodyAsString());
            }
            logger.debug("Result: " + res);
        }
    } catch (MalformedURLException e) {
        throw new HttpClientException("Bad URL", e);
    } catch (HttpException e) {
        throw new HttpClientException("HTTP Error: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new HttpClientException(
                "Error occurred while trying to authenticate to server: " + e.getMessage(), e);
    }

    return true;
}

From source file:com.thoughtworks.go.server.materials.MaterialUpdateServiceTest.java

@Test
public void shouldReturn401WhenUserIsNotAnAdmin_WhenInvokingPostCommitHookMaterialUpdate() {
    when(goConfigService.isUserAdmin(username)).thenReturn(false);
    service.notifyMaterialsForUpdate(username, new HashMap(), result);
    assertThat(result.isSuccessful(), is(false));
    assertThat(result.httpCode(), is(HttpStatus.SC_UNAUTHORIZED));
    assertThat(result.hasMessage(), is(true));
    verify(goConfigService).isUserAdmin(username);
}

From source file:com.zimbra.qa.unittest.TestCollectConfigServletsAccess.java

/**
 * Verify that delegated admin canNOT access servlet at /service/collectldapconfig/
 * @throws Exception//from  www.  ja v a2 s. co m
 */
@Test
public void testLDAPConfigDelegatedAdmin() throws Exception {
    ZAuthToken at = TestUtil.getAdminSoapTransport(TEST_ADMIN_NAME, PASSWORD).getAuthToken();
    URI servletURI = new URI(getLDAPConfigServletUrl());
    HttpState initialState = HttpClientUtil.newHttpState(at, servletURI.getHost(), true);
    HttpClient restClient = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    restClient.setState(initialState);
    restClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    GetMethod get = new GetMethod(servletURI.toString());
    int statusCode = HttpClientUtil.executeMethod(restClient, get);
    assertEquals("This request should NOT succeed. Getting status code " + statusCode,
            HttpStatus.SC_UNAUTHORIZED, statusCode);
}

From source file:com.thoughtworks.go.server.service.PipelinePauseServiceTest.java

@Test
public void shouldPopulateHttpResult401WhenPipelineIsNotAuthorizedForPausing() throws Exception {
    setUpValidPipelineWithInvalidAuth();

    HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();

    pipelinePauseService.pause(VALID_PIPELINE, "cause", INVALID_USER, result);

    assertThat(result.isSuccessful(), is(false));
    assertThat(result.httpCode(), is(HttpStatus.SC_UNAUTHORIZED));
    verify(pipelineDao, never()).pause(VALID_PIPELINE, "cause", "admin");
}