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:com.adobe.aem.demo.communities.Loader.java

private static String doGet(String hostname, String port, String url, String user, String password,
        List<NameValuePair> params) {

    String rawResponse = null;// w ww .ja va2 s.  c  o m

    try {

        HttpHost target = new HttpHost(hostname, Integer.parseInt(port), "http");
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
                new UsernamePasswordCredentials(user, password));
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
                .build();

        try {

            // Adding the Basic Authentication data to the context for this command
            AuthCache authCache = new BasicAuthCache();
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(target, basicAuth);
            HttpClientContext localContext = HttpClientContext.create();
            localContext.setAuthCache(authCache);

            // Composing the root URL for all subsequent requests
            URIBuilder uribuilder = new URIBuilder();
            uribuilder.setScheme("http").setHost(hostname).setPort(Integer.parseInt(port)).setPath(url);

            // Adding the params
            if (params != null)
                for (NameValuePair nvp : params) {
                    uribuilder.setParameter(nvp.getName(), nvp.getValue());
                }

            URI uri = uribuilder.build();
            logger.debug("URI built as " + uri.toString());
            HttpGet httpget = new HttpGet(uri);
            CloseableHttpResponse response = httpClient.execute(httpget, localContext);
            try {
                rawResponse = EntityUtils.toString(response.getEntity(), "UTF-8");
            } catch (Exception ex) {
                logger.error(ex.getMessage());
            } finally {
                response.close();
            }

        } catch (Exception ex) {
            logger.error(ex.getMessage());
        } finally {
            httpClient.close();
        }

    } catch (IOException e) {

        e.printStackTrace();
    }

    return rawResponse;

}

From source file:com.rabbitmq.http.client.Client.java

private HttpComponentsClientHttpRequestFactory getRequestFactory(final URL url, final String username,
        final String password, final SSLConnectionSocketFactory sslConnectionSocketFactory,
        final SSLContext sslContext) throws MalformedURLException {
    String theUser = username;//  w  ww .  ja  va2s. c  o  m
    String thePassword = password;
    String userInfo = url.getUserInfo();
    if (userInfo != null && theUser == null) {
        String[] userParts = userInfo.split(":");
        if (userParts.length > 0) {
            theUser = userParts[0];
        }
        if (userParts.length > 1) {
            thePassword = userParts[1];
        }
    }
    final HttpClientBuilder bldr = HttpClientBuilder.create()
            .setDefaultCredentialsProvider(getCredentialsProvider(url, theUser, thePassword));
    bldr.setDefaultHeaders(Arrays.asList(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json")));
    if (sslConnectionSocketFactory != null) {
        bldr.setSSLSocketFactory(sslConnectionSocketFactory);
    }
    if (sslContext != null) {
        bldr.setSslcontext(sslContext);
    }

    HttpClient httpClient = bldr.build();

    // RabbitMQ HTTP API currently does not support challenge/response for PUT methods.
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicScheme = new BasicScheme();
    authCache.put(new HttpHost(rootUri.getHost(), rootUri.getPort(), rootUri.getScheme()), basicScheme);
    final HttpClientContext ctx = HttpClientContext.create();
    ctx.setAuthCache(authCache);
    return new HttpComponentsClientHttpRequestFactory(httpClient) {
        @Override
        protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
            return ctx;
        }
    };
}

From source file:org.glassfish.jersey.apache.connector.ApacheConnector.java

@Override
public ClientResponse apply(final ClientRequest clientRequest) throws ProcessingException {
    final HttpUriRequest request = getUriHttpRequest(clientRequest);
    final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(clientRequest.getHeaders(), request);

    try {/*from w w  w. jav a 2s  .com*/
        final CloseableHttpResponse response;
        final HttpClientContext context = HttpClientContext.create();
        if (preemptiveBasicAuth) {
            final AuthCache authCache = new BasicAuthCache();
            final BasicScheme basicScheme = new BasicScheme();
            authCache.put(getHost(request), basicScheme);
            context.setAuthCache(authCache);
        }
        response = client.execute(getHost(request), request, context);
        HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, clientRequest.getHeaders(),
                this.getClass().getName());

        final Response.StatusType status = response.getStatusLine().getReasonPhrase() == null
                ? Statuses.from(response.getStatusLine().getStatusCode())
                : Statuses.from(response.getStatusLine().getStatusCode(),
                        response.getStatusLine().getReasonPhrase());

        final ClientResponse responseContext = new ClientResponse(status, clientRequest);
        final List<URI> redirectLocations = context.getRedirectLocations();
        if (redirectLocations != null && !redirectLocations.isEmpty()) {
            responseContext.setResolvedRequestUri(redirectLocations.get(redirectLocations.size() - 1));
        }

        final Header[] respHeaders = response.getAllHeaders();
        final MultivaluedMap<String, String> headers = responseContext.getHeaders();
        for (final Header header : respHeaders) {
            final String headerName = header.getName();
            List<String> list = headers.get(headerName);
            if (list == null) {
                list = new ArrayList<>();
            }
            list.add(header.getValue());
            headers.put(headerName, list);
        }

        final HttpEntity entity = response.getEntity();

        if (entity != null) {
            if (headers.get(HttpHeaders.CONTENT_LENGTH) == null) {
                headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(entity.getContentLength()));
            }

            final Header contentEncoding = entity.getContentEncoding();
            if (headers.get(HttpHeaders.CONTENT_ENCODING) == null && contentEncoding != null) {
                headers.add(HttpHeaders.CONTENT_ENCODING, contentEncoding.getValue());
            }
        }

        try {
            responseContext.setEntityStream(new HttpClientResponseInputStream(getInputStream(response)));
        } catch (final IOException e) {
            LOGGER.log(Level.SEVERE, null, e);
        }

        return responseContext;
    } catch (final Exception e) {
        throw new ProcessingException(e);
    }
}

