Example usage for org.apache.http.client AuthCache put

List of usage examples for org.apache.http.client AuthCache put

Introduction

In this page you can find the example usage for org.apache.http.client AuthCache put.

Prototype

void put(HttpHost host, AuthScheme authScheme);

Source Link

Usage

From source file:org.apache.manifoldcf.authorities.authorities.jira.JiraSession.java

private void getRest(String rightside, JiraJSONResponse response) throws IOException, ResponseException {

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local
    // auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(host, basicAuth);

    // Add AuthCache to the execution context
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);

    final HttpRequestBase method = new HttpGet(host.toURI() + path + rightside);
    method.addHeader("Accept", "application/json");

    try {//from   w  w  w .  j a v  a 2s.c  o  m
        HttpResponse httpResponse = httpClient.execute(method, localContext);
        int resultCode = httpResponse.getStatusLine().getStatusCode();
        if (resultCode != 200)
            throw new ResponseException(
                    "Unexpected result code " + resultCode + ": " + convertToString(httpResponse));
        Object jo = convertToJSON(httpResponse);
        response.acceptJSONObject(jo);
    } finally {
        method.abort();
    }
}

From source file:com.cloudbees.tomcat.valves.PrivateAppValveIntegratedTest.java

@Test
public void pre_emptive_basic_authentication_scenario() throws IOException {
    System.out.println("pre_emptive_basic_authentication_scenario");

    privateAppValve.setAuthenticationEntryPoint(PrivateAppValve.AuthenticationEntryPoint.BASIC_AUTH);

    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(httpHost.getHostName(), httpHost.getPort()),
            new UsernamePasswordCredentials(accessKey, secretKey));

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(httpHost, basicAuth);

    // Add AuthCache to the execution context
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpGet httpget = new HttpGet("/");

    for (int i = 0; i < 3; i++) {
        HttpResponse response = httpClient.execute(httpHost, httpget, localcontext);
        assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpServletResponse.SC_OK));
        assertThat(response.containsHeader("x-response"), is(true));

        dumpHttpResponse(response);/*from   www.  jav a 2 s .c  om*/

        EntityUtils.consumeQuietly(response.getEntity());
    }

}

From source file:org.elasticsearch.xpack.watcher.common.http.HttpClient.java

public HttpResponse execute(HttpRequest request) throws IOException {
    URI uri = createURI(request);

    HttpRequestBase internalRequest;/*from w w  w.ja v  a 2s . c  om*/
    if (request.method == HttpMethod.HEAD) {
        internalRequest = new HttpHead(uri);
    } else {
        HttpMethodWithEntity methodWithEntity = new HttpMethodWithEntity(uri, request.method.name());
        if (request.hasBody()) {
            ByteArrayEntity entity = new ByteArrayEntity(request.body.getBytes(StandardCharsets.UTF_8));
            String contentType = request.headers().get(HttpHeaders.CONTENT_TYPE);
            if (Strings.hasLength(contentType)) {
                entity.setContentType(contentType);
            } else {
                entity.setContentType(ContentType.TEXT_PLAIN.toString());
            }
            methodWithEntity.setEntity(entity);
        }
        internalRequest = methodWithEntity;
    }
    internalRequest.setHeader(HttpHeaders.ACCEPT_CHARSET, StandardCharsets.UTF_8.name());

    // headers
    if (request.headers().isEmpty() == false) {
        for (Map.Entry<String, String> entry : request.headers.entrySet()) {
            internalRequest.setHeader(entry.getKey(), entry.getValue());
        }
    }

    // BWC - hack for input requests made to elasticsearch that do not provide the right content-type header!
    if (request.hasBody() && internalRequest.containsHeader("Content-Type") == false) {
        XContentType xContentType = XContentFactory.xContentType(request.body());
        if (xContentType != null) {
            internalRequest.setHeader("Content-Type", xContentType.mediaType());
        }
    }

    RequestConfig.Builder config = RequestConfig.custom();
    setProxy(config, request, settingsProxy);
    HttpClientContext localContext = HttpClientContext.create();
    // auth
    if (request.auth() != null) {
        ApplicableHttpAuth applicableAuth = httpAuthRegistry.createApplicable(request.auth);
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        applicableAuth.apply(credentialsProvider, new AuthScope(request.host, request.port));
        localContext.setCredentialsProvider(credentialsProvider);

        // preemptive auth, no need to wait for a 401 first
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(new HttpHost(request.host, request.port, request.scheme.scheme()), basicAuth);
        localContext.setAuthCache(authCache);
    }

    // timeouts
    if (request.connectionTimeout() != null) {
        config.setConnectTimeout(Math.toIntExact(request.connectionTimeout.millis()));
    } else {
        config.setConnectTimeout(Math.toIntExact(defaultConnectionTimeout.millis()));
    }

    if (request.readTimeout() != null) {
        config.setSocketTimeout(Math.toIntExact(request.readTimeout.millis()));
        config.setConnectionRequestTimeout(Math.toIntExact(request.readTimeout.millis()));
    } else {
        config.setSocketTimeout(Math.toIntExact(defaultReadTimeout.millis()));
        config.setConnectionRequestTimeout(Math.toIntExact(defaultReadTimeout.millis()));
    }

    internalRequest.setConfig(config.build());

    try (CloseableHttpResponse response = SocketAccess
            .doPrivileged(() -> client.execute(internalRequest, localContext))) {
        // headers
        Header[] headers = response.getAllHeaders();
        Map<String, String[]> responseHeaders = new HashMap<>(headers.length);
        for (Header header : headers) {
            if (responseHeaders.containsKey(header.getName())) {
                String[] old = responseHeaders.get(header.getName());
                String[] values = new String[old.length + 1];

                System.arraycopy(old, 0, values, 0, old.length);
                values[values.length - 1] = header.getValue();

                responseHeaders.put(header.getName(), values);
            } else {
                responseHeaders.put(header.getName(), new String[] { header.getValue() });
            }
        }

        final byte[] body;
        // not every response has a content, i.e. 204
        if (response.getEntity() == null) {
            body = new byte[0];
        } else {
            try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                try (InputStream is = new SizeLimitInputStream(maxResponseSize,
                        response.getEntity().getContent())) {
                    Streams.copy(is, outputStream);
                }
                body = outputStream.toByteArray();
            }
        }
        return new HttpResponse(response.getStatusLine().getStatusCode(), body, responseHeaders);
    }
}

