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.zimbra.qa.unittest.TestCookieReuse.java

/**
 * Verify that we canNOT RE-use the cookie for REST session if the session is valid
 *///  ww w .  jav  a 2  s . c om
@Test
public void testAutoEndSession() throws ServiceException, IOException {
    //establish legitimate connection
    TestUtil.setAccountAttr(USER_NAME, Provisioning.A_zimbraForceClearCookies, "TRUE");
    ZMailbox mbox = TestUtil.getZMailbox(USER_NAME);
    URI uri = mbox.getRestURI("Inbox?fmt=rss");
    HttpClient alice = mbox.getHttpClient(uri);

    //create evesdropper's connection
    HttpClient eve = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    Cookie[] cookies = alice.getState().getCookies();
    HttpState state = new HttpState();
    for (int i = 0; i < cookies.length; i++) {
        Cookie cookie = cookies[i];
        state.addCookie(new Cookie(uri.getHost(), cookie.getName(), cookie.getValue(), "/", null, false));
    }
    eve.setState(state);
    Account a = TestUtil.getAccount(USER_NAME);
    a.setForceClearCookies(true);

    EndSessionRequest esr = new EndSessionRequest();
    mbox.invokeJaxb(esr);
    GetMethod get = new GetMethod(uri.toString());
    int statusCode = HttpClientUtil.executeMethod(eve, get);
    Assert.assertEquals("This request should not succeed. Getting status code " + statusCode,
            HttpStatus.SC_UNAUTHORIZED, statusCode);
}

From source file:davmail.exchange.ExchangeSessionFactory.java

/**
 * Send a request to Exchange server to check current settings.
 *
 * @throws IOException if unable to access Exchange server
 *///from  ww  w. j  ava 2s.  c  o  m
public static void checkConfig() throws IOException {
    String url = Settings.getProperty("davmail.url");
    HttpClient httpClient = DavGatewayHttpClientFacade.getInstance(url);
    GetMethod testMethod = new GetMethod(url);
    try {
        // get webMail root url (will not follow redirects)
        int status = DavGatewayHttpClientFacade.executeTestMethod(httpClient, testMethod);
        ExchangeSession.LOGGER.debug("Test configuration status: " + status);
        if (status != HttpStatus.SC_OK && status != HttpStatus.SC_UNAUTHORIZED
                && !DavGatewayHttpClientFacade.isRedirect(status)) {
            throw new DavMailException("EXCEPTION_CONNECTION_FAILED", url, status);
        }
        // session opened, future failure will mean network down
        configChecked = true;
        // Reset so next time an problem occurs message will be sent once
        errorSent = false;
    } catch (Exception exc) {
        handleNetworkDown(exc);
    } finally {
        testMethod.releaseConnection();
    }

}

From source file:com.kodokux.github.api.GithubApiUtil.java

private static void checkStatusCode(@NotNull HttpMethod method) throws IOException {
    int code = method.getStatusCode();
    switch (code) {
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
    case HttpStatus.SC_ACCEPTED:
    case HttpStatus.SC_NO_CONTENT:
        return;//from  w  w w  .  ja  v a2 s  . c o m
    case HttpStatus.SC_BAD_REQUEST:
    case HttpStatus.SC_UNAUTHORIZED:
    case HttpStatus.SC_PAYMENT_REQUIRED:
    case HttpStatus.SC_FORBIDDEN:
        String message = getErrorMessage(method);
        if (message.contains("API rate limit exceeded")) {
            throw new GithubRateLimitExceededException(message);
        }
        throw new GithubAuthenticationException("Request response: " + message);
    default:
        throw new GithubStatusCodeException(code + ": " + getErrorMessage(method), code);
    }
}

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

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

    HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();

    pipelinePauseService.unpause(VALID_PIPELINE, INVALID_USER, result);

    assertThat(result.isSuccessful(), is(false));
    assertThat(result.httpCode(), is(HttpStatus.SC_UNAUTHORIZED));
    verify(pipelineDao, never()).unpause(VALID_PIPELINE);
}

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

/**
 * Verify that an HTTP client canNOT access servlet at /service/collectldapconfig/ without an auth token
 * @throws Exception/*from   w w w  . j a v a 2  s . c  o  m*/
 */
