Example usage for org.apache.http.impl.client HttpClients custom

List of usage examples for org.apache.http.impl.client HttpClients custom

Introduction

In this page you can find the example usage for org.apache.http.impl.client HttpClients custom.

Prototype

public static HttpClientBuilder custom() 

Source Link

Document

Creates builder object for construction of custom CloseableHttpClient instances.

Usage

From source file:no.difi.vefa.peppol.lookup.fetcher.BasicApacheFetcher.java

protected CloseableHttpClient createClient() {
    return HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
}

From source file:com.blazemeter.bamboo.plugin.api.HttpUtility.java

public HttpUtility() {
    this.httpClient = HttpClients.createDefault();
    useProxy = Boolean.parseBoolean(System.getProperty(Constants.USE_PROXY));
    proxyHost = System.getProperty(Constants.PROXY_HOST);

    try {//  ww w.j  ava 2s. co m
        this.proxyPort = Integer.parseInt(System.getProperty(Constants.PROXY_PORT));
    } catch (NumberFormatException nfe) {
        logger.error("Failed to read http.proxyPort: ", nfe);
    }
    if (useProxy && !org.apache.commons.lang3.StringUtils.isBlank(this.proxyHost)) {
        this.proxy = new HttpHost(proxyHost, proxyPort);

        this.proxyUser = System.getProperty(Constants.PROXY_USER);
        this.proxyPass = System.getProperty(Constants.PROXY_PASS);
        if (!org.apache.commons.lang3.StringUtils.isEmpty(this.proxyUser)
                && !org.apache.commons.lang3.StringUtils.isEmpty(this.proxyPass)) {
            Credentials cr = new UsernamePasswordCredentials(proxyUser, proxyPass);
            AuthScope aus = new AuthScope(proxyHost, proxyPort);
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(aus, cr);
            this.httpClient = HttpClients.custom().setProxy(proxy).setDefaultCredentialsProvider(credsProvider)
                    .build();
        } else {
            this.httpClient = HttpClients.custom().setProxy(proxy).build();
        }
    }
}

From source file:org.superbiz.AuthBeanTest.java

private String get(final String user, final String password) {
    final BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
    basicCredentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
    final CloseableHttpClient client = HttpClients.custom()
            .setDefaultCredentialsProvider(basicCredentialsProvider).build();

    final HttpHost httpHost = new HttpHost(webapp.getHost(), webapp.getPort(), webapp.getProtocol());
    final AuthCache authCache = new BasicAuthCache();
    final BasicScheme basicAuth = new BasicScheme();
    authCache.put(httpHost, basicAuth);//  ww w . j ava2 s .  c om
    final HttpClientContext context = HttpClientContext.create();
    context.setAuthCache(authCache);

    final HttpGet get = new HttpGet(webapp.toExternalForm() + "servlet");
    CloseableHttpResponse response = null;
    try {
        response = client.execute(httpHost, get, context);
        return response.getStatusLine().getStatusCode() + " " + EntityUtils.toString(response.getEntity());
    } catch (final IOException e) {
        throw new IllegalStateException(e);
    } finally {
        try {
            IO.close(response);
        } catch (final IOException e) {
            // no-op
        }
    }
}

From source file:monasca.api.infrastructure.persistence.influxdb.InfluxV9RepoReader.java

@Inject
public InfluxV9RepoReader(final ApiConfig config) {

    this.influxName = config.influxDB.getName();
    logger.debug("Influxdb database name: {}", this.influxName);

    this.influxUrl = config.influxDB.getUrl() + "/query";
    logger.debug("Influxdb URL: {}", this.influxUrl);

    this.influxUser = config.influxDB.getUser();
    this.influxPass = config.influxDB.getPassword();
    this.influxCreds = this.influxUser + ":" + this.influxPass;

    this.gzip = config.influxDB.getGzip();
    logger.debug("Influxdb gzip responses: {}", this.gzip);

    logger.debug("Setting up basic Base64 authentication");
    this.baseAuthHeader = "Basic " + new String(Base64.encodeBase64(this.influxCreds.getBytes()));

    // We inject InfluxV9RepoReader as a singleton. So, we must share connections safely.
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(config.influxDB.getMaxHttpConnections());

    if (this.gzip) {

        logger.debug("Setting up gzip responses from Influxdb");

        this.httpClient = HttpClients.custom().setConnectionManager(cm)
                .addInterceptorFirst(new HttpRequestInterceptor() {

                    public void process(final HttpRequest request, final HttpContext context)
                            throws HttpException, IOException {
                        if (!request.containsHeader("Accept-Encoding")) {
                            request.addHeader("Accept-Encoding", "gzip");
                        }/*from  w ww  .ja v  a2s  .c om*/
                    }
                }).addInterceptorFirst(new HttpResponseInterceptor() {

                    public void process(final HttpResponse response, final HttpContext context)
                            throws HttpException, IOException {
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            Header ceheader = entity.getContentEncoding();
                            if (ceheader != null) {
                                HeaderElement[] codecs = ceheader.getElements();
                                for (int i = 0; i < codecs.length; i++) {
                                    if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                                        return;
                                    }
                                }
                            }
                        }
                    }
                }).build();

    } else {

        logger.debug("Setting up non-gzip responses from Influxdb");

        this.httpClient = HttpClients.custom().setConnectionManager(cm).build();

    }
}

From source file:com.github.restdriver.clientdriver.integration.SecureClientDriverTest.java