From source file:com.github.dockerjava.jaxrs.connector.ApacheConnector.java

@Override
public ClientResponse apply(final ClientRequest clientRequest) throws ProcessingException {
    final HttpUriRequest request = getUriHttpRequest(clientRequest);
    final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(clientRequest.getHeaders(), request);

    try {/*w w w .j a  v  a 2  s  .  c o  m*/
        final CloseableHttpResponse response;
        final HttpClientContext context = HttpClientContext.create();
        if (preemptiveBasicAuth) {
            final AuthCache authCache = new BasicAuthCache();
            final BasicScheme basicScheme = new BasicScheme();
            authCache.put(getHost(request), basicScheme);
            context.setAuthCache(authCache);
        }
        response = client.execute(getHost(request), request, context);
        HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, clientRequest.getHeaders(),
                this.getClass().getName());

        final Response.StatusType status = response.getStatusLine().getReasonPhrase() == null
                ? Statuses.from(response.getStatusLine().getStatusCode())
                : Statuses.from(response.getStatusLine().getStatusCode(),
                        response.getStatusLine().getReasonPhrase());

        final ClientResponse responseContext = new ApacheConnectorClientResponse(status, clientRequest,
                response);
        final List<URI> redirectLocations = context.getRedirectLocations();
        if (redirectLocations != null && !redirectLocations.isEmpty()) {
            responseContext.setResolvedRequestUri(redirectLocations.get(redirectLocations.size() - 1));
        }

        final Header[] respHeaders = response.getAllHeaders();
        final MultivaluedMap<String, String> headers = responseContext.getHeaders();
        for (final Header header : respHeaders) {
            final String headerName = header.getName();
            List<String> list = headers.get(headerName);
            if (list == null) {
                list = new ArrayList<String>();
            }
            list.add(header.getValue());
            headers.put(headerName, list);
        }

        final HttpEntity entity = response.getEntity();

        if (entity != null) {
            if (headers.get(HttpHeaders.CONTENT_LENGTH) == null) {
                headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(entity.getContentLength()));
            }

            final Header contentEncoding = entity.getContentEncoding();
            if (headers.get(HttpHeaders.CONTENT_ENCODING) == null && contentEncoding != null) {
                headers.add(HttpHeaders.CONTENT_ENCODING, contentEncoding.getValue());
            }
        }

        try {
            responseContext.setEntityStream(new HttpClientResponseInputStream(response));
        } catch (final IOException e) {
            LOGGER.log(Level.SEVERE, null, e);
        }

        return responseContext;
    } catch (final Exception e) {
        throw new ProcessingException(e);
    }
}