@Test
public void testLDAPConfigNoToken() throws Exception {
    URI servletURI = new URI(getLDAPConfigServletUrl());
    HttpClient restClient = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    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.hp.alm.ali.idea.cfg.AliConfigurable.java

public static ServerType getServerType(RestClient restClient, boolean loginLogout) throws AuthenticationFailed {
    try {/*w  w  w. j  av a 2s.  c o  m*/
        if (loginLogout) {
            restClient.login();
        }
        // check for at least ALM 11
        RestService.getForString(restClient, "defects?query={0}", EntityQuery.encode("{id[0]}"));

        try {
            InputStream is = restClient.getForStream("customization/extensions");
            return checkServerType(ProjectExtensionsList.create(is));
        } catch (HttpClientErrorException e) {
            if (e.getHttpStatus() == HttpStatus.SC_NOT_FOUND) {
                return checkServerTypeOldStyle(restClient);
            }
            throw e;
        }
    } catch (HttpClientErrorException e) {
        if (e.getHttpStatus() == HttpStatus.SC_UNAUTHORIZED) {
            throw new AuthenticationFailed();
        } else {
            throw new RuntimeException("Failed to connect to HP ALM: "
                    + handleGenericException(restClient, restClient.getDomain(), restClient.getProject()));
        }
    } catch (Exception e) {
        throw new RuntimeException("Failed to connect to HP ALM: "
                + handleGenericException(restClient, restClient.getDomain(), restClient.getProject()));
    } finally {
        if (loginLogout) {
            RestService.logout(restClient);
        }
    }
}

From source file:PublisherUtil.java

/**
 * Publishes a list of files and a datasource to the server with basic authentication to the server
 * //from ww w . jav  a  2 s. c  o m
 * @param publishURL
 *          The URL of the Pentaho server
 * @param publishPath
 *          The path in the solution to place the files
 * @param publishFiles
 *          Array of File objects to post to the server
 * @param dataSource
 *          The datasource to publish to the server
 * @param publishPassword
 *          The publishing password for the server
 * @param serverUserid
 *          The userid to authenticate to the server
 * @param serverPassword
 *          The password to authenticate with the server
 * @param overwrite
 *          Whether the server should overwrite the file if it exists already
 * @param mkdirs
 *          Whether the server should create any missing folders on the publish path
 * @return Server response as a string
* @throws Exception 
 */
public static String publish(final String publishURL, final String publishPath, final File publishFiles[],
        final String publishPassword, final String serverUserid, final String serverPassword,
        final boolean overwrite, final boolean mkdirs) throws Exception {
    int status = -1;
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); //$NON-NLS-1$ //$NON-NLS-2$
    System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true"); //$NON-NLS-1$ //$NON-NLS-2$
    System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire.header", "warn");//$NON-NLS-1$ //$NON-NLS-2$
    System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "warn");//$NON-NLS-1$ //$NON-NLS-2$

    String fullURL = null;
    try {
        fullURL = publishURL + "?publishPath=" + URLEncoder.encode(publishPath, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        fullURL = publishURL + "?publishPath=" + publishPath;
        System.out.println("Erro de publicao na classe publisher!" + e);
        // throw new Exception("Erro de publicao na classe publisher!" + e);
    }
    if (publishPassword == null) {
        throw new IllegalArgumentException("PUBLISHERUTIL.ERROR_0001_PUBLISH_PASSWORD_REQUIRED"); //$NON-NLS-1$
        // throw new IllegalArgumentException(Messages.getErrorString("PUBLISHERUTIL.ERROR_0001_PUBLISH_PASSWORD_REQUIRED")); //$NON-NLS-1$
    }

    fullURL += "&publishKey=" + PublisherUtil.getPasswordKey(publishPassword); //$NON-NLS-1$
    fullURL += "&overwrite=" + overwrite; //$NON-NLS-1$
    fullURL += "&mkdirs=" + mkdirs; //$NON-NLS-1$

    PostMethod filePost = new PostMethod(fullURL);

    Part[] parts = new Part[publishFiles.length];
    for (int i = 0; i < publishFiles.length; i++) {
        try {
            File file = publishFiles[i];
            FileInputStream in = new FileInputStream(file);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            IOUtils.copy(in, out);
            String reportNameEncoded = (URLEncoder.encode(file.getName(), "UTF-8"));
            ByteArrayPartSource source = new ByteArrayPartSource(reportNameEncoded, out.toByteArray());
            parts[i] = new FilePart(reportNameEncoded, source, FilePart.DEFAULT_CONTENT_TYPE, "UTF-8");
        } catch (Exception e) {
            PublisherUtil.logger.error(null, e);
            throw new Exception("Erro de publicao na classe publisher!" + e);
        }
    }

    filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
    HttpClient client = new HttpClient();

    try {
        if ((serverUserid != null) && (serverUserid.length() > 0) && (serverPassword != null)
                && (serverPassword.length() > 0)) {
            Credentials creds = new UsernamePasswordCredentials(serverUserid, serverPassword);
            client.getState().setCredentials(AuthScope.ANY, creds);
            client.getParams().setAuthenticationPreemptive(true);
        }
        status = client.executeMethod(filePost);

        if (status == HttpStatus.SC_OK) {
            String postResult = filePost.getResponseBodyAsString();

            if (postResult != null) {
                try {
                    return postResult.trim(); // +" - "+Integer.parseInt(postResult.trim());
                } catch (NumberFormatException e) {
                    PublisherUtil.logger.error(null, e);
                    // throw new Exception("Erro de publicao na classe publisher!" + e + " " +PublisherUtil.FILE_ADD_INVALID_USER_CREDENTIALS);
                    return "" + PublisherUtil.FILE_ADD_INVALID_USER_CREDENTIALS;
                }
            }
        } else if (status == HttpStatus.SC_UNAUTHORIZED) {
            return "" + PublisherUtil.FILE_ADD_INVALID_USER_CREDENTIALS;
        }
    } catch (HttpException e) {
        PublisherUtil.logger.error(null, e);
        // throw new Exception("Erro de publicao na classe publisher!" + e );
    } catch (IOException e) {
        PublisherUtil.logger.error(null, e);
        // throw new Exception("Erro de publicao na classe publisher!" + e );
    }
    // return Messages.getString("REPOSITORYFILEPUBLISHER.USER_PUBLISHER_FAILED"); //$NON-NLS-1$
    return "" + PublisherUtil.FILE_ADD_FAILED;
}