From source file:com.cloudbees.servlet.filters.PrivateAppFilterIntegratedTest.java

@Test
public void pre_emptive_basic_authentication_scenario() throws IOException {
    System.out.println("pre_emptive_basic_authentication_scenario");

    privateAppFilter.setAuthenticationEntryPoint(PrivateAppFilter.AuthenticationEntryPoint.BASIC_AUTH);

    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(httpHost.getHostName(), httpHost.getPort()),
            new UsernamePasswordCredentials(accessKey, secretKey));

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(httpHost, basicAuth);

    // Add AuthCache to the execution context
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpGet httpget = new HttpGet("/");

    for (int i = 0; i < 3; i++) {
        HttpResponse response = httpClient.execute(httpHost, httpget, localcontext);
        assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpServletResponse.SC_OK));
        assertThat(response.containsHeader("x-response"), is(true));

        dumpHttpResponse(response);/*from w w  w .ja v  a2  s . co  m*/

        EntityUtils.consumeQuietly(response.getEntity());
    }

}

From source file:com.sun.jersey.client.apache4.ApacheHttpClient4Handler.java

public ClientResponse handle(final ClientRequest cr) throws ClientHandlerException {

    final HttpUriRequest request = getUriHttpRequest(cr);

    writeOutBoundHeaders(cr.getHeaders(), request);

    try {/*from www  .  j  a va 2  s  .com*/
        HttpResponse response;

        if (preemptiveBasicAuth) {
            AuthCache authCache = new BasicAuthCache();
            BasicScheme basicScheme = new BasicScheme();
            authCache.put(getHost(request), basicScheme);
            BasicHttpContext localContext = new BasicHttpContext();
            localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);

            response = getHttpClient().execute(getHost(request), request, localContext);
        } else {
            response = getHttpClient().execute(getHost(request), request);
        }

        ClientResponse r = new ClientResponse(response.getStatusLine().getStatusCode(),
                getInBoundHeaders(response), new HttpClientResponseInputStream(response),
                getMessageBodyWorkers());
        if (!r.hasEntity()) {
            r.bufferEntity();
            r.close();
        }

        return r;
    } catch (Exception e) {
        throw new ClientHandlerException(e);
    }

}

From source file:org.apache.jena.atlas.web.auth.PreemptiveBasicAuthenticator.java

@Override
public void apply(AbstractHttpClient client, HttpContext httpContext, URI target) {
    this.authenticator.apply(client, httpContext, target);

    // Enable preemptive basic authentication
    // For nice layering we need to respect existing auth cache if present
    AuthCache authCache = (AuthCache) httpContext.getAttribute(ClientContext.AUTH_CACHE);
    if (authCache == null)
        authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme(this.isProxy ? ChallengeState.PROXY : ChallengeState.TARGET);
    // TODO It is possible that this overwrites existing cached credentials
    // so potentially not ideal.
    authCache.put(new HttpHost(target.getHost(), target.getPort()), basicAuth);
    httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
}

From source file:com.anaplan.client.transport.ApacheHttpProvider.java