From source file:com.adobe.aem.demo.communities.Loader.java

private static String doPost(String hostname, String port, String url, String user, String password,
        HttpEntity entity, String lookup, String referer) {

    String jsonElement = null;//from   ww  w  .ja  v a  2s  .c  o m

    try {

        HttpHost target = new HttpHost(hostname, Integer.parseInt(port), "http");
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
                new UsernamePasswordCredentials(user, password));
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
                .build();

        try {

            // Adding the Basic Authentication data to the context for this command
            AuthCache authCache = new BasicAuthCache();
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(target, basicAuth);
            HttpClientContext localContext = HttpClientContext.create();
            localContext.setAuthCache(authCache);

            // Composing the root URL for all subsequent requests
            String postUrl = "http://" + hostname + ":" + port + url;
            logger.debug("Posting request as " + user + " with password " + password + " to " + postUrl);

            // Preparing a standard POST HTTP command
            HttpPost request = new HttpPost(postUrl);
            request.setEntity(entity);
            if (!entity.getContentType().toString().contains("multipart")) {
                request.addHeader("content-type", "application/x-www-form-urlencoded");
            }
            request.addHeader("Accept", "application/json, text/javascript, */*; q=0.01");
            request.addHeader("Origin", postUrl);
            if (referer != null) {
                logger.debug("Referer header added to request: " + referer);
                request.addHeader("Referer", referer);
            }

            // Sending the HTTP POST command
            CloseableHttpResponse response = httpClient.execute(target, request, localContext);
            try {
                String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
                logger.debug("Got POST response:" + responseString);
                if (lookup != null) {
                    logger.debug("JSON lookup value: " + lookup);
                    int separatorIndex = lookup.indexOf("/");
                    if (separatorIndex > 0) {

                        // Grabbing element in a nested element
                        Object object = new JSONObject(responseString).get(lookup.substring(0, separatorIndex));
                        if (object != null) {

                            if (object instanceof JSONArray) {

                                logger.debug("JSON object is a JSONArray");
                                JSONArray jsonArray = (JSONArray) object;
                                if (jsonArray.length() == 1) {
                                    JSONObject jsonObject = jsonArray.getJSONObject(0);
                                    jsonElement = jsonObject.getString(lookup.substring(1 + separatorIndex));
                                    logger.debug("JSON value (jsonArray) returned is " + jsonElement);
                                }

                            } else if (object instanceof JSONObject) {

                                logger.debug("JSON object is a JSONObject");
                                JSONObject jsonobject = (JSONObject) object;
                                jsonElement = jsonobject.getString(lookup.substring(1 + separatorIndex));
                                logger.debug("JSON value (jsonObject) returned is " + jsonElement);

                            }
                        }

                    } else {
                        // Grabbing element at the top of the JSON response
                        jsonElement = new JSONObject(responseString).getString(lookup);
                        logger.debug("JSON (top) value returned is " + jsonElement);

                    }
                }

            } catch (Exception ex) {
                logger.error(ex.getMessage());
            } finally {
                response.close();
            }

        } catch (Exception ex) {
            logger.error(ex.getMessage());
        } finally {
            httpClient.close();
        }

    } catch (IOException e) {
        logger.error(e.getMessage());
    }

    return jsonElement;

}

From source file:eu.europa.ec.markt.dss.validation102853.https.CommonDataLoader.java

protected HttpResponse getHttpResponse(final HttpUriRequest httpRequest, final URI uri) throws DSSException {

    final HttpClient client = getHttpClient(uri);

    final String host = uri.getHost();
    final int port = uri.getPort();
    final String scheme = uri.getScheme();
    final HttpHost targetHost = new HttpHost(host, port, scheme);

    // 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 localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);

    try {/*  w w  w  .  j  a  va 2 s. c  o  m*/
        final HttpResponse response = client.execute(targetHost, httpRequest, localContext);
        return response;
    } catch (IOException e) {
        throw new DSSException(e);
    }
}

From source file:run.var.teamcity.cloud.docker.client.apcon.ApacheConnector.java

@Override
public ClientResponse apply(final ClientRequest clientRequest) throws ProcessingException {
    final HttpUriRequest request = getUriHttpRequest(clientRequest);
    final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(clientRequest.getHeaders(), request);

    try {//from   www . j  ava 2s. c  o m
        final CloseableHttpResponse response;
        final HttpClientContext context = HttpClientContext.create();
        if (preemptiveBasicAuth) {
            final AuthCache authCache = new BasicAuthCache();
            final BasicScheme basicScheme = new BasicScheme();
            authCache.put(getHost(request), basicScheme);
            context.setAuthCache(authCache);
        }
        response = client.execute(getHost(request), request, context);
        HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, clientRequest.getHeaders(),
                this.getClass().getName());

        final Response.StatusType status = response.getStatusLine().getReasonPhrase() == null
                ? Statuses.from(response.getStatusLine().getStatusCode())
                : Statuses.from(response.getStatusLine().getStatusCode(),
                        response.getStatusLine().getReasonPhrase());

        final ClientResponse responseContext = new ClientResponse(status, clientRequest);
        final List<URI> redirectLocations = context.getRedirectLocations();
        if (redirectLocations != null && !redirectLocations.isEmpty()) {
            responseContext.setResolvedRequestUri(redirectLocations.get(redirectLocations.size() - 1));
        }

        final Header[] respHeaders = response.getAllHeaders();
        final MultivaluedMap<String, String> headers = responseContext.getHeaders();
        for (final Header header : respHeaders) {
            final String headerName = header.getName();
            List<String> list = headers.get(headerName);
            if (list == null) {
                list = new ArrayList<>();
            }
            list.add(header.getValue());
            headers.put(headerName, list);
        }

        final HttpEntity entity = response.getEntity();

        if (entity != null) {
            if (headers.get(HttpHeaders.CONTENT_LENGTH) == null) {
                headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(entity.getContentLength()));
            }

            final Header contentEncoding = entity.getContentEncoding();
            if (headers.get(HttpHeaders.CONTENT_ENCODING) == null && contentEncoding != null) {
                headers.add(HttpHeaders.CONTENT_ENCODING, contentEncoding.getValue());
            }
        }

        try {
            responseContext.setEntityStream(new HttpClientResponseInputStream(getInputStream(response)));
        } catch (final IOException e) {
            LOGGER.log(Level.SEVERE, null, e);
        }

        localHttpContext.set(context);
        return responseContext;
    } catch (final Exception e) {
        throw new ProcessingException(e);
    }
}

From source file:org.elasticsearch.client.RestClient.java

/**
 * Replaces the hosts that the client communicates with.
 * @see HttpHost//www .  j  av a  2s .c  o m
 */
public synchronized void setHosts(HttpHost... hosts) {
    if (hosts == null || hosts.length == 0) {
        throw new IllegalArgumentException("hosts must not be null nor empty");
    }
    Set<HttpHost> httpHosts = new HashSet<>();
    AuthCache authCache = new BasicAuthCache();
    for (HttpHost host : hosts) {
        Objects.requireNonNull(host, "host cannot be null");
        httpHosts.add(host);
        authCache.put(host, new BasicScheme());
    }
    this.hostTuple = new HostTuple<>(Collections.unmodifiableSet(httpHosts), authCache);
    this.blacklist.clear();
}

From source file:org.archive.modules.fetcher.FetchHTTPRequest.java

protected void populateHttpCredential(HttpHost host, AuthScheme authScheme, String user, String password) {
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, password);

    AuthCache authCache = httpClientContext.getAuthCache();
    if (authCache == null) {
        authCache = new BasicAuthCache();
        httpClientContext.setAuthCache(authCache);
    }//w  w w.j  a  v  a2s  .  co m
    authCache.put(host, authScheme);

    if (httpClientContext.getCredentialsProvider() == null) {
        httpClientContext.setCredentialsProvider(new BasicCredentialsProvider());
    }
    httpClientContext.getCredentialsProvider().setCredentials(new AuthScope(host), credentials);
}