Example usage for org.apache.http.impl.client HttpClientBuilder setMaxConnPerRoute

List of usage examples for org.apache.http.impl.client HttpClientBuilder setMaxConnPerRoute

Introduction

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

Prototype

public final HttpClientBuilder setMaxConnPerRoute(final int maxConnPerRoute) 

Source Link

Document

Assigns maximum connection per route value.

Usage

From source file:org.ow2.proactive.http.CommonHttpClientBuilder.java

public CloseableHttpClient build() {
    org.apache.http.impl.client.HttpClientBuilder internalHttpClientBuilder = createInternalHttpClientBuilder();

    if (useSystemProperties) {
        internalHttpClientBuilder.useSystemProperties();
    }//from   www  .ja  v  a 2  s.  c o  m

    if (overrideAllowAnyHostname != null) {
        if (overrideAllowAnyHostname) {
            acceptAnyHostname = true;
        } else {
            acceptAnyHostname = false;
        }
    }

    if (overrideAllowAnyCertificate != null) {
        if (overrideAllowAnyCertificate) {
            acceptAnyCertificate = true;
        } else {
            acceptAnyCertificate = false;
        }
    }

    if (acceptAnyCertificate) {
        internalHttpClientBuilder.setSslcontext(createSslContext());
    }

    if (acceptAnyHostname) {
        internalHttpClientBuilder.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    }

    if (maxConnections > 0) {
        internalHttpClientBuilder.setMaxConnPerRoute(maxConnections);
        internalHttpClientBuilder.setMaxConnTotal(maxConnections);
    }

    if (requestConfig != null) {
        internalHttpClientBuilder.setDefaultRequestConfig(requestConfig);
    }

    if (!useContentCompression) {
        internalHttpClientBuilder.disableContentCompression();
    }

    return internalHttpClientBuilder.build();
}

From source file:com.gargoylesoftware.htmlunit.HttpWebConnection.java

/**
 * Creates the <tt>HttpClientBuilder</tt> that will be used by this WebClient.
 * Extensions may override this method in order to create a customized
 * <tt>HttpClientBuilder</tt> instance (e.g. with a custom
 * {@link org.apache.http.conn.ClientConnectionManager} to perform
 * some tracking; see feature request 1438216).
 * @return the <tt>HttpClientBuilder</tt> that will be used by this WebConnection
 *//*from www  .j a v  a 2  s.c  o m*/
protected HttpClientBuilder createHttpClient() {
    final HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setRedirectStrategy(new HtmlUnitRedirectStrategie());
    configureTimeout(builder, getTimeout());
    configureHttpsScheme(builder);
    builder.setMaxConnPerRoute(6);
    return builder;
}

From source file:com.nextdoor.bender.ipc.http.AbstractHttpTransportFactory.java

protected HttpClientBuilder getClientBuilder(boolean useSSL, String url, Map<String, String> stringHeaders,
        int socketTimeout) {

    HttpClientBuilder cb = HttpClientBuilder.create();

    /*/*from www. j  a  v  a  2s.c  o m*/
     * Setup SSL
     */
    if (useSSL) {
        /*
         * All trusting SSL context
         */
        try {
            cb.setSSLContext(getSSLContext());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        /*
         * All trusting hostname verifier
         */
        cb.setSSLHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });
    }

    /*
     * Add default headers
     */
    ArrayList<BasicHeader> headers = new ArrayList<BasicHeader>(stringHeaders.size());
    stringHeaders.forEach((k, v) -> headers.add(new BasicHeader(k, v)));
    cb.setDefaultHeaders(headers);

    /*
     * Set socket timeout and transport threads
     */
    SocketConfig sc = SocketConfig.custom().setSoTimeout(socketTimeout).build();
    cb.setDefaultSocketConfig(sc);
    cb.setMaxConnPerRoute(this.config.getThreads());
    cb.setMaxConnTotal(this.config.getThreads());

    return cb;
}