/** {@inheritDoc} */
@Override/*w w w .j  ava 2 s.c  o m*/
public void setServiceCredentials(Credentials serviceCredentials) throws AnaplanAPITransportException {

    super.setServiceCredentials(serviceCredentials);

    if (getServiceLocation() != null) {
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicScheme = new BasicScheme();
        authCache.put(httpHost, basicScheme);
        httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    }
}

From source file:de.dtag.tlabs.cbclient.CBClient.java

public void performHO() {

    try {/*  www .jav a  2 s.c  o m*/
        System.out.println("Perform HO");
        HttpHost targetHost = new HttpHost(httpHostAddr, httpHostPort, "http");
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials("admin", "epc"));

        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);

        // Add AuthCache to the execution context
        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(credsProvider);

        HttpPost httpPost = new HttpPost(andsfResource);

        switch (newPolicy) {
        case NONE:
            break;

        case LTE:
            //Switch over to LTE
            sendingPolicy = toLTE;
            currentPolicy = accessModes.LTE;
            System.out.println("SWITCHING OVER TO LTE");
            break;

        case WIFI:
            //Switch over to WIFI
            sendingPolicy = toWiFi;
            currentPolicy = accessModes.WIFI;
            System.out.println("SWITCHING OVER TO WIFI");
            break;

        default:
            break;
        }

        StringEntity postEntity = new StringEntity(sendingPolicy, ContentType.APPLICATION_FORM_URLENCODED);

        httpPost.setEntity(postEntity);

        StringWriter writer = new StringWriter();

        System.out.println("httpPost: " + httpPost);

        CloseableHttpResponse response = httpClient.execute(targetHost, httpPost, context);
        try {
            HttpEntity entity = response.getEntity();
            System.out.println("Response: " + response.getStatusLine().toString());

            InputStream is = entity.getContent();
            IOUtils.copy(is, writer);
            String responseContent = writer.toString();

            if (responseContent.contains("Success")) {
                System.out.println("Response content: Success");
            } else {
                System.out.println("Response content: No Success found");
            }

        } finally {
            response.close();
        }
    } catch (IOException e) {
        System.out.println("IOException found");
        e.printStackTrace();
    } catch (IllegalStateException e) {
        System.out.println("Exception found");
        e.printStackTrace();
    }
}

From source file:edu.lternet.pasta.client.LoginClient.java

/**
 * Perform a PASTA login operation using the user's credentials. Because there
 * is not a formal PASTA login method, we will use a simple query for the Data
 * Package Manager service, which will perform the necessary user
 * authentication (this step should be replaced with a formal PASTA
 * "login service method").//from w w w  .  j  a  v  a  2 s.co  m
 * 
 * @param uid
 *          The user identifier.
 * @param password
 *          The user password.
 * 
 * @return The authentication token as a String object if the login is
 *         successful.
 */
private String login(String uid, String password) {

    String token = null;
    String username = PastaClient.composeDistinguishedName(uid);

    /*
     * The following set of code sets up Preemptive Authentication for the HTTP
     * CLIENT and is done so at the warning stated within the Apache
     * Http-Components Client tutorial here:
     * http://hc.apache.org/httpcomponents-
     * client-ga/tutorial/html/authentication.html#d5e1031
     */

    // Define host parameters
    HttpHost httpHost = new HttpHost(this.pastaHost, this.pastaPort, this.pastaProtocol);
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();

    // Define user authentication credentials that will be used with the host
    AuthScope authScope = new AuthScope(httpHost.getHostName(), httpHost.getPort());
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(authScope, credentials);

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();

    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(httpHost, basicAuth);

    // Add AuthCache to the execution context
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthCache(authCache);

    HttpGet httpGet = new HttpGet(this.LOGIN_URL);
    HttpResponse response = null;
    Header[] headers = null;
    Integer statusCode = null;

    try {

        response = httpClient.execute(httpHost, httpGet, context);
        headers = response.getAllHeaders();
        statusCode = (Integer) response.getStatusLine().getStatusCode();
        logger.info("STATUS: " + statusCode.toString());

    } catch (UnsupportedEncodingException e) {
        logger.error(e);
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        logger.error(e);
        e.printStackTrace();
    } catch (IOException e) {
        logger.error(e);
        e.printStackTrace();
    } finally {
        closeHttpClient(httpClient);
    }

    if (statusCode == HttpStatus.SC_OK) {

        String headerName = null;
        String headerValue = null;

        // Loop through all headers looking for the "Set-Cookie" header.
        for (int i = 0; i < headers.length; i++) {
            headerName = headers[i].getName();

            if (headerName.equals("Set-Cookie")) {
                headerValue = headers[i].getValue();
                token = this.getAuthToken(headerValue);
            }

        }

    }

    return token;
}