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:microsoft.exchange.webservices.data.core.ExchangeServiceBase.java

private void initializeHttpPoolingClient() {
    Registry<ConnectionSocketFactory> registry = createConnectionSocketFactoryRegistry();
    PoolingHttpClientConnectionManager httpConnectionManager = new PoolingHttpClientConnectionManager(registry);
    httpConnectionManager.setMaxTotal(maximumPoolingConnections);
    httpConnectionManager.setDefaultMaxPerRoute(maximumPoolingConnections);
    AuthenticationStrategy authStrategy = new CookieProcessingTargetAuthenticationStrategy();

    httpPoolingClient = HttpClients.custom().setConnectionManager(httpConnectionManager)
            .setTargetAuthenticationStrategy(authStrategy).build();
}

From source file:com.couchbase.jdbc.core.ProtocolImpl.java

public ProtocolImpl(String url, Properties props) {

    if (props.containsKey(ConnectionParameters.USER)) {
        user = props.getProperty(ConnectionParameters.USER);
    }/*  w w  w.  j a  v  a  2 s .c o m*/
    if (props.containsKey(ConnectionParameters.PASSWORD)) {
        password = props.getProperty(ConnectionParameters.PASSWORD);
    }
    if (props.containsKey("credentials")) {
        credentials = props.getProperty("credentials");
    }
    this.url = url;
    setConnectionTimeout(props.getProperty(ConnectionParameters.CONNECTION_TIMEOUT));
    if (props.containsKey(ConnectionParameters.SCAN_CONSISTENCY)) {
        scanConsistency = props.getProperty(ConnectionParameters.SCAN_CONSISTENCY);
    }

    requestConfig = RequestConfig.custom().setConnectionRequestTimeout(0).setConnectTimeout(connectTimeout)
            .setSocketTimeout(connectTimeout).build();

    if (props.containsKey(ConnectionParameters.ENABLE_SSL)
            && props.getProperty(ConnectionParameters.ENABLE_SSL).equals("true")) {
        SSLContextBuilder builder = SSLContexts.custom();

        try {
            builder.loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            });
            SSLContext sslContext = builder.build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                    new X509HostnameVerifier() {
                        @Override
                        public void verify(String host, SSLSocket ssl) throws IOException {
                        }

                        @Override
                        public void verify(String host, X509Certificate cert) throws SSLException {
                        }

                        @Override
                        public void verify(String host, String[] cns, String[] subjectAlts)
                                throws SSLException {
                        }

                        @Override
                        public boolean verify(String s, SSLSession sslSession) {
                            return true;
                        }
                    });

            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory>create().register("https", sslsf).build();
            HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(requestConfig)
                    .build();
            ssl = true;

        } catch (Exception ex) {
            logger.error("Error creating ssl client", ex);
        }

    } else {
        httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
    }
}

From source file:org.drugis.addis.config.MainConfig.java

@Bean
public HttpClient httpClient(RequestConfig requestConfig) throws KeyStoreException, IOException,
        CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException {
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(new FileInputStream(KEYSTORE_PATH), KEYSTORE_PASSWORD.toCharArray());
    String ADDIS_LOCAL = System.getenv("ADDIS_LOCAL");

    SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadKeyMaterial(keyStore,
            KEYSTORE_PASSWORD.toCharArray());
    if (ADDIS_LOCAL != null) {
        String TRUSTSTORE_PATH = WebConstants.loadSystemEnv("TRUSTSTORE_PATH");
        sslContextBuilder.loadTrustMaterial(new File(TRUSTSTORE_PATH));
    }/*  w  w  w .  j a  v  a 2  s .co  m*/
    sslContextBuilder.build();
    SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(
            sslContextBuilder.build());

    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", connectionSocketFactory).register("http", new PlainConnectionSocketFactory())
            .build();
    HttpClientConnectionManager clientConnectionManager = new PoolingHttpClientConnectionManager(registry);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    return httpClientBuilder.setConnectionManager(clientConnectionManager).setMaxConnTotal(20)
            .setMaxConnPerRoute(2).setDefaultRequestConfig(requestConfig).build();
}

From source file:com.crosstreelabs.cognitio.gumshoe.transport.HttpTransport.java

private void buildHttpClient() {
    requestConfig = RequestConfig.custom().setExpectContinueEnabled(false).setCookieSpec(CookieSpecs.DEFAULT)
            .setRedirectsEnabled(false).setSocketTimeout(5000).setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000).setStaleConnectionCheckEnabled(true).build();

    RegistryBuilder<ConnectionSocketFactory> connRegistryBuilder = RegistryBuilder.create();
    connRegistryBuilder.register("http", PlainConnectionSocketFactory.INSTANCE);
    try { // Fixing: https://code.google.com/p/crawler4j/issues/detail?id=174
          // By always trusting the ssl certificate
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            @Override//from   w w w  .  j a v  a2  s  .  c o  m
            public boolean isTrusted(final X509Certificate[] chain, String authType) {
                return true;
            }
        }).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        connRegistryBuilder.register("https", sslsf);
    } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException e) {
        LOGGER.warn("Exception thrown while trying to register https");
        LOGGER.debug("Stacktrace", e);
    }

    Registry<ConnectionSocketFactory> connRegistry = connRegistryBuilder.build();
    connectionManager = new PoolingHttpClientConnectionManager(connRegistry);
    connectionManager.setMaxTotal(5);
    connectionManager.setDefaultMaxPerRoute(5);

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setDefaultRequestConfig(requestConfig);
    clientBuilder.setConnectionManager(connectionManager);
    clientBuilder.setUserAgent("Cognitio");

    httpClient = clientBuilder.build();
}

From source file:cn.org.once.cstack.utils.JSONClient.java

public CloseableHttpClient buildSecureHttpClient() throws IOException {
    if (isUnixSocket) {
        HttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(
                getUnixSocketFactoryRegistry());
        HttpClientBuilder builder = HttpClients.custom();
        builder.setConnectionManager(manager);
        return builder.build();
    } else if (certPathDirectory != null && !certPathDirectory.isEmpty()) {
        org.apache.http.impl.client.HttpClientBuilder builder = HttpClients.custom();
        HttpClientConnectionManager manager = getConnectionFactory(this.certPathDirectory, 10);
        builder.setConnectionManager(manager);
        return builder.build();
    } else {// www.  jav a  2s.c om
        return HttpClients.createDefault();
    }
}

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);/*from ww w.  j  a  va 2  s .co  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.jasig.cas.util.http.SimpleHttpClientFactoryBean.java

/**
 * Build a HTTP client based on the current properties.
 *
 * @return the built HTTP client/*  w  w  w .j  a v a 2 s. com*/
 */
private CloseableHttpClient buildHttpClient() {
    try {

        final ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
        final LayeredConnectionSocketFactory sslsf = this.sslSocketFactory;

        final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", plainsf).register("https", sslsf).build();

        final PoolingHttpClientConnectionManager connMgmr = new PoolingHttpClientConnectionManager(registry);
        connMgmr.setMaxTotal(this.maxPooledConnections);
        connMgmr.setDefaultMaxPerRoute(this.maxConnectionsPerRoute);

        final HttpHost httpHost = new HttpHost(InetAddress.getLocalHost());
        final HttpRoute httpRoute = new HttpRoute(httpHost);
        connMgmr.setMaxPerRoute(httpRoute, MAX_CONNECTIONS_PER_ROUTE);

        final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(this.readTimeout)
                .setConnectTimeout(this.connectionTimeout).setConnectionRequestTimeout(this.connectionTimeout)
                .setStaleConnectionCheckEnabled(true).setCircularRedirectsAllowed(this.circularRedirectsAllowed)
                .setRedirectsEnabled(this.redirectsEnabled).setAuthenticationEnabled(this.authenticationEnabled)
                .build();

        final HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connMgmr)
                .setDefaultRequestConfig(requestConfig).setSSLSocketFactory(sslsf)
                .setSSLHostnameVerifier(this.hostnameVerifier).setRedirectStrategy(this.redirectionStrategy)
                .setDefaultCredentialsProvider(this.credentialsProvider).setDefaultCookieStore(this.cookieStore)
                .setConnectionReuseStrategy(this.connectionReuseStrategy)
                .setConnectionBackoffStrategy(this.connectionBackoffStrategy)
                .setServiceUnavailableRetryStrategy(this.serviceUnavailableRetryStrategy)
                .setProxyAuthenticationStrategy(this.proxyAuthenticationStrategy)
                .setDefaultHeaders(this.defaultHeaders).useSystemProperties();

        return builder.build();

    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}

From source file:de.codecentric.boot.admin.zuul.filters.route.SimpleHostRoutingFilter.java

protected PoolingHttpClientConnectionManager newConnectionManager() {
    try {//from w  ww. j  a  v  a2 s.c  om
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                    throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
                    throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } }, new SecureRandom());

        RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder
                .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE);
        if (this.sslHostnameValidationEnabled) {
            registryBuilder.register("https", new SSLConnectionSocketFactory(sslContext));
        } else {
            registryBuilder.register("https",
                    new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE));
        }
        final Registry<ConnectionSocketFactory> registry = registryBuilder.build();

        this.connectionManager = new PoolingHttpClientConnectionManager(registry);
        this.connectionManager.setMaxTotal(this.hostProperties.getMaxTotalConnections());
        this.connectionManager.setDefaultMaxPerRoute(this.hostProperties.getMaxPerRouteConnections());
        return this.connectionManager;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.jboss.as.test.integration.management.http.HttpDeploymentUploadUnitTestCase.java

private CloseableHttpClient createHttpClient() {
    try {/*w w w.ja  v  a2  s  .c o  m*/
        final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory()).build();
        final CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                new AuthScope(managementClient.getMgmtAddress(), managementClient.getMgmtPort()),
                new UsernamePasswordCredentials(Authentication.USERNAME, Authentication.PASSWORD));
        return HttpClientBuilder.create().setConnectionManager(new PoolingHttpClientConnectionManager(registry))
                .setDefaultCredentialsProvider(credsProvider).build();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.thinkbiganalytics.rest.JerseyRestClient.java

public JerseyRestClient(JerseyClientConfig config) {
    useConnectionPooling = config.isUseConnectionPooling();
    SSLContext sslContext = null;
    if (config.isHttps()) {
        SslConfigurator sslConfig = null;
        byte[] keyStoreFile = null;
        byte[] truststoreFile = null;

        try {/*w w w  .j  av  a 2s .  c  om*/
            if (StringUtils.isNotBlank(config.getKeystorePath())) {
                InputStream keystore = JerseyRestClient.class.getResourceAsStream(config.getKeystorePath());
                if (keystore != null) {
                    keyStoreFile = ByteStreams.toByteArray(keystore);
                }
            }
        } catch (IOException e) {
        }

        try {
            if (StringUtils.isNotBlank(config.getTruststorePath())) {
                InputStream truststore = JerseyRestClient.class.getResourceAsStream(config.getTruststorePath());
                if (truststore != null) {
                    truststoreFile = ByteStreams.toByteArray(truststore);
                }
            }
        } catch (IOException e) {
        }

        if (keyStoreFile != null) {
            sslConfig = SslConfigurator.newInstance()
                    .trustStoreBytes(truststoreFile != null ? truststoreFile : keyStoreFile)
                    .trustStorePassword(config.getTruststorePassword() != null ? config.getTruststorePassword()
                            : config.getKeystorePassword())
                    .trustStoreType(config.getTrustStoreType())
                    .keyStoreBytes(keyStoreFile != null ? keyStoreFile : truststoreFile)
                    .keyStorePassword(config.getKeystorePassword());
        } else {
            sslConfig = SslConfigurator.newInstance()
                    .keyStoreFile(config.getKeystorePath() == null ? config.getTruststorePath()
                            : config.getKeystorePath())
                    .keyStorePassword(config.getKeystorePassword() == null ? config.getTruststorePassword()
                            : config.getKeystorePassword())
                    .trustStoreFile(config.getTruststorePath() == null ? config.getKeystorePath()
                            : config.getTruststorePath())
                    .trustStorePassword(config.getTruststorePassword() == null ? config.getKeystorePassword()
                            : config.getTruststorePassword())
                    .trustStoreType(config.getTrustStoreType());
        }

        try {
            sslContext = sslConfig.createSSLContext();
        } catch (Exception e) {
            log.error("ERROR creating CLient SSL Context.  " + e.getMessage()
                    + " Falling back to Jersey Client without SSL.  Rest Integration with '" + config.getUrl()
                    + "'  will probably not work until this is fixed!");
        }
    }

    ClientConfig clientConfig = new ClientConfig();

    // Add in Timeouts if configured.  Values are in milliseconds
    if (config.getReadTimeout() != null) {
        clientConfig.property(ClientProperties.READ_TIMEOUT, config.getReadTimeout());
    }
    if (config.getConnectTimeout() != null) {
        clientConfig.property(ClientProperties.CONNECT_TIMEOUT, config.getConnectTimeout());
    }

    if (useConnectionPooling) {

        PoolingHttpClientConnectionManager connectionManager = null;
        if (sslContext != null) {

            HostnameVerifier defaultHostnameVerifier = new DefaultHostnameVerifier();

            LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                    defaultHostnameVerifier);

            final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslSocketFactory).build();

            connectionManager = new PoolingHttpClientConnectionManager(registry);
        } else {
            connectionManager = new PoolingHttpClientConnectionManager();
        }
        connectionManager.setDefaultMaxPerRoute(100); // # of connections allowed per host/address
        connectionManager.setMaxTotal(200); // number of connections allowed in total

        clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, connectionManager);
        HttpUrlConnectorProvider connectorProvider = new HttpUrlConnectorProvider();
        clientConfig.connectorProvider(connectorProvider);

    }

    clientConfig.register(MultiPartFeature.class);

    // allow derived classes to modify the client config
    extendClientConfig(clientConfig);

    if (sslContext != null) {
        log.info("Created new Jersey Client with SSL connecting to {} ", config.getUrl());
        client = new JerseyClientBuilder().withConfig(clientConfig).sslContext(sslContext).build();
    } else {
        log.info("Created new Jersey Client without SSL connecting to {} ", config.getUrl());
        client = JerseyClientBuilder.createClient(clientConfig);
    }

    // Register Jackson for the internal mapper
    objectMapper = new JacksonObjectMapperProvider().getContext(null);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    //register custom features
    registerClientFeatures(client);

    // Configure authentication
    if (StringUtils.isNotBlank(config.getUsername())) {
        HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(config.getUsername(),
                config.getPassword());
        client.register(feature);
    }
    this.uri = config.getUrl();
    this.username = config.getUsername();

    if (StringUtils.isNotBlank(config.getHost()) && !HOST_NOT_SET_VALUE.equals(config.getHost())) {
        this.isHostConfigured = true;
    } else {
        log.info("Jersey Rest Client not initialized.  Host name is Not set!!");
    }
}