From source file:org.apache.hadoop.gateway.dispatch.DefaultHttpClientFactory.java

@Override
public HttpClient createHttpClient(FilterConfig filterConfig) {
    HttpClientBuilder builder = null;
    GatewayConfig gatewayConfig = (GatewayConfig) filterConfig.getServletContext()
            .getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE);
    if (gatewayConfig != null && gatewayConfig.isMetricsEnabled()) {
        GatewayServices services = (GatewayServices) filterConfig.getServletContext()
                .getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
        MetricsService metricsService = services.getService(GatewayServices.METRICS_SERVICE);
        builder = metricsService.getInstrumented(HttpClientBuilder.class);
    } else {/*from w w w  .j  a v a2s. c om*/
        builder = HttpClients.custom();
    }
    if ("true".equals(System.getProperty(GatewayConfig.HADOOP_KERBEROS_SECURED))) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UseJaasCredentials());

        Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                .register(AuthSchemes.SPNEGO, new KnoxSpnegoAuthSchemeFactory(true)).build();

        builder = builder.setDefaultAuthSchemeRegistry(authSchemeRegistry)
                .setDefaultCookieStore(new HadoopAuthCookieStore())
                .setDefaultCredentialsProvider(credentialsProvider);
    } else {
        builder = builder.setDefaultCookieStore(new NoCookieStore());
    }

    builder.setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE);
    builder.setConnectionReuseStrategy(DefaultConnectionReuseStrategy.INSTANCE);
    builder.setRedirectStrategy(new NeverRedirectStrategy());
    builder.setRetryHandler(new NeverRetryHandler());

    int maxConnections = getMaxConnections(filterConfig);
    builder.setMaxConnTotal(maxConnections);
    builder.setMaxConnPerRoute(maxConnections);

    builder.setDefaultRequestConfig(getRequestConfig(filterConfig));

    HttpClient client = builder.build();
    return client;
}

From source file:com.cisco.oss.foundation.http.apache.ApacheHttpClient.java

@Override
protected void configureClient() {

    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder.setConnectTimeout(metadata.getConnectTimeout());
    requestBuilder = requestBuilder.setSocketTimeout(metadata.getReadTimeout());
    requestBuilder = requestBuilder.setStaleConnectionCheckEnabled(metadata.isStaleConnectionCheckEnabled());

    RequestConfig requestConfig = requestBuilder.build();

    boolean addSslSupport = StringUtils.isNotEmpty(metadata.getKeyStorePath())
            && StringUtils.isNotEmpty(metadata.getKeyStorePassword());

    boolean addTrustSupport = StringUtils.isNotEmpty(metadata.getTrustStorePath())
            && StringUtils.isNotEmpty(metadata.getTrustStorePassword());

    autoCloseable = metadata.isAutoCloseable();

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    SSLContext sslContext = null;

    try {/*ww  w  .jav  a 2  s. co m*/

        String keystoreType = "JKS";
        if (addSslSupport && addTrustSupport) {

            KeyStore keyStore = KeyStore.getInstance(keystoreType);
            keyStore.load(new FileInputStream(metadata.getKeyStorePath()),
                    metadata.getKeyStorePassword().toCharArray());

            KeyStore trustStore = KeyStore.getInstance(keystoreType);
            trustStore.load(new FileInputStream(metadata.getTrustStorePath()),
                    metadata.getTrustStorePassword().toCharArray());

            sslContext = SSLContexts.custom().useProtocol("TLS")
                    .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray())
                    .loadTrustMaterial(trustStore, null).build();

        } else if (addSslSupport) {

            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());

            KeyStore keyStore = KeyStore.getInstance(keystoreType);
            keyStore.load(new FileInputStream(metadata.getKeyStorePath()),
                    metadata.getKeyStorePassword().toCharArray());

            tmf.init(keyStore);

            sslContext = SSLContexts.custom().useProtocol("SSL")
                    .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray()).build();

            sslContext.init(null, tmf.getTrustManagers(), null);

            SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);

            httpClientBuilder.setSSLSocketFactory(sf);

        } else if (addTrustSupport) {

            KeyStore trustStore = KeyStore.getInstance(keystoreType);
            trustStore.load(new FileInputStream(metadata.getTrustStorePath()),
                    metadata.getTrustStorePassword().toCharArray());

            sslContext = SSLContexts.custom().useProtocol("TLS").loadTrustMaterial(trustStore, null).build();

        }

        if (addSslSupport | addTrustSupport) {
            SSLContext.setDefault(sslContext);
            httpClientBuilder.setSslcontext(sslContext);
        }

    } catch (Exception e) {
        LOGGER.error("can't set TLS Support. Error is: {}", e, e);
    }

    httpClientBuilder.setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress())
            .setMaxConnTotal(metadata.getMaxConnectionsTotal()).setDefaultRequestConfig(requestConfig)
            .evictExpiredConnections().evictIdleConnections(metadata.getIdleTimeout(), TimeUnit.MILLISECONDS)
            .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout()));

    HttpAsyncClientBuilder httpAsyncClientBuilder = HttpAsyncClients.custom();

    httpAsyncClientBuilder.setDefaultRequestConfig(requestConfig)
            .setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress())
            .setMaxConnTotal(metadata.getMaxConnectionsTotal())
            .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout()))
            .setSSLContext(sslContext);

    if (metadata.isDisableCookies()) {
        httpClientBuilder.disableCookieManagement();
        httpAsyncClientBuilder.disableCookieManagement();
    }

    if (hostnameVerifier != null) {
        httpClientBuilder.setSSLHostnameVerifier(hostnameVerifier);
        httpAsyncClientBuilder.setSSLHostnameVerifier(hostnameVerifier);
    }

    if (!followRedirects) {
        httpClientBuilder.disableRedirectHandling();
    }

    httpClient = httpClientBuilder.build();

    httpAsyncClient = httpAsyncClientBuilder.build();

    httpAsyncClient.start();

}

From source file:com.cisco.oss.foundation.http.netlifx.apache.ApacheNetflixHttpClient.java

protected void configureClient() {

    clientConfig = new DefaultClientConfigImpl();
    clientConfig.loadProperties(getApiName());
    setLoadBalancer(loadBalancer);//from   w  w  w.  j  a va  2 s  .  co m
    //        clientConfig.set(CommonClientConfigKey.NIWSServerListClassName, DiscoveryEnabledNIWSServerList.class.getName());
    //        clientConfig.set(IClientConfigKey.Keys.DeploymentContextBasedVipAddresses, metadata.getServiceName());
    //        clientConfig.set(CommonClientConfigKey.NFLoadBalancerRuleClassName, RoundRobinRule.class.getName());
    //        clientConfig.set(CommonClientConfigKey.NFLoadBalancerPingClassName, NIWSDiscoveryPing.class.getName());
    //        clientConfig.set(CommonClientConfigKey.VipAddressResolverClassName, SimpleVipAddressResolver.class.getName());

    if (DiscoveryManager.getInstance().getDiscoveryClient() == null && startEurekaClient) {
        EurekaInstanceConfig eurekaInstanceConfig = new MyDataCenterInstanceConfig(getApiName());
        EurekaClientConfig eurekaClientConfig = new DefaultEurekaClientConfig(getApiName() + ".");
        DiscoveryManager.getInstance().initComponent(eurekaInstanceConfig, eurekaClientConfig);
    }

    loadBalancer.initWithNiwsConfig(clientConfig);

    //        if (HystrixPlugins.getInstance().getMetricsPublisher() == null) {
    //            HystrixPlugins.getInstance().registerMetricsPublisher(HystrixMetricsPublisherDefault.getInstance());
    //        }

    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder.setConnectTimeout(metadata.getConnectTimeout());
    requestBuilder = requestBuilder.setSocketTimeout(metadata.getReadTimeout());
    requestBuilder = requestBuilder.setStaleConnectionCheckEnabled(metadata.isStaleConnectionCheckEnabled());

    RequestConfig requestConfig = requestBuilder.build();

    boolean addSslSupport = StringUtils.isNotEmpty(metadata.getKeyStorePath())
            && StringUtils.isNotEmpty(metadata.getKeyStorePassword());

    boolean addTrustSupport = StringUtils.isNotEmpty(metadata.getTrustStorePath())
            && StringUtils.isNotEmpty(metadata.getTrustStorePassword());

    autoCloseable = metadata.isAutoCloseable();

    autoEncodeUri = metadata.isAutoEncodeUri();
    followRedirects = metadata.isFollowRedirects();

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    SSLContext sslContext = null;

    try {

        String keystoreType = "JKS";
        if (addSslSupport && addTrustSupport) {

            KeyStore keyStore = KeyStore.getInstance(keystoreType);
            keyStore.load(new FileInputStream(metadata.getKeyStorePath()),
                    metadata.getKeyStorePassword().toCharArray());

            KeyStore trustStore = KeyStore.getInstance(keystoreType);
            trustStore.load(new FileInputStream(metadata.getTrustStorePath()),
                    metadata.getTrustStorePassword().toCharArray());

            sslContext = SSLContexts.custom().useProtocol("TLS")
                    .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray())
                    .loadTrustMaterial(trustStore, null).build();

        } else if (addSslSupport) {

            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());

            KeyStore keyStore = KeyStore.getInstance(keystoreType);
            keyStore.load(new FileInputStream(metadata.getKeyStorePath()),
                    metadata.getKeyStorePassword().toCharArray());

            tmf.init(keyStore);

            sslContext = SSLContexts.custom().useProtocol("SSL")
                    .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray()).build();

            sslContext.init(null, tmf.getTrustManagers(), null);

            SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);

            httpClientBuilder.setSSLSocketFactory(sf);

        } else if (addTrustSupport) {

            KeyStore trustStore = KeyStore.getInstance(keystoreType);
            trustStore.load(new FileInputStream(metadata.getTrustStorePath()),
                    metadata.getTrustStorePassword().toCharArray());

            sslContext = SSLContexts.custom().useProtocol("TLS").loadTrustMaterial(trustStore, null).build();

        }

        if (addSslSupport | addTrustSupport) {
            SSLContext.setDefault(sslContext);
            httpClientBuilder.setSslcontext(sslContext);
        }

    } catch (Exception e) {
        LOGGER.error("can't set TLS Support. Error is: {}", e, e);
    }

    httpClientBuilder.setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress())
            .setMaxConnTotal(metadata.getMaxConnectionsTotal()).setDefaultRequestConfig(requestConfig)
            .evictExpiredConnections().evictIdleConnections(metadata.getIdleTimeout(), TimeUnit.MILLISECONDS)
            .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout()));

    HttpAsyncClientBuilder httpAsyncClientBuilder = HttpAsyncClients.custom();

    httpAsyncClientBuilder.setDefaultRequestConfig(requestConfig)
            .setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress())
            .setMaxConnTotal(metadata.getMaxConnectionsTotal())
            .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout()))
            .setSSLContext(sslContext);

    if (metadata.isDisableCookies()) {
        httpClientBuilder.disableCookieManagement();
        httpAsyncClientBuilder.disableCookieManagement();
    }

    if (hostnameVerifier != null) {
        httpClientBuilder.setSSLHostnameVerifier(hostnameVerifier);
        httpAsyncClientBuilder.setSSLHostnameVerifier(hostnameVerifier);
    }

    if (!followRedirects) {
        httpClientBuilder.disableRedirectHandling();
    }

    httpClient = httpClientBuilder.build();

    httpAsyncClient = httpAsyncClientBuilder.build();

    httpAsyncClient.start();

}