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() 

Source Link

Usage

From source file:org.apache.manifoldcf.agents.output.opensearchserver.OpenSearchServerConnector.java

protected HttpClient getSession() throws ManifoldCFException {
    if (client == null) {
        connectionManager = new PoolingHttpClientConnectionManager();

        final int executorTimeout = 300000;
        final int socketTimeout = 60000;
        final int connectionTimeout = 60000;

        RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
                .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true)
                .setExpectContinueEnabled(true).setConnectTimeout(connectionTimeout)
                .setConnectionRequestTimeout(socketTimeout);

        HttpClientBuilder clientBuilder = HttpClients.custom().setConnectionManager(connectionManager)
                .setMaxConnTotal(1).disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build())
                .setRequestExecutor(new HttpRequestExecutor(executorTimeout)).setDefaultSocketConfig(
                        SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build());

        client = clientBuilder.build();/*from  w w w .j  a va2 s . c  o  m*/

    }
    expirationTime = System.currentTimeMillis() + EXPIRATION_INTERVAL;
    return client;
}

From source file:org.brutusin.rpc.client.http.HttpEndpoint.java

public HttpEndpoint(URI endpoint, Config cfg, HttpClientContextFactory clientContextFactory) {
    if (endpoint == null) {
        throw new IllegalArgumentException("Endpoint is required");
    }//w  w w . j  a  va 2s  .  com
    if (cfg == null) {
        cfg = new ConfigurationBuilder().build();
    }
    CacheConfig cacheConfig = CacheConfig.custom().setMaxCacheEntries(cfg.getMaxCacheEntries())
            .setMaxObjectSize(cfg.getMaxCacheObjectSize()).build();
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(1000 * cfg.getConnectTimeOutSeconds())
            .setSocketTimeout(1000 * cfg.getSocketTimeOutSeconds()).build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(cfg.getMaxConections());

    this.endpoint = endpoint;
    this.httpClient = CachingHttpClients.custom().setCacheConfig(cacheConfig)
            .setDefaultRequestConfig(requestConfig).setRetryHandler(new StandardHttpRequestRetryHandler())
            .setConnectionManager(cm).build();
    this.clientContextFactory = clientContextFactory;
    initPingThread(cfg.getPingSeconds());
}

From source file:org.bimserver.client.AbstractBimServerClientFactory.java

public void initHttpClient() {
    HttpClientBuilder builder = HttpClientBuilder.create();

    HttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    builder.setConnectionManager(connManager);

    //      builder.addInterceptorFirst(new HttpRequestInterceptor() {
    //         public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    //            if (!request.containsHeader("Accept-Encoding")) {
    //               request.addHeader("Accept-Encoding", "gzip");
    //            }
    //         }/*from   w  w w  .jav  a2  s  .  c  o  m*/
    //      });
    //
    //      builder.addInterceptorFirst(new HttpResponseInterceptor() {
    //         public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException {
    //            HttpEntity entity = response.getEntity();
    //            if (entity != null) {
    //               Header ceheader = entity.getContentEncoding();
    //               if (ceheader != null) {
    //                  HeaderElement[] codecs = ceheader.getElements();
    //                  for (int i = 0; i < codecs.length; i++) {
    //                     if (codecs[i].getName().equalsIgnoreCase("gzip")) {
    //                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
    //                        return;
    //                     }
    //                  }
    //               }
    //            }
    //         }
    //      });

    httpClient = builder.build();
}

From source file:org.apache.gobblin.http.ApacheHttpClient.java

private HttpClientConnectionManager getHttpConnManager(Config config) {
    HttpClientConnectionManager httpConnManager;

    String connMgrStr = config.getString(HTTP_CONN_MANAGER);
    switch (ConnManager.valueOf(connMgrStr.toUpperCase())) {
    case BASIC://  w w w. j  a  v a 2s .c  o m
        httpConnManager = new BasicHttpClientConnectionManager();
        break;
    case POOLING:
        PoolingHttpClientConnectionManager poolingConnMgr = new PoolingHttpClientConnectionManager();
        poolingConnMgr.setMaxTotal(config.getInt(POOLING_CONN_MANAGER_MAX_TOTAL_CONN));
        poolingConnMgr.setDefaultMaxPerRoute(config.getInt(POOLING_CONN_MANAGER_MAX_PER_CONN));
        httpConnManager = poolingConnMgr;
        break;
    default:
        throw new IllegalArgumentException(connMgrStr + " is not supported");
    }

    LOG.info("Using " + httpConnManager.getClass().getSimpleName());
    return httpConnManager;
}

From source file:org.kaaproject.kaa.server.appenders.rest.appender.RestLogAppender.java

@Override
protected void initFromConfiguration(LogAppenderDto appender, RestConfig configuration) {
    this.configuration = configuration;
    this.executor = Executors.newFixedThreadPool(configuration.getConnectionPoolSize());
    target = new HttpHost(configuration.getHost(), configuration.getPort(),
            configuration.getSsl() ? "https" : "http");
    HttpClientBuilder builder = HttpClients.custom();
    if (configuration.getUsername() != null && configuration.getPassword() != null) {
        LOG.info("Adding basic auth credentials provider");
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
                new UsernamePasswordCredentials(configuration.getUsername(), configuration.getPassword()));
        builder.setDefaultCredentialsProvider(credsProvider);
    }/*  w  w w . j a va2 s.  c  o m*/
    if (!configuration.getVerifySslCert()) {
        LOG.info("Adding trustful ssl context");
        SSLContextBuilder sslBuilder = new SSLContextBuilder();
        try {
            sslBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslBuilder.build());
            builder.setSSLSocketFactory(sslsf);
        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
            LOG.error("Failed to init socket factory {}", ex.getMessage(), ex);
        }
    }
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setDefaultMaxPerRoute(configuration.getConnectionPoolSize());
    cm.setMaxTotal(configuration.getConnectionPoolSize());
    builder.setConnectionManager(cm);
    this.client = builder.build();
}

From source file:org.apache.manifoldcf.authorities.authorities.jira.JiraSession.java

/**
 * Constructor. Create a session.//from   w w w .  java  2  s  .c  o m
 */
public JiraSession(String clientId, String clientSecret, String protocol, String host, int port, String path,
        String proxyHost, int proxyPort, String proxyDomain, String proxyUsername, String proxyPassword)
        throws ManifoldCFException {
    this.host = new HttpHost(host, port, protocol);
    this.path = path;
    this.clientId = clientId;
    this.clientSecret = clientSecret;

    int socketTimeout = 900000;
    int connectionTimeout = 60000;

    javax.net.ssl.SSLSocketFactory httpsSocketFactory = KeystoreManagerFactory.getTrustingSecureSocketFactory();
    SSLConnectionSocketFactory myFactory = new SSLConnectionSocketFactory(
            new InterruptibleSocketFactory(httpsSocketFactory, connectionTimeout),
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    connectionManager = new PoolingHttpClientConnectionManager();

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

    // If authentication needed, set that
    if (clientId != null) {
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(clientId, clientSecret));
    }

    RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
            .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).setExpectContinueEnabled(true)
            .setConnectTimeout(connectionTimeout).setConnectionRequestTimeout(socketTimeout);

    // If there's a proxy, set that too.
    if (proxyHost != null && proxyHost.length() > 0) {

        // Configure proxy authentication
        if (proxyUsername != null && proxyUsername.length() > 0) {
            if (proxyPassword == null)
                proxyPassword = "";
            if (proxyDomain == null)
                proxyDomain = "";

            credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, currentHost, proxyDomain));
        }

        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        requestBuilder.setProxy(proxy);
    }

    httpClient = HttpClients.custom().setConnectionManager(connectionManager).setMaxConnTotal(1)
            .disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build())
            .setDefaultSocketConfig(
                    SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
            .setDefaultCredentialsProvider(credentialsProvider).setSSLSocketFactory(myFactory)
            .setRequestExecutor(new HttpRequestExecutor(socketTimeout))
            .setRedirectStrategy(new DefaultRedirectStrategy()).build();

}

From source file:org.apache.manifoldcf.crawler.connectors.confluence.ConfluenceSession.java

public ConfluenceSession(String clientId, String clientSecret, String protocol, String host, int port,
        String path, String proxyHost, int proxyPort, String proxyDomain, String proxyUsername,
        String proxyPassword) throws ManifoldCFException {
    this.host = new HttpHost(host, port, protocol);
    this.path = path;
    this.clientId = clientId;
    this.clientSecret = clientSecret;

    int socketTimeout = 900000;
    int connectionTimeout = 60000;

    javax.net.ssl.SSLSocketFactory httpsSocketFactory = KeystoreManagerFactory.getTrustingSecureSocketFactory();
    SSLConnectionSocketFactory myFactory = new SSLConnectionSocketFactory(
            new InterruptibleSocketFactory(httpsSocketFactory, connectionTimeout),
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    connectionManager = new PoolingHttpClientConnectionManager();

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

    // If authentication needed, set that
    if (clientId != null) {
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(clientId, clientSecret));
    }// w  w w.j a  v  a  2  s.c  o  m

    RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
            .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).setExpectContinueEnabled(true)
            .setConnectTimeout(connectionTimeout).setConnectionRequestTimeout(socketTimeout);

    // If there's a proxy, set that too.
    if (proxyHost != null && proxyHost.length() > 0) {

        // Configure proxy authentication
        if (proxyUsername != null && proxyUsername.length() > 0) {
            if (proxyPassword == null)
                proxyPassword = "";
            if (proxyDomain == null)
                proxyDomain = "";

            credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, currentHost, proxyDomain));
        }

        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        requestBuilder.setProxy(proxy);
    }

    httpClient = HttpClients.custom().setConnectionManager(connectionManager).setMaxConnTotal(1)
            .disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build())
            .setDefaultSocketConfig(
                    SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
            .setDefaultCredentialsProvider(credentialsProvider).setSSLSocketFactory(myFactory)
            .setRequestExecutor(new HttpRequestExecutor(socketTimeout))
            .setRedirectStrategy(new DefaultRedirectStrategy()).build();
}

From source file:org.muhia.app.psi.integ.config.ke.obopay.ObopayBulkApiClientConfiguration.java

@Bean(name = "obopayBulkApiHttpClient")
public CloseableHttpClient httpClient() {

    RequestConfig config = RequestConfig.custom().setConnectTimeout(properties.getTransportConnectionTimeout())
            .setConnectionRequestTimeout(properties.getTransportReadTimeout())
            .setSocketTimeout(properties.getTransportSocketTimeout()).build();
    //        CredentialsProvider provider = new BasicCredentialsProvider();
    //        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(properties.getCrbaTransunionTransportUsername(), properties.getCrbaTransunionTransportPassword());
    //        provider.setCredentials(AuthScope.ANY, credentials);

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    connManager.setMaxTotal(properties.getPoolHostMax());
    connManager.setDefaultMaxPerRoute(properties.getPoolDefaultMaxPerhost());
    connManager.setValidateAfterInactivity(properties.getPoolValidateAfterActivity());

    return HttpClientBuilder.create().setDefaultRequestConfig(config)
            //                .setDefaultCredentialsProvider(provider)
            .setConnectionManager(connManager).evictExpiredConnections()
            .addInterceptorFirst(new RemoveHttpHeadersInterceptor()).build();

}

From source file:org.apache.lucene.replicator.ReplicatorTestCase.java

/**
 * Returns a {@link HttpClientConnectionManager}.
 * <p>//from  w  ww .ja va 2 s.  c om
 * <b>NOTE:</b> do not {@link HttpClientConnectionManager#shutdown()} this
 * connection manager, it will be close automatically after all tests have
 * finished.
 */
public static synchronized HttpClientConnectionManager getClientConnectionManager() {
    if (clientConnectionManager == null) {
        PoolingHttpClientConnectionManager ccm = new PoolingHttpClientConnectionManager();
        ccm.setDefaultMaxPerRoute(128);
        ccm.setMaxTotal(128);
        clientConnectionManager = ccm;
    }

    return clientConnectionManager;
}

From source file:gobblin.writer.http.AbstractHttpWriterBuilder.java

public B fromConfig(Config config) {
    config = config.withFallback(FALLBACK);
    RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT)
            .setSocketTimeout(config.getInt(REQUEST_TIME_OUT_MS_KEY))
            .setConnectTimeout(config.getInt(CONNECTION_TIME_OUT_MS_KEY))
            .setConnectionRequestTimeout(config.getInt(CONNECTION_TIME_OUT_MS_KEY)).build();

    getHttpClientBuilder().setDefaultRequestConfig(requestConfig);

    if (config.hasPath(STATIC_SVC_ENDPOINT)) {
        try {/* www.j a va 2  s.  c o m*/
            svcEndpoint = Optional.of(new URI(config.getString(AbstractHttpWriterBuilder.STATIC_SVC_ENDPOINT)));
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    String connMgrStr = config.getString(HTTP_CONN_MANAGER);
    switch (ConnManager.valueOf(connMgrStr.toUpperCase())) {
    case BASIC:
        httpConnManager = new BasicHttpClientConnectionManager();
        break;
    case POOLING:
        PoolingHttpClientConnectionManager poolingConnMgr = new PoolingHttpClientConnectionManager();
        poolingConnMgr.setMaxTotal(config.getInt(POOLING_CONN_MANAGER_MAX_TOTAL_CONN));
        poolingConnMgr.setDefaultMaxPerRoute(config.getInt(POOLING_CONN_MANAGER_MAX_PER_CONN));
        httpConnManager = poolingConnMgr;
        break;
    default:
        throw new IllegalArgumentException(connMgrStr + " is not supported");
    }
    LOG.info("Using " + httpConnManager.getClass().getSimpleName());
    return typedSelf();
}