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:org.neo4j.ogm.drivers.http.driver.HttpDriver.java

private synchronized CloseableHttpClient httpClient() {

    if (httpClient == null) { // most of the time this will be false, branch-prediction will be very fast and the lock released immediately

        try {/*from  w w  w.  ja v a2s. c  o  m*/
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

            SSLContext sslContext = SSLContext.getDefault();

            if (configuration.getTrustStrategy() != null) {

                if (configuration.getTrustStrategy().equals("ACCEPT_UNSIGNED")) {
                    sslContext = new SSLContextBuilder().loadTrustMaterial(null, (arg0, arg1) -> true).build();

                    LOGGER.warn("Certificate validation has been disabled");
                }
            }

            // setup the default or custom ssl context
            httpClientBuilder.setSSLContext(sslContext);

            HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();

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

            // allows multi-threaded use
            PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
                    socketFactoryRegistry);

            Integer connectionPoolSize = configuration.getConnectionPoolSize();

            connectionManager.setMaxTotal(connectionPoolSize);
            connectionManager.setDefaultMaxPerRoute(connectionPoolSize);

            httpClientBuilder.setConnectionManager(connectionManager);

            httpClient = httpClientBuilder.build();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    return httpClient;
}

From source file:fr.treeptik.cloudunit.docker.JSONClient.java

private static HttpClientConnectionManager getConnectionFactory(String certPath, int maxConnections)
        throws IOException {
    PoolingHttpClientConnectionManager ret = new PoolingHttpClientConnectionManager(
            getSslFactoryRegistry(certPath));
    ret.setDefaultMaxPerRoute(maxConnections);
    return ret;/*from w  ww  .j av a 2s .com*/
}

From source file:de.tudarmstadt.ukp.shibhttpclient.ShibHttpClient.java

/**
 * Create a new client (with an explicit proxy and possibly transparent authentication)
 * /*from w  w w  .ja v  a 2  s  .  c  o  m*/
 * @param aIdpUrl
 *            the URL of the IdP. Should probably be something ending in "/SAML2/SOAP/ECP"
 * @param aUsername
 *            the user name to log into the IdP.
 * @param aPassword
 *            the password to log in to the IdP.
 * @param aProxy
 *            if not {@code null}, use this proxy instead of the default system proxy (if any)
 * @param anyCert
 *            if {@code true}, accept any certificate from any remote host. Otherwise,
 *            certificates need to be installed in the JRE.
 * @param transparentAuth
 *            if {@code true} (default), add a HttpRequestPostProcessor to transparently 
 *            authenticate. Otherwise, you must handle the authentication process yourself.
 */
public ShibHttpClient(String aIdpUrl, String aUsername, String aPassword, HttpHost aProxy, boolean anyCert,
        boolean transparentAuth) {

    setIdpUrl(aIdpUrl);
    setUsername(aUsername);
    setPassword(aPassword);

    // Use a pooling connection manager, because we'll have to do a call out to the IdP
    // while still being in a connection with the SP
    PoolingHttpClientConnectionManager connMgr;
    if (anyCert) {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory>create().register("http", new PlainConnectionSocketFactory())
                    .register("https", new SSLConnectionSocketFactory(builder.build(),
                            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER))
                    .build();
            connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        } catch (GeneralSecurityException e) {
            // There shouldn't be any of these exceptions, because we do not use an actual
            // keystore
            throw new IllegalStateException(e);
        }
    } else {
        connMgr = new PoolingHttpClientConnectionManager();
    }
    connMgr.setMaxTotal(10);
    connMgr.setDefaultMaxPerRoute(5);

    // The client needs to remember the auth cookie
    cookieStore = new BasicCookieStore();
    RequestConfig globalRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
            .build();

    // Let's throw all common client elements into one builder object
    HttpClientBuilder customClient = HttpClients.custom().setConnectionManager(connMgr)
            // The client needs to remember the auth cookie
            .setDefaultRequestConfig(globalRequestConfig).setDefaultCookieStore(cookieStore)
            // Add the ECP/PAOS headers - needs to be added first so the cookie we get from
            // the authentication can be handled by the RequestAddCookies interceptor later
            .addInterceptorFirst(new HttpRequestPreprocessor());

    // Automatically log into IdP if transparent Shibboleth authentication handling is requested (default)
    if (transparentAuth) {
        customClient = customClient.addInterceptorFirst(new HttpRequestPostprocessor());
    }

    // Build the client with/without proxy settings 
    if (aProxy == null) {
        // use the proxy settings of the JVM, if specified 
        client = customClient.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()))
                .build();
    } else {
        // use the explicit proxy
        client = customClient.setProxy(aProxy).build();
    }

    parserPool = new BasicParserPool();
    parserPool.setNamespaceAware(true);
}

From source file:com.aliyun.oss.common.comm.DefaultServiceClient.java

protected HttpClientConnectionManager createHttpClientConnectionManager() {
    SSLContext sslContext = null;
    try {// w w w .  j  a  va2  s  .  c o m
        sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }

        }).build();

    } catch (Exception e) {
        throw new ClientException(e.getMessage());
    }

    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
            NoopHostnameVerifier.INSTANCE);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register(Protocol.HTTP.toString(), PlainConnectionSocketFactory.getSocketFactory())
            .register(Protocol.HTTPS.toString(), sslSocketFactory).build();

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry);
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnections());
    connectionManager.setMaxTotal(config.getMaxConnections());
    connectionManager.setValidateAfterInactivity(config.getValidateAfterInactivity());
    connectionManager.setDefaultSocketConfig(
            SocketConfig.custom().setSoTimeout(config.getSocketTimeout()).setTcpNoDelay(true).build());
    if (config.isUseReaper()) {
        IdleConnectionReaper.setIdleConnectionTime(config.getIdleConnectionTime());
        IdleConnectionReaper.registerConnectionManager(connectionManager);
    }
    return connectionManager;
}

From source file:org.springframework.extensions.webscripts.connector.RemoteClient.java

public void init() {
    RemoteConfigElement remoteConfig = (RemoteConfigElement) configService.getConfig("Remote")
            .getConfigElement("remote");

    SSLConfigDescriptor sslConfigDescriptor = null;
    if (remoteConfig != null) {
        sslConfigDescriptor = remoteConfig.getSSLConfigDescriptor();
    }/*  w  w  w  .  j a v a  2 s . co  m*/

    if (sslConfigDescriptor != null && sslConfigDescriptor.getSocketFactoryRegistry() != null) {
        connectionManager = new PoolingHttpClientConnectionManager(
                sslConfigDescriptor.getSocketFactoryRegistry());
    } else {
        connectionManager = new PoolingHttpClientConnectionManager();
    }

    connectionManager.setMaxTotal(poolSize);
    connectionManager.setDefaultMaxPerRoute(poolSize);
}

From source file:com.jive.myco.seyren.core.util.graphite.GraphiteHttpClient.java

private HttpClientConnectionManager createConnectionManager() {
    PoolingHttpClientConnectionManager manager;
    if ("https".equals(graphiteScheme) && !StringUtils.isEmpty(graphiteKeyStore)
            && !StringUtils.isEmpty(graphiteKeyStorePassword) && !StringUtils.isEmpty(graphiteTrustStore)) {
        try {/*from   w  w w. j ava  2s. co  m*/
            KeyStore keyStore = loadKeyStore(graphiteKeyStore, graphiteKeyStorePassword);
            KeyStore trustStore = loadKeyStore(graphiteTrustStore, null);

            KeyManagerFactory keyManagerFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, graphiteKeyStorePassword.toCharArray());
            KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

            TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(trustStore);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(keyManagers, trustManagers, null);

            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);

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

            manager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        } catch (Exception e) {
            LOGGER.warn("A problem occurred when building SSLConnectionSocketFactory", e);
            throw new RuntimeException("Error while building SSLConnectionSocketFactory", e);
        }
    } else {
        manager = new PoolingHttpClientConnectionManager();
    }

    manager.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE);
    return manager;
}

From source file:ch.cyberduck.core.http.HttpConnectionPoolBuilder.java

protected PoolingHttpClientConnectionManager pool(final Registry<ConnectionSocketFactory> registry) {
    if (log.isDebugEnabled()) {
        log.debug(String.format("Setup connection pool with registry %s", registry));
    }/*  ww  w . j  a  v  a  2s. c  o m*/
    final PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(registry);
    manager.setMaxTotal(preferences.getInteger("http.connections.total"));
    manager.setDefaultMaxPerRoute(preferences.getInteger("http.connections.route"));
    manager.setValidateAfterInactivity(5000);
    return manager;
}

From source file:nl.uva.mediamosa.impl.MediaMosaImpl.java

private HttpClient getHttpClient() {
    HttpClientBuilder b = HttpClientBuilder.create().setDefaultCookieStore(httpCookieStore);

    SSLContext sslContext = null;
    try {/*from  ww  w .j a  v a2s.  c  o  m*/
        sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        log.warn("Unexpected error occurerd while setting up SSL context", e);
    }
    b.setSSLContext(sslContext);

    HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();

    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();
    // allows multi-threaded use
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    b.setConnectionManager(connMgr);

    return b.build();
}

From source file:org.infinispan.server.test.rest.security.RESTCertSecurityTest.java

public static CloseableHttpClient securedClient(String alias) {
    try {/*from  w w  w  . j  a  v  a2 s  .  c o  m*/
        SSLContext ctx = SSLContext.getInstance("TLS");
        JBossJSSESecurityDomain jsseSecurityDomain = new JBossJSSESecurityDomain("client_cert_auth");
        jsseSecurityDomain.setKeyStorePassword("changeit");
        ClassLoader tccl = Thread.currentThread().getContextClassLoader();
        URL keystore = tccl.getResource("client.keystore");
        jsseSecurityDomain.setKeyStoreURL(keystore.getPath());
        jsseSecurityDomain.setClientAlias(alias);
        jsseSecurityDomain.reloadKeyAndTrustStore();
        KeyManager[] keyManagers = jsseSecurityDomain.getKeyManagers();
        TrustManager[] trustManagers = jsseSecurityDomain.getTrustManagers();
        ctx.init(keyManagers, trustManagers, null);
        X509HostnameVerifier verifier = new X509HostnameVerifier() {

            @Override
            public void verify(String s, SSLSocket sslSocket) throws IOException {
            }

            @Override
            public void verify(String s, X509Certificate x509Certificate) throws SSLException {
            }

            @Override
            public void verify(String s, String[] strings, String[] strings1) throws SSLException {
            }

            @Override
            public boolean verify(String string, SSLSession ssls) {
                return true;
            }
        };
        ConnectionSocketFactory sslssf = new SSLConnectionSocketFactory(ctx, verifier);//SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ConnectionSocketFactory plainsf = new PlainConnectionSocketFactory();
        Registry<ConnectionSocketFactory> sr = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", plainsf).register("https", sslssf).build();
        HttpClientConnectionManager pcm = new PoolingHttpClientConnectionManager(sr);
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(pcm).build();

        return httpClient;
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}