From source file:davmail.exchange.ews.EwsExchangeSession.java

/**
 * Check endpoint url.//from   w ww  . j a va  2s  . co m
 *
 * @param endPointUrl endpoint url
 * @throws IOException on error
 */
protected void checkEndPointUrl(String endPointUrl) throws IOException {
    HttpMethod getMethod = new GetMethod(endPointUrl);
    getMethod.setFollowRedirects(false);
    try {
        int status = DavGatewayHttpClientFacade.executeNoRedirect(httpClient, getMethod);
        if (status == HttpStatus.SC_UNAUTHORIZED) {
            throw new DavMailAuthenticationException("EXCEPTION_AUTHENTICATION_FAILED");
        } else if (status != HttpStatus.SC_MOVED_TEMPORARILY) {
            throw DavGatewayHttpClientFacade.buildHttpException(getMethod);
        }
        // check Location
        Header locationHeader = getMethod.getResponseHeader("Location");
        if (locationHeader == null || !"/ews/services.wsdl".equalsIgnoreCase(locationHeader.getValue())) {
            throw new IOException("Ews endpoint not available at " + getMethod.getURI().toString());
        }
    } finally {
        getMethod.releaseConnection();
    }
}

From source file:com.hp.alm.ali.idea.content.settings.SettingsPanel.java

private void checkConnection(String location, String domain, String project, String username, String password)
        throws AuthenticationFailed {
    RestClient restClient = RestService.createRestClient(location, domain, project, username, password,
            RestClient.SessionStrategy.AUTO_LOGIN);
    try {/*  w  ww. j  a va2 s.co  m*/
        restClient.getForString("defects?query={0}", EntityQuery.encode("{id[0]}"));
        RestService.logout(restClient);
    } catch (HttpClientErrorException e) {
        if (e.getHttpStatus() == HttpStatus.SC_UNAUTHORIZED) {
            throw new AuthenticationFailed();
        } else {
            throw new RuntimeException("Failed to connect to HP ALM");
        }
    } catch (Exception e) {
        throw new RuntimeException("Failed to connect to HP ALM");
    }
}

From source file:com.twinsoft.convertigo.engine.util.WsReference.java

private static void tryAuthentication(RemoteFileReference wsReference) throws Exception {
    URL urlToConnect = wsReference.getUrl();
    String wsdlUrl = wsReference.getUrlpath();
    String username = wsReference.getAuthUser();
    String password = wsReference.getAuthPassword();

    HttpClient client = new HttpClient();

    client.getState().setCredentials(new AuthScope(urlToConnect.getHost(), urlToConnect.getPort()),
            new UsernamePasswordCredentials(username, password));

    GetMethod get = new GetMethod(wsdlUrl);
    get.setDoAuthentication(true);/*w  ww.j  a  va 2  s.  c  om*/

    int statuscode = client.executeMethod(get);

    if (statuscode == HttpStatus.SC_UNAUTHORIZED) {
        throw new Exception(HttpStatus.SC_UNAUTHORIZED + " - Unauthorized connection!");
    }
}