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

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

Introduction

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

Prototype

public final HttpClientBuilder setConnectionManager(final HttpClientConnectionManager connManager) 

Source Link

Document

Assigns HttpClientConnectionManager instance.

Usage

From source file:eu.delving.sip.base.HttpClientFactory.java

public static HttpClient createHttpClient(File storageDirectory) {
    HttpClientBuilder builder = HttpClientBuilder.create().disableAutomaticRetries();
    builder.setConnectionManager(new PoolingHttpClientConnectionManager());
    if (!StorageFinder.isStandalone(storageDirectory)) {
        String serverUrl = String.format("http://%s", getHostPort(storageDirectory));
        handleProxy(serverUrl, builder);
    }/*from  ww  w  .  j  a va  2  s  . c  o m*/
    return builder.build();
}

From source file:ee.ria.xroad.proxy.clientproxy.FastestConnectionSelectingSSLSocketFactoryIntegrationTest.java

private static void createClient() throws Exception {
    RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
            .<ConnectionSocketFactory>create();

    socketFactoryRegistry.register("http", PlainConnectionSocketFactory.INSTANCE);

    socketFactoryRegistry.register("https", createSSLSocketFactory());

    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry.build());
    connMgr.setMaxTotal(CLIENT_MAX_TOTAL_CONNECTIONS);
    connMgr.setDefaultMaxPerRoute(CLIENT_MAX_CONNECTIONS_PER_ROUTE);

    int timeout = SystemProperties.getClientProxyTimeout();
    RequestConfig.Builder rb = RequestConfig.custom();
    rb.setConnectTimeout(timeout);//w  w w. j a v a  2s  .com
    rb.setConnectionRequestTimeout(timeout);
    rb.setSocketTimeout(timeout);

    HttpClientBuilder cb = HttpClients.custom();
    cb.setConnectionManager(connMgr);
    cb.setDefaultRequestConfig(rb.build());

    // Disable request retry
    cb.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));

    client = cb.build();
}

From source file:org.tinymediamanager.scraper.util.TmmHttpClient.java

/**
 * instantiates a new CloseableHttpClient
 * // w ww  .j  av a 2  s .co m
 * @return CloseableHttpClient
 */
public static CloseableHttpClient createHttpClient() {
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    // Increase default max connection per route to 5
    connectionManager.setMaxTotal(5);

    HttpClientBuilder httpClientBuilder = HttpClients.custom().useSystemProperties();
    httpClientBuilder.setConnectionManager(connectionManager);

    // my own retry handler
    HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {
        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount >= 5) {
                // Do not retry if over max retry count
                return false;
            }
            if (exception instanceof InterruptedIOException) {
                // Timeout
                return false;
            }
            if (exception instanceof UnknownHostException) {
                // Unknown host
                return false;
            }
            if (exception instanceof ConnectTimeoutException) {
                // Connection refused
                return false;
            }
            if (exception instanceof SSLException) {
                // SSL handshake exception
                return false;
            }
            HttpClientContext clientContext = HttpClientContext.adapt(context);
            HttpRequest request = clientContext.getRequest();
            boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
            if (idempotent) {
                // Retry if the request is considered idempotent
                return true;
            }
            return false;
        }

    };
    httpClientBuilder.setRetryHandler(myRetryHandler);

    // set proxy if needed
    if ((Globals.settings.useProxy())) {
        setProxy(httpClientBuilder);
    }

    return httpClientBuilder.build();
}

From source file:ee.ria.xroad.common.request.ManagementRequestClient.java

private static CloseableHttpClient createHttpClient(KeyManager km, TrustManager tm) throws Exception {
    RegistryBuilder<ConnectionSocketFactory> sfr = RegistryBuilder.<ConnectionSocketFactory>create();

    sfr.register("http", PlainConnectionSocketFactory.INSTANCE);

    SSLContext ctx = SSLContext.getInstance(CryptoUtils.SSL_PROTOCOL);
    ctx.init(km != null ? new KeyManager[] { km } : null, tm != null ? new TrustManager[] { tm } : null,
            new SecureRandom());

    SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(ctx,
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    sfr.register("https", sf);

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(sfr.build());
    cm.setMaxTotal(CLIENT_MAX_TOTAL_CONNECTIONS);
    cm.setDefaultMaxPerRoute(CLIENT_MAX_CONNECTIONS_PER_ROUTE);

    int timeout = SystemProperties.getClientProxyTimeout();
    int socketTimeout = SystemProperties.getClientProxyHttpClientTimeout();

    RequestConfig.Builder rb = RequestConfig.custom();
    rb.setConnectTimeout(timeout);//  www .j ava2  s  .c o m
    rb.setConnectionRequestTimeout(timeout);
    rb.setSocketTimeout(socketTimeout);

    HttpClientBuilder cb = HttpClients.custom();
    cb.setConnectionManager(cm);
    cb.setDefaultRequestConfig(rb.build());

    // Disable request retry
    cb.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));

    return cb.build();
}

From source file:org.apache.solr.cloud.TestMiniSolrCloudClusterSSL.java

/**
 * Returns a new HttpClient that supports both HTTP and HTTPS (with the default test truststore), but 
 * has no keystore -- so servers requiring client authentication should fail.
 *///from w  w  w .j  a v  a  2 s.co m
private static CloseableHttpClient getSslAwareClientWithNoClientCerts() throws Exception {

    // NOTE: This method explicitly does *NOT* use HttpClientUtil code because that
    // will muck with the global static HttpClientBuilder / SchemeRegistryProvider
    // and we can't do that and still test the entire purpose of what we are trying to test here.

    final SSLTestConfig clientConfig = new SSLTestConfig(true, false);

    final SSLConnectionSocketFactory sslFactory = clientConfig.buildClientSSLConnectionSocketFactory();
    assert null != sslFactory;

    final Registry<ConnectionSocketFactory> socketFactoryReg = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslFactory).register("http", PlainConnectionSocketFactory.INSTANCE).build();

    final HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryReg));

    return builder.build();
}

From source file:org.apache.solr.client.solrj.impl.HttpClientUtil.java

/**
 * Creates new http client by using the provided configuration.
 * /* ww  w.  ja  v  a 2 s .c o m*/
 */
public static CloseableHttpClient createClient(final SolrParams params, PoolingHttpClientConnectionManager cm,
        boolean sharedConnectionManager) {
    final ModifiableSolrParams config = new ModifiableSolrParams(params);
    if (logger.isDebugEnabled()) {
        logger.debug("Creating new http client, config:" + config);
    }

    cm.setMaxTotal(params.getInt(HttpClientUtil.PROP_MAX_CONNECTIONS, 10000));
    cm.setDefaultMaxPerRoute(params.getInt(HttpClientUtil.PROP_MAX_CONNECTIONS_PER_HOST, 10000));
    cm.setValidateAfterInactivity(
            Integer.getInteger(VALIDATE_AFTER_INACTIVITY, VALIDATE_AFTER_INACTIVITY_DEFAULT));

    HttpClientBuilder newHttpClientBuilder = HttpClientBuilder.create();

    if (sharedConnectionManager) {
        newHttpClientBuilder.setConnectionManagerShared(true);
    } else {
        newHttpClientBuilder.setConnectionManagerShared(false);
    }

    ConnectionKeepAliveStrategy keepAliveStrat = new ConnectionKeepAliveStrategy() {
        @Override
        public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
            // we only close connections based on idle time, not ttl expiration
            return -1;
        }
    };

    if (httpClientBuilder.getAuthSchemeRegistryProvider() != null) {
        newHttpClientBuilder.setDefaultAuthSchemeRegistry(
                httpClientBuilder.getAuthSchemeRegistryProvider().getAuthSchemeRegistry());
    }
    if (httpClientBuilder.getCookieSpecRegistryProvider() != null) {
        newHttpClientBuilder.setDefaultCookieSpecRegistry(
                httpClientBuilder.getCookieSpecRegistryProvider().getCookieSpecRegistry());
    }
    if (httpClientBuilder.getCredentialsProviderProvider() != null) {
        newHttpClientBuilder.setDefaultCredentialsProvider(
                httpClientBuilder.getCredentialsProviderProvider().getCredentialsProvider());
    }

    newHttpClientBuilder.addInterceptorLast(new DynamicInterceptor());

    newHttpClientBuilder = newHttpClientBuilder.setKeepAliveStrategy(keepAliveStrat).evictIdleConnections(
            (long) Integer.getInteger(EVICT_IDLE_CONNECTIONS, EVICT_IDLE_CONNECTIONS_DEFAULT),
            TimeUnit.MILLISECONDS);

    HttpClientBuilder builder = setupBuilder(newHttpClientBuilder, params);

    HttpClient httpClient = builder.setConnectionManager(cm).build();

    assert ObjectReleaseTracker.track(httpClient);
    return (CloseableHttpClient) httpClient;
}

From source file:lh.api.showcase.server.util.HttpClientUtils.java

public static CloseableHttpClient createHttpClient(HasProxySettings proxySetting,
        PoolingHttpClientConnectionManager connectionManager) {
    // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d5e475

    HttpClientBuilder clientBuilder = HttpClients.custom();
    if (proxySetting != null && proxySetting.isActive()) {
        logger.info("Set the http proxy (" + proxySetting.getHost() + ":" + proxySetting.getPort() + ")");
        CredentialsProvider credsProvider = Preconditions.checkNotNull(proxySetting.getCredentialsProvider());
        HttpHost proxy = new HttpHost(proxySetting.getHost(), proxySetting.getPort());
        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);

        clientBuilder.setRoutePlanner(routePlanner).setDefaultCredentialsProvider(credsProvider);
    }/*from   w  w  w  .  j a v a 2 s  . c o  m*/
    if (connectionManager != null) {
        clientBuilder.setConnectionManager(connectionManager);
    }
    return clientBuilder.build();
}

From source file:com.liferay.sync.engine.lan.session.LanSession.java

private static HttpClient _createHttpClient(int connectTimeout, int maxPerRoute, int maxTotal,
        int socketTimeout) {

    RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();

    try {/*  www.  j a  va 2  s  .c  om*/
        registryBuilder.register("https", _getSSLSocketFactory());
    } catch (Exception e) {
        _logger.error(e.getMessage(), e);
    }

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
            registryBuilder.build());

    connectionManager.setDefaultMaxPerRoute(maxPerRoute);
    connectionManager.setMaxTotal(maxTotal);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    RequestConfig.Builder builder = RequestConfig.custom();

    builder.setConnectTimeout(connectTimeout);
    builder.setSocketTimeout(socketTimeout);

    httpClientBuilder.setDefaultRequestConfig(builder.build());

    httpClientBuilder.setConnectionManager(connectionManager);

    return httpClientBuilder.build();
}

From source file:com.qwazr.utils.http.HttpUtils.java

/**
 * Create a new HttpClient which accept untrusted SSL certificates
 *
 * @return a new HttpClient/*w ww .  j a  va  2s.com*/
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public static CloseableHttpClient createHttpClient_AcceptsUntrustedCerts()
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

    final HttpClientBuilder unsecureHttpClientBuilder = HttpClientBuilder.create();

    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();

    unsecureHttpClientBuilder.setSSLContext(sslContext);

    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
            NoopHostnameVerifier.INSTANCE);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();

    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    unsecureHttpClientBuilder.setConnectionManager(connMgr);
    return unsecureHttpClientBuilder.build();
}

From source file:mobi.jenkinsci.server.core.net.PooledHttpClientFactory.java

private HttpClientBuilder configureHttpClientBuilder(HttpClientBuilder httpClientBuilder) {
    return httpClientBuilder.setConnectionManager(getHttpConnectionManager())
            .setDefaultRequestConfig(getRequestConfig()).setDefaultSocketConfig(getSocketConfig());
}