@Test(expected = SSLHandshakeException.class)
public void testConnectionFailsWithoutTrustMaterial() throws Exception {
    // Arrange/*from   ww  w . jav  a  2  s  . c  o  m*/
    KeyStore keyStore = getKeystore();
    SecureClientDriver driver = new SecureClientDriver(
            new DefaultClientDriverJettyHandler(new DefaultRequestMatcher()), keyStore, "password",
            "certificate");
    driver.addExpectation(onRequestTo("/test"), giveEmptyResponse());

    // set the test certificate as trusted
    HttpClient client = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
    HttpGet getter = new HttpGet(driver.getBaseUrl() + "/test");

    // Act
    client.execute(getter);

}

From source file:eu.over9000.cathode.Dispatcher.java

Dispatcher(final String clientID, final String authToken) {
    undocumented = new UndocumentedDispatcher();

    final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(CONNECTION_COUNT);
    connectionManager.setDefaultMaxPerRoute(CONNECTION_COUNT);

    final List<Header> headers = new ArrayList<>();
    headers.add(new BasicHeader(HttpHeaders.ACCEPT, "application/vnd.twitchtv.v3+json"));
    headers.add(new BasicHeader("Client-ID", clientID));
    if (authToken != null) {
        headers.add(new BasicHeader("Authorization", "OAuth " + authToken));
    }//  w w w . ja  v a2  s  . c o  m

    HTTP_CLIENT = HttpClients.custom().setDefaultHeaders(headers).setConnectionManager(connectionManager)
            .build();
}

From source file:io.crate.integrationtests.BlobSslEnabledITest.java

@Test
public void testGetBlob() throws Exception {
    // this test verifies that the non-zero-copy code path in the HttpBlobHandler works
    String digest = uploadSmallBlob();
    String blobUri = blobUri(digest);

    // can't follow redirects because ssl isn't really enabled
    // -> figure out the node that really has the blob

    CloseableHttpClient client = HttpClients.custom().disableRedirectHandling().build();
    List<String> redirectLocations = getRedirectLocations(client, blobUri, address);
    InetSocketAddress correctAddress;
    if (redirectLocations.isEmpty()) {
        correctAddress = address;//from w  ww  . j  ava  2 s  . c  o m
    } else {
        correctAddress = address2;
    }

    HttpGet httpGet = new HttpGet(String.format(Locale.ENGLISH, "http://%s:%s/_blobs/%s",
            correctAddress.getHostName(), correctAddress.getPort(), blobUri));

    CloseableHttpResponse response = client.execute(httpGet);
    assertEquals(1500, response.getEntity().getContentLength());
}

From source file:com.mirth.connect.plugins.httpauth.oauth2.OAuth2Authenticator.java

@Override
public AuthenticationResult authenticate(RequestInfo request) throws Exception {
    OAuth2HttpAuthProperties properties = getReplacedProperties(request);

    CloseableHttpClient client = null;//from ww  w .j  ava 2 s .  c  o m
    CloseableHttpResponse response = null;

    try {
        // Create and configure the client and context 
        RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory());
        ConnectorPluginProperties pluginProperties = null;
        if (CollectionUtils.isNotEmpty(properties.getConnectorPluginProperties())) {
            pluginProperties = properties.getConnectorPluginProperties().iterator().next();
        }
        provider.getHttpConfiguration().configureSocketFactoryRegistry(pluginProperties, socketFactoryRegistry);
        BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager(
                socketFactoryRegistry.build());
        httpClientConnectionManager.setSocketConfig(SocketConfig.custom().setSoTimeout(SOCKET_TIMEOUT).build());
        HttpClientBuilder clientBuilder = HttpClients.custom()
                .setConnectionManager(httpClientConnectionManager);
        HttpUtil.configureClientBuilder(clientBuilder);
        client = clientBuilder.build();

        HttpClientContext context = HttpClientContext.create();
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(SOCKET_TIMEOUT)
                .setSocketTimeout(SOCKET_TIMEOUT).setStaleConnectionCheckEnabled(true).build();
        context.setRequestConfig(requestConfig);

        URIBuilder uriBuilder = new URIBuilder(properties.getVerificationURL());

        // Add query parameters
        if (properties.getTokenLocation() == TokenLocation.QUERY) {
            List<String> paramList = request.getQueryParameters().get(properties.getLocationKey());
            if (CollectionUtils.isNotEmpty(paramList)) {
                for (String value : paramList) {
                    uriBuilder.addParameter(properties.getLocationKey(), value);
                }
            }
        }

        // Build the final URI and create a GET request
        HttpGet httpGet = new HttpGet(uriBuilder.build());

        // Add headers
        if (properties.getTokenLocation() == TokenLocation.HEADER) {
            List<String> headerList = request.getHeaders().get(properties.getLocationKey());
            if (CollectionUtils.isNotEmpty(headerList)) {
                for (String value : headerList) {
                    httpGet.addHeader(properties.getLocationKey(), value);
                }
            }
        }

        // Execute the request
        response = client.execute(httpGet, context);

        // Determine authentication from the status code 
        if (response.getStatusLine().getStatusCode() < 400) {
            return AuthenticationResult.Success();
        } else {
            return AuthenticationResult.Failure();
        }
    } finally {
        HttpClientUtils.closeQuietly(response);
        HttpClientUtils.closeQuietly(client);
    }
}