Example usage for org.apache.http.impl.conn PoolingHttpClientConnectionManager PoolingHttpClientConnectionManager

List of usage examples for org.apache.http.impl.conn PoolingHttpClientConnectionManager PoolingHttpClientConnectionManager

Introduction

In this page you can find the example usage for org.apache.http.impl.conn PoolingHttpClientConnectionManager PoolingHttpClientConnectionManager.

Prototype

public PoolingHttpClientConnectionManager(
            final HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory) 

Source Link

Usage

From source file:com.ericsson.gerrit.plugins.highavailability.forwarder.rest.HttpClientProvider.java

private HttpClientConnectionManager customConnectionManager() {
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslSocketFactory).register("http", PlainConnectionSocketFactory.INSTANCE)
            .build();/*ww w.  j a v  a2 s .c o  m*/
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry);
    connManager.setDefaultMaxPerRoute(CONNECTIONS_PER_ROUTE);
    connManager.setMaxTotal(MAX_CONNECTIONS);
    connManager.setValidateAfterInactivity(MAX_CONNECTION_INACTIVITY);
    return connManager;
}

From source file:org.ops4j.pax.url.mvn.internal.HttpClients.java

private static PoolingHttpClientConnectionManager createConnManager(PropertyResolver resolver, String pid) {
    boolean SSL_INSECURE = getBoolean(resolver, "maven.wagon.http.ssl.insecure",
            !getBoolean(resolver, pid + "certificateCheck", false));
    boolean IGNORE_SSL_VALIDITY_DATES = getBoolean(resolver, "maven.wagon.http.ssl.ignore.validity.dates",
            false);//from  ww  w.  j a  v a2 s.com
    boolean SSL_ALLOW_ALL = getBoolean(resolver, "maven.wagon.http.ssl.allowall",
            !getBoolean(resolver, pid + "certificateCheck", false));
    boolean PERSISTENT_POOL = getBoolean(resolver, "maven.wagon.http.pool", true);
    int MAX_CONN_PER_ROUTE = getInteger(resolver, "maven.wagon.httpconnectionManager.maxPerRoute", 20);
    int MAX_CONN_TOTAL = getInteger(resolver, "maven.wagon.httpconnectionManager.maxTotal", 40);

    String sslProtocolsStr = getProperty(resolver, "https.protocols", null);
    String cipherSuitesStr = getProperty(resolver, "https.cipherSuites", null);
    String[] sslProtocols = sslProtocolsStr != null ? sslProtocolsStr.split(" *, *") : null;
    String[] cipherSuites = cipherSuitesStr != null ? cipherSuitesStr.split(" *, *") : null;

    SSLConnectionSocketFactory sslConnectionSocketFactory;
    if (SSL_INSECURE) {
        try {
            SSLContext sslContext = new SSLContextBuilder().useSSL()
                    .loadTrustMaterial(null, new RelaxedTrustStrategy(IGNORE_SSL_VALIDITY_DATES)).build();
            sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, sslProtocols, cipherSuites,
                    SSL_ALLOW_ALL ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
                            : SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        } catch (Exception ex) {
            throw new SSLInitializationException(ex.getMessage(), ex);
        }
    } else {
        sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                HttpsURLConnection.getDefaultSSLSocketFactory(), sslProtocols, cipherSuites,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    }

    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", sslConnectionSocketFactory).build();

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
    if (PERSISTENT_POOL) {
        connManager.setDefaultMaxPerRoute(MAX_CONN_PER_ROUTE);
        connManager.setMaxTotal(MAX_CONN_TOTAL);
    } else {
        connManager.setMaxTotal(1);
    }

    boolean soKeepAlive = getBoolean(resolver, pid + ServiceConstants.PROPERTY_SOCKET_SO_KEEPALIVE, false);
    int soLinger = getInteger(resolver, pid + ServiceConstants.PROPERTY_SOCKET_SO_LINGER, -1);
    boolean soReuseAddress = getBoolean(resolver, pid + ServiceConstants.PROPERTY_SOCKET_SO_REUSEADDRESS,
            false);
    boolean soTcpNoDelay = getBoolean(resolver, pid + ServiceConstants.PROPERTY_SOCKET_TCP_NODELAY, true);
    //        int soTimeout = getInteger( resolver, pid + ServiceConstants.PROPERTY_SOCKET_SO_TIMEOUT, 0 );
    SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(soKeepAlive) // default false
            .setSoLinger(soLinger) // default -1
            .setSoReuseAddress(soReuseAddress) // default false
            .setTcpNoDelay(soTcpNoDelay) // default true
            .setSoTimeout(0) // default 0, but set in org.apache.http.impl.conn.CPoolProxy.setSocketTimeout()
            // this value is not used
            .build();
    connManager.setDefaultSocketConfig(socketConfig);

    int bufferSize = getInteger(resolver, pid + ServiceConstants.PROPERTY_CONNECTION_BUFFER_SIZE, 8192);
    ConnectionConfig connectionConfig = ConnectionConfig.custom().setBufferSize(bufferSize) // default 8192
            .setFragmentSizeHint(bufferSize) // default 'buffer size'
            .build();
    connManager.setDefaultConnectionConfig(connectionConfig);

    return connManager;
}

From source file:leap.lang.http.client.apache.ApacheHttpClient.java

protected CloseableHttpClient initHttpClient() {
    HttpClientBuilder cb = HttpClientBuilder.create();

    //TODO : small buffer size will cause socket closed when reading response entity?
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(getDefaultRegistry());
    //cm.setDefaultConnectionConfig(ConnectionConfig.custom().setBufferSize(1024 * 1024).build());

    cm.setMaxTotal(maxConnectionTotal);// www.  j av  a2 s  .c o  m
    cm.setDefaultMaxPerRoute(maxConnectionPerRoute);

    if (bufferSize > 0) {
        ConnectionConfig cc = ConnectionConfig.copy(ConnectionConfig.DEFAULT).setBufferSize(bufferSize).build();

        cm.setDefaultConnectionConfig(cc);
    }

    cb.setRetryHandler(new HttpRequestRetryHandler() {
        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            return false;
        }
    });

    cb.setConnectionManager(cm);
    cb.setDefaultRequestConfig(requestConfig);

    return cb.build();
}

From source file:com.vmware.bdd.cli.http.HttpClientProvider.java

@Bean(name = SECURE_HTTP_CLIENT)
@Qualifier(SECURE_HTTP_CLIENT)//from  w w  w  . jav  a2  s .co m
public HttpClient secureHttpClient()
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    SSLContext sslContext = SSLContexts.custom().useTLS().build();

    sslContext.init(null, new TrustManager[] { trustManager }, null);

    String[] supportedProtocols = cliProperties.getSupportedProtocols();
    String[] supportedCipherSuites = cliProperties.getSupportedCipherSuites();
    String hostnameVerifier = cliProperties.getHostnameVerifier();

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("supported protocols: " + ArrayUtils.toString(supportedProtocols));
        LOGGER.debug("supported cipher suites: " + ArrayUtils.toString(supportedCipherSuites));
        LOGGER.debug("hostname verifier: " + hostnameVerifier);
    }

    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, supportedProtocols,
            supportedCipherSuites, getHostnameVerifier(hostnameVerifier));

    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", socketFactory)
            .build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    cm.setMaxTotal(20);
    cm.setDefaultMaxPerRoute(10);
    //      HttpHost proxy = new HttpHost("127.0.0.1", 8810, "http");
    //      HttpClient  client1 = HttpClients.custom().setSSLSocketFactory(socketFactory).setProxy(proxy).build();

    HttpClient client1 = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    return client1;
}

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);/*  ww  w  . j av  a 2s.  co m*/
    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.createnet.raptor.auth.AuthHttpClient.java

private CloseableHttpClient getHttpClient() throws KeyStoreException, NoSuchAlgorithmException,
        KeyManagementException, UnrecoverableKeyException, CertificateException, IOException {

    if (httpclient == null) {

        logger.debug("Created http client instance");

        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(new File(config.token.truststore.path),
                config.token.truststore.password.toCharArray(), new TrustSelfSignedStrategy()).build();

        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
                new String[] { "TLSv1.2", "TLSv1.1", "TLSv1" }, null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());

        Registry socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE).register("https", sslsf).build();

        HttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager(
                socketFactoryRegistry);//from  ww  w.  ja  va  2s.  c om

        httpclient = HttpClients.custom()
                //              .setSSLSocketFactory(sslsf)
                .setConnectionManager(poolingConnManager)
                //              .setConnectionManagerShared(true)
                .build();
    }

    return httpclient;
}

From source file:com.questdb.test.tools.HttpTestUtils.java

private static HttpClientBuilder createHttpClient_AcceptsUntrustedCerts() throws Exception {
    HttpClientBuilder b = HttpClientBuilder.create();

    // setup a Trust Strategy that allows all certificates.
    ///*from  w w w  . j av  a  2s.  com*/
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();

    b.setSSLContext(sslContext);

    // here's the special part:
    //      -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
    //      -- and create a Registry, to register it.
    //
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
            new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();

    // now, we create connection-manager using our Registry.
    //      -- allows multi-threaded use
    b.setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryRegistry));

    return b;
}

From source file:ee.ria.xroad.common.opmonitoring.OpMonitoringDaemonHttpClient.java

/**
 * Creates HTTP client.//ww  w.  j  av a  2  s  .c o m
 * @param authKey the client's authentication key
 * @param clientMaxTotalConnections client max total connections
 * @param clientMaxConnectionsPerRoute client max connections per route
 * @param connectionTimeoutMilliseconds connection timeout in milliseconds
 * @param socketTimeoutMilliseconds socket timeout in milliseconds
 * @return HTTP client
 * @throws Exception if creating a HTTPS client and SSLContext
 * initialization fails
 */
public static CloseableHttpClient createHttpClient(InternalSSLKey authKey, int clientMaxTotalConnections,
        int clientMaxConnectionsPerRoute, int connectionTimeoutMilliseconds, int socketTimeoutMilliseconds)
        throws Exception {
    log.trace("createHttpClient()");

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

    if ("https".equalsIgnoreCase(OpMonitoringSystemProperties.getOpMonitorDaemonScheme())) {
        sfr.register("https", createSSLSocketFactory(authKey));
    } else {
        sfr.register("http", PlainConnectionSocketFactory.INSTANCE);
    }

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(sfr.build());
    cm.setMaxTotal(clientMaxTotalConnections);
    cm.setDefaultMaxPerRoute(clientMaxConnectionsPerRoute);
    cm.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).build());

    RequestConfig.Builder rb = RequestConfig.custom().setConnectTimeout(connectionTimeoutMilliseconds)
            .setConnectionRequestTimeout(connectionTimeoutMilliseconds)
            .setSocketTimeout(socketTimeoutMilliseconds);

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

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

    return cb.build();
}

From source file:eu.itesla_project.histodb.client.impl.HistoDbHttpClientImpl.java

private synchronized CloseableHttpClient getHttpclient(HistoDbConfig config) {
    if (httpClient == null) {
        try {//from  w  w w  .  jav a  2s  . com
            ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
            } };
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
            Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", plainsf).register("https", sslsf).build();
            PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);
            cm.setDefaultMaxPerRoute(10);
            cm.setMaxTotal(20);
            HttpClientBuilder httpClientBuilder = HttpClients.custom().setConnectionManager(cm);
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(
                    new AuthScope(new HttpHost(config.getConnectionParameters().getHost(),
                            config.getConnectionParameters().getPort())),
                    new UsernamePasswordCredentials(config.getConnectionParameters().getUserName(),
                            config.getConnectionParameters().getPassword()));
            if (config.getProxyParameters() != null) {
                HttpHost proxy = new HttpHost(config.getProxyParameters().getHost(),
                        config.getProxyParameters().getPort());
                credentialsProvider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials(
                        config.getProxyParameters().getUserName(), config.getProxyParameters().getPassword()));
                httpClientBuilder.setProxy(proxy);
            }
            httpClient = httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider).build();
        } catch (KeyManagementException | NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
    return httpClient;
}

From source file:sachin.spider.WebSpider.java

/**
 *
 * @param config/*w  w w  .  j a  v  a  2 s .  c  o  m*/
 * @param latch
 */
@SuppressWarnings("deprecation")
public void setValues(SpiderConfig config, CountDownLatch latch) {
    try {
        this.config = config;
        this.latch = latch;
        HttpClientBuilder builder = HttpClientBuilder.create();
        builder.setUserAgent(config.getUserAgentString());
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

            @Override
            public boolean isTrusted(java.security.cert.X509Certificate[] xcs, String string)
                    throws java.security.cert.CertificateException {
                return true;
            }
        }).build();
        builder.setSslcontext(sslContext);
        HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                hostnameVerifier);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory).build();
        cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        cm.setDefaultMaxPerRoute(config.getTotalSpiders() * 2);
        cm.setMaxTotal(config.getTotalSpiders() * 2);
        if (config.isAuthenticate()) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(config.getUsername(), config.getPassword()));
            httpclient = HttpClients.custom().setUserAgent(config.getUserAgentString())
                    .setDefaultCredentialsProvider(credentialsProvider).setConnectionManager(cm).build();

        } else {
            httpclient = HttpClients.custom().setConnectionManager(cm).setUserAgent(config.getUserAgentString())
                    .build();
        }
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
        Logger.getLogger(WebSpider.class.getName()).log(Level.SEVERE, null, ex);
    }
}