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.kuali.rice.ksb.messaging.serviceconnectors.DefaultHttpClientConfigurer.java

/**
 * Builds the HttpClientConnectionManager.
 *
 * <p>Note that this calls {@link #buildSslConnectionSocketFactory()} and registers the resulting {@link SSLConnectionSocketFactory}
 * (if non-null) with its socket factory registry.</p>
 *
 * @return the HttpClientConnectionManager
 *//*from w  w  w .j  a  va  2s  .c o  m*/
protected HttpClientConnectionManager buildConnectionManager() {
    PoolingHttpClientConnectionManager poolingConnectionManager = null;

    SSLConnectionSocketFactory sslConnectionSocketFactory = buildSslConnectionSocketFactory();
    if (sslConnectionSocketFactory != null) {
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create().register("https", sslConnectionSocketFactory)
                .register("http", new PlainConnectionSocketFactory()).build();
        poolingConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    } else {
        poolingConnectionManager = new PoolingHttpClientConnectionManager();
    }

    // Configure the connection manager
    poolingConnectionManager
            .setMaxTotal(MAX_TOTAL_CONNECTIONS.getValueOrDefault(DEFAULT_MAX_TOTAL_CONNECTIONS));

    // By default we'll set the max connections per route (essentially that means per host for us) to the max total
    poolingConnectionManager
            .setDefaultMaxPerRoute(MAX_TOTAL_CONNECTIONS.getValueOrDefault(DEFAULT_MAX_TOTAL_CONNECTIONS));

    SocketConfig.Builder socketConfigBuilder = SocketConfig.custom();
    socketConfigBuilder.setSoTimeout(SO_TIMEOUT.getValueOrDefault(DEFAULT_SOCKET_TIMEOUT));

    Integer soLinger = SO_LINGER.getValue();
    if (soLinger != null) {
        socketConfigBuilder.setSoLinger(soLinger);
    }

    Boolean isTcpNoDelay = TCP_NODELAY.getValue();
    if (isTcpNoDelay != null) {
        socketConfigBuilder.setTcpNoDelay(isTcpNoDelay);
    }

    poolingConnectionManager.setDefaultSocketConfig(socketConfigBuilder.build());

    ConnectionConfig.Builder connectionConfigBuilder = ConnectionConfig.custom();

    Integer sendBuffer = SO_SNDBUF.getValue();
    Integer receiveBuffer = SO_RCVBUF.getValue();

    // if either send or recieve buffer size is set, we'll set the buffer size to whichever is greater
    if (sendBuffer != null || receiveBuffer != null) {
        Integer bufferSize = -1;
        if (sendBuffer != null) {
            bufferSize = sendBuffer;
        }

        if (receiveBuffer != null && receiveBuffer > bufferSize) {
            bufferSize = receiveBuffer;
        }

        connectionConfigBuilder.setBufferSize(bufferSize);
    }

    String contentCharset = HTTP_CONTENT_CHARSET.getValue();
    if (contentCharset != null) {
        connectionConfigBuilder.setCharset(Charset.forName(contentCharset));
    }

    poolingConnectionManager.setDefaultConnectionConfig(connectionConfigBuilder.build());

    return poolingConnectionManager;
}

From source file:eu.europa.ec.markt.dss.validation102853.https.CommonDataLoader.java

private HttpClientConnectionManager getConnectionManager() throws DSSException {

    LOG.debug("HTTPS TrustStore undefined, using default");
    RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistryBuilder = RegistryBuilder.create();
    socketFactoryRegistryBuilder = setConnectionManagerSchemeHttp(socketFactoryRegistryBuilder);
    socketFactoryRegistryBuilder = setConnectionManagerSchemeHttps(socketFactoryRegistryBuilder);

    final HttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistryBuilder.build());
    return connectionManager;
}

From source file:com.spectralogic.ds3client.networking.NetworkClientImpl.java

private static HttpClientConnectionManager createConnectionManager(
        final Registry<ConnectionSocketFactory> socketFactoryRegistry) {
    final PoolingHttpClientConnectionManager connectionManager;
    if (socketFactoryRegistry != null) {
        connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    } else {/*  w  w w  . j  a  v a 2s .co  m*/
        connectionManager = new PoolingHttpClientConnectionManager();
    }

    connectionManager.setDefaultMaxPerRoute(MAX_CONNECTION_PER_ROUTE);
    connectionManager.setMaxTotal(MAX_CONNECTION_TOTAL);
    return connectionManager;
}

From source file:de.elomagic.maven.http.HTTPMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    try {/*ww w.  j  av a2s. c  om*/
        Executor executor;

        if (httpsInsecure) {
            getLog().info("Accepting unsecure HTTPS connections.");
            try {
                SSLContextBuilder builder = new SSLContextBuilder();
                builder.loadTrustMaterial(null, new TrustAllStrategy());
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());

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

                PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
                        sfr);
                connectionManager.setDefaultMaxPerRoute(100);
                connectionManager.setMaxTotal(200);
                connectionManager.setValidateAfterInactivity(1000);

                HttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connectionManager)
                        .build();

                executor = Executor.newInstance(httpClient);
            } catch (Exception ex) {
                throw new Exception("Unable to setup HTTP client for unstrusted connections.", ex);
            }
        } else {
            executor = Executor.newInstance();
        }

        Settings settings = session.getSettings();
        if (StringUtils.isNotBlank(serverId)) {
            Server server = settings.getServer(serverId);
            if (server == null) {
                throw new Exception("Server ID \"" + serverId + "\" not found in your Maven settings.xml");
            }
            getLog().debug("ServerId: " + serverId);
            executor.auth(server.getUsername(), server.getPassword());
        }

        Request request = createRequestMethod();

        request.setHeader("Accept", accept);

        if (httpHeaders != null) {
            for (Entry<String, String> entry : httpHeaders.entrySet()) {
                request.addHeader(entry.getKey(), entry.getValue());
            }
        }

        if (formParams != null) {
            Form form = Form.form();
            for (Entry<String, String> entry : formParams.entrySet()) {
                form.add(entry.getKey(), entry.getValue());
            }
        }

        if (fromFile != null) {
            if (!fromFile.exists()) {
                throw new MojoExecutionException("From file \"" + fromFile + "\" doesn't exist.");
            }

            if (StringUtils.isBlank(contentType)) {
                contentType = Files.probeContentType(fromFile.toPath());
            }

            getLog().debug("From file: " + fromFile);
            getLog().debug("Upload file size: "
                    + FileUtils.byteCountToDisplaySize(new Long(fromFile.length()).intValue()));
            getLog().debug("Content type: " + contentType);

            if (StringUtils.isBlank(contentType)) {
                request.body(new FileEntity(fromFile));
            } else {
                request.body(new FileEntity(fromFile, ContentType.create(contentType)));
            }
        }

        getLog().info(method + " " + url);

        Response response = executor.execute(request);
        handleResponse(response);
    } catch (Exception ex) {
        getLog().error(ex);
        if (failOnError) {
            throw new MojoExecutionException(ex.getMessage(), ex);
        } else {
            getLog().info("Fail on error is disabled. Continue execution.");
        }
    }

}

From source file:org.apache.hadoop.gateway.shell.Hadoop.java

private CloseableHttpClient createClient(ClientContext clientContext) throws GeneralSecurityException {

    // SSL/*from  w w  w.  j  ava2  s .  c  o  m*/
    HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
    TrustStrategy trustStrategy = null;
    if (clientContext.connection().secure()) {
        hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();
    } else {
        trustStrategy = TrustSelfSignedStrategy.INSTANCE;
        System.out.println("**************** WARNING ******************\n"
                + "This is an insecure client instance and may\n"
                + "leave the interactions subject to a man in\n" + "the middle attack. Please use the login()\n"
                + "method instead of loginInsecure() for any\n" + "sensitive or production usecases.\n"
                + "*******************************************");
    }

    KeyStore trustStore = getTrustStore();
    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore, trustStrategy).build();
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", new SSLConnectionSocketFactory(sslContext, hostnameVerifier)).build();

    // Pool
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
    connectionManager.setMaxTotal(clientContext.pool().maxTotal());
    connectionManager.setDefaultMaxPerRoute(clientContext.pool().defaultMaxPerRoute());

    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setBufferSize(clientContext.connection().bufferSize()).build();
    connectionManager.setDefaultConnectionConfig(connectionConfig);

    SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(clientContext.socket().keepalive())
            .setSoLinger(clientContext.socket().linger())
            .setSoReuseAddress(clientContext.socket().reuseAddress())
            .setSoTimeout(clientContext.socket().timeout()).setTcpNoDelay(clientContext.socket().tcpNoDelay())
            .build();
    connectionManager.setDefaultSocketConfig(socketConfig);

    // Auth
    URI uri = URI.create(clientContext.url());
    host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());

    CredentialsProvider credentialsProvider = null;
    if (clientContext.username() != null && clientContext.password() != null) {
        credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(host.getHostName(), host.getPort()),
                new UsernamePasswordCredentials(clientContext.username(), clientContext.password()));

        AuthCache authCache = new BasicAuthCache();
        BasicScheme authScheme = new BasicScheme();
        authCache.put(host, authScheme);
        context = new BasicHttpContext();
        context.setAttribute(org.apache.http.client.protocol.HttpClientContext.AUTH_CACHE, authCache);
    }
    return HttpClients.custom().setConnectionManager(connectionManager)
            .setDefaultCredentialsProvider(credentialsProvider).build();

}

From source file:ai.susi.server.ClientConnection.java

private static PoolingHttpClientConnectionManager getConnctionManager(boolean useAuthentication) {

    // allow opportunistic encryption if needed

    boolean trustAllCerts = !"none".equals(DAO.getConfig("httpsclient.trustselfsignedcerts", "peers"))
            && (!useAuthentication || "all".equals(DAO.getConfig("httpsclient.trustselfsignedcerts", "peers")));

    Registry<ConnectionSocketFactory> socketFactoryRegistry = null;
    if (trustAllCerts) {
        try {//from   ww w.  j  a va 2 s.  co  m
            SSLConnectionSocketFactory trustSelfSignedSocketFactory = new SSLConnectionSocketFactory(
                    new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
                    new TrustAllHostNameVerifier());
            socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", new PlainConnectionSocketFactory())
                    .register("https", trustSelfSignedSocketFactory).build();
        } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
            Log.getLog().warn(e);
        }
    }

    PoolingHttpClientConnectionManager cm = (trustAllCerts && socketFactoryRegistry != null)
            ? new PoolingHttpClientConnectionManager(socketFactoryRegistry)
            : new PoolingHttpClientConnectionManager();

    // twitter specific options
    cm.setMaxTotal(200);
    cm.setDefaultMaxPerRoute(20);
    HttpHost twitter = new HttpHost("twitter.com", 443);
    cm.setMaxPerRoute(new HttpRoute(twitter), 50);

    return cm;
}

From source file:co.cask.cdap.client.rest.RestStreamClient.java

private PoolingHttpClientConnectionManager createConnectionManager() {
    if (connectionRegistry != null) {
        return new PoolingHttpClientConnectionManager(connectionRegistry);
    } else {/*from  w w  w.j  av  a2  s. co  m*/
        return new PoolingHttpClientConnectionManager();
    }
}

From source file:com.bosch.cr.examples.inventorybrowser.server.CustomProxyServlet.java

private synchronized CloseableHttpClient getHttpClient() {
    if (httpClient == null) {
        try {/*from  w w w  .  j av a 2s . c  o  m*/
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

            // #### ONLY FOR TEST: Trust ANY certificate (self certified, any chain, ...)
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true)
                    .build();
            httpClientBuilder.setSSLContext(sslContext);

            // #### ONLY FOR TEST: Do NOT verify hostname
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
                    NoopHostnameVerifier.INSTANCE);

            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslConnectionSocketFactory).build();
            PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(
                    socketFactoryRegistry);
            httpClientBuilder.setConnectionManager(httpClientConnectionManager);

            if (getConfig().getProperty("http.proxyHost") != null) {
                httpClientBuilder.setProxy(new HttpHost(getConfig().getProperty("http.proxyHost"),
                        Integer.parseInt(getConfig().getProperty("http.proxyPort"))));
            }

            httpClient = httpClientBuilder.build();
        } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException ex) {
            throw new RuntimeException(ex);
        }
    }

    return httpClient;
}

From source file:org.thingsboard.server.msa.AbstractContainerTest.java

private static HttpComponentsClientHttpRequestFactory getRequestFactoryForSelfSignedCert() throws Exception {
    SSLContextBuilder builder = SSLContexts.custom();
    builder.loadTrustMaterial(null, (TrustStrategy) (chain, authType) -> true);
    SSLContext sslContext = builder.build();
    SSLConnectionSocketFactory sslSelfSigned = new SSLConnectionSocketFactory(sslContext,
            new X509HostnameVerifier() {
                @Override/*  w  w  w. ja v a2 s.  c o  m*/
                public void verify(String host, SSLSocket ssl) {
                }

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

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

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

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

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
    return new HttpComponentsClientHttpRequestFactory(httpClient);
}

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

private HttpClientConnectionManager getClientConnectionManager() throws Exception {
    RegistryBuilder<ConnectionSocketFactory> sfr = RegistryBuilder.create();

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

    if (SystemProperties.isSslEnabled()) {
        sfr.register("https", createSSLSocketFactory());
    }//  ww w  .j a v  a 2 s .  c o m

    SocketConfig.Builder sockBuilder = SocketConfig.custom().setTcpNoDelay(true);
    sockBuilder.setSoLinger(SystemProperties.getClientProxyHttpClientSoLinger());
    sockBuilder.setSoTimeout(SystemProperties.getClientProxyHttpClientTimeout());
    SocketConfig socketConfig = sockBuilder.build();

    PoolingHttpClientConnectionManager poolingManager = new PoolingHttpClientConnectionManager(sfr.build());
    poolingManager.setMaxTotal(SystemProperties.getClientProxyPoolTotalMaxConnections());
    poolingManager.setDefaultMaxPerRoute(SystemProperties.getClientProxyPoolDefaultMaxConnectionsPerRoute());
    poolingManager.setDefaultSocketConfig(socketConfig);
    poolingManager.setValidateAfterInactivity(
            SystemProperties.getClientProxyValidatePoolConnectionsAfterInactivityMs());

    return poolingManager;
}