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

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

Introduction

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

Prototype

public void setDefaultMaxPerRoute(final int max) 

Source Link

Usage

From source file:au.com.borner.salesforce.client.rest.ConnectionManager.java

public ConnectionManager() {
    loggedIn = false;//from   w  ww.  j a  v a  2  s.c o  m
    SSLContext sslContext = SSLContexts.createSystemDefault();
    LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);

    PoolingHttpClientConnectionManager pcm = new PoolingHttpClientConnectionManager();
    pcm.setMaxTotal(100);
    pcm.setDefaultMaxPerRoute(50);

    HttpCompressionRequestInterceptor requestInterceptor = new HttpCompressionRequestInterceptor();
    HttpCompressionResponseInterceptor responseInterceptor = new HttpCompressionResponseInterceptor();

    httpClient = HttpClients.custom().setConnectionManager(pcm).setSSLSocketFactory(sslSocketFactory)
            .addInterceptorFirst(requestInterceptor).addInterceptorFirst(responseInterceptor).build();
}

From source file:jp.co.ctc_g.jse.core.rest.springmvc.client.ProxyClientHttpRequestFactory.java

/**
 * ???????HttpClient????????//from w  ww .  java  2  s.  c  o m
 * {@inheritDoc}
 */
@Override
public void afterPropertiesSet() throws Exception {

    Assert.notNull(proxyHost, "(proxyHost)???");
    Assert.notNull(proxyPort, "??(proxyPort)???");

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(maxTotal);
    connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);

    HttpClientBuilder builder = HttpClients.custom();
    builder.setConnectionManager(connectionManager);
    if (authentication) {
        Assert.notNull(username,
                "??true???????(username)???");
        Assert.notNull(password,
                "??true?????(password)???");
        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(
                new HttpHost(proxyHost, Integer.parseInt(proxyPort)));
        builder.setRoutePlanner(routePlanner);
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(proxyHost, Integer.parseInt(proxyPort)),
                new UsernamePasswordCredentials(username, password));
        builder.setDefaultCredentialsProvider(credsProvider);
    }
    builder.setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout(readTimeout).build());
    CloseableHttpClient client = builder.build();
    setHttpClient(client);
}

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 {/*from w  w  w.  j  a v  a 2s. c om*/
            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();
}

From source file:org.geosdi.geoplatform.experimental.openam.support.config.connector.secure.OpenAMAuthorizedConnector.java

protected OpenAMAuthorizedConnector(GPConnectorSettings theOpenAMConnectorSettings) {
    Preconditions.checkNotNull(theOpenAMConnectorSettings, "The OpenAMConnectorSettings must not be null.");
    this.openAMConnectorSettings = theOpenAMConnectorSettings;
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(this.openAMConnectorSettings.getMaxTotalConnections());
    cm.setDefaultMaxPerRoute(this.openAMConnectorSettings.getDefaultMaxPerRoute());
    this.httpClient = HttpClients.custom().setConnectionManager(cm)
            .setRetryHandler(new OpenAMHttpRequestRetryHandler(5)).build();
}

From source file:org.nebula.framework.client.NebulaRestClient.java

public NebulaRestClient(String accessId, String secretKey, String hostname, int port, String contextPath,
        int connectionTimeoutInSecs, int socketTimeoutInSecs, int maxTotalConnections) {
    this.accessId = accessId;
    this.secretKey = secretKey;
    this.target = new HttpHost(hostname, port);

    requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectionTimeoutInSecs * 1000)
            .setConnectTimeout(connectionTimeoutInSecs * 1000).setSocketTimeout(socketTimeoutInSecs * 1000)
            .build();/*from   www. j  a v  a 2  s. c om*/

    requestMapper = new RequestMapper(contextPath);

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(maxTotalConnections);
    cm.setDefaultMaxPerRoute(maxTotalConnections);
    client = HttpClientBuilder.create().setConnectionManager(cm).build();

}

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  .ja  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:org.openhab.binding.ihc.ws.IhcConnectionPool.java

private void init() {

    // Create a local instance of cookie store
    cookieStore = new BasicCookieStore();

    // Create local HTTP context
    localContext = HttpClientContext.create();

    // Bind custom cookie store to the local context
    localContext.setCookieStore(cookieStore);

    httpClientBuilder = HttpClientBuilder.create();

    // Setup a Trust Strategy that allows all certificates.

    logger.debug("Initialize SSL context");

    // Create a trust manager that does not validate certificate chains,
    // but accept all.
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        @Override/*from w  w w  .j a va  2s.c om*/
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            logger.trace("Trusting server cert: " + certs[0].getIssuerDN());
        }
    } };

    // Install the all-trusting trust manager

    try {
        // Controller supports only SSLv3 and TLSv1
        sslContext = SSLContext.getInstance("TLSv1");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

    } catch (NoSuchAlgorithmException e) {
        logger.warn("Exception", e);
    } catch (KeyManagementException e) {
        logger.warn("Exception", e);
    }

    httpClientBuilder.setSslcontext(sslContext);

    // Controller accepts only HTTPS connections and because normally IP
    // address are used on home network rather than DNS names, create custom
    // host name verifier.
    HostnameVerifier hostnameVerifier = new HostnameVerifier() {

        @Override
        public boolean verify(String arg0, SSLSession arg1) {
            logger.trace("HostnameVerifier: arg0 = " + arg0);
            logger.trace("HostnameVerifier: arg1 = " + arg1);
            return true;
        }
    };

    // Create an SSL Socket Factory, to use our weakened "trust strategy"
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
            new String[] { "TLSv1" }, null, hostnameVerifier);

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

    // Create connection-manager using our Registry. Allows multi-threaded
    // use
    PoolingHttpClientConnectionManager connMngr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);

    // Increase max connection counts
    connMngr.setMaxTotal(20);
    connMngr.setDefaultMaxPerRoute(6);

    httpClientBuilder.setConnectionManager(connMngr);
}

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);//from  w  ww . j av  a 2s  . c  om
    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.github.horrorho.liquiddonkey.http.HttpClientFactory.java

public CloseableHttpClient client() {
    logger.trace("<< client()");

    PoolingHttpClientConnectionManager connectionManager = config.isRelaxedSSL()
            ? new PoolingHttpClientConnectionManager(relaxedSocketFactoryRegistry())
            : new PoolingHttpClientConnectionManager();

    connectionManager.setMaxTotal(config.maxConnections());
    connectionManager.setDefaultMaxPerRoute(config.maxConnections());
    connectionManager.setValidateAfterInactivity(config.validateAfterInactivityMs());

    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(config.timeoutMs())
            .setConnectTimeout(config.timeoutMs()).setSocketTimeout(config.timeoutMs()).build();

    HttpRequestRetryHandler httpRequestRetryHandler = config.isPersistent()
            ? new PersistentHttpRequestRetryHandler(config.retryCount(), config.retryDelayMs(),
                    config.timeoutMs(), true)
            : new DefaultHttpRequestRetryHandler(config.retryCount(), false);

    CloseableHttpClient client = HttpClients.custom().setRetryHandler(httpRequestRetryHandler)
            .setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig)
            .setUserAgent(config.userAgent()).build();

    logger.trace(">> client()", client);
    return client;
}