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:com.baidubce.http.BceHttpClient.java

/**
 * Create connection manager for http client.
 *
 * @return The connection manager for http client.
 *//* w w  w. j  av  a 2s  . co m*/
private HttpClientConnectionManager createHttpClientConnectionManager() {
    ConnectionSocketFactory socketFactory = PlainConnectionSocketFactory.getSocketFactory();
    LayeredConnectionSocketFactory sslSocketFactory;
    try {
        sslSocketFactory = new SSLConnectionSocketFactory(SSLContext.getDefault(),
                SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER);
    } catch (NoSuchAlgorithmException e) {
        throw new BceClientException("Fail to create SSLConnectionSocketFactory", e);
    }
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register(Protocol.HTTP.toString(), socketFactory)
            .register(Protocol.HTTPS.toString(), sslSocketFactory).build();
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
    connectionManager.setDefaultMaxPerRoute(this.config.getMaxConnections());
    connectionManager.setDefaultSocketConfig(SocketConfig.custom()
            .setSoTimeout(this.config.getSocketTimeoutInMillis()).setTcpNoDelay(true).build());
    connectionManager.setMaxTotal(this.config.getMaxConnections());
    return connectionManager;
}

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  ww .  j a va 2s  . c  o  m
 */
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: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 {/*  ww  w .  j  a 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:org.artifactory.util.HttpClientConfigurator.java

/**
 * Creates custom Http Client connection pool to be used by Http Client
 *
 * @return {@link PoolingHttpClientConnectionManager}
 *///from ww w  . j a  va 2 s  . c o  m
private PoolingHttpClientConnectionManager createConnectionMgr() {
    PoolingHttpClientConnectionManager connectionMgr;
    connectionMgr = new PoolingHttpClientConnectionManager(INACTIVITY_TIMEOUT, TimeUnit.MILLISECONDS);
    connectionMgr.setMaxTotal(MAX_TOTAL_CONNECTIONS);
    connectionMgr.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_HOST);
    HttpHost localhost = new HttpHost(LOCALHOST, DEFAULT_PORT);
    connectionMgr.setMaxPerRoute(new HttpRoute(localhost), DEFAULT_POOL_MAX_CONNECTIONS_PER_ROUTE);
    return connectionMgr;
}

From source file:org.commonjava.aprox.client.core.AproxClientHttp.java

public synchronized void connect() {
    if (this.connectionManager == null) {
        final PoolingHttpClientConnectionManager pcm = new PoolingHttpClientConnectionManager();
        pcm.setDefaultMaxPerRoute(GLOBAL_MAX_CONNECTIONS);

        this.connectionManager = new CloseBlockingConnectionManager(pcm);
    }/*from w  w w  . ja  va2 s  . co m*/
}

From source file:com.hp.octane.integrations.services.rest.OctaneRestClientImpl.java

OctaneRestClientImpl(OctaneSDK.SDKServicesConfigurer configurer) {
    if (configurer == null) {
        throw new IllegalArgumentException("invalid configurer");
    }// w ww  .j av a2s .c  om

    this.configurer = configurer;

    SSLContext sslContext = SSLContexts.createSystemDefault();
    HostnameVerifier hostnameVerifier = new CustomHostnameVerifier();
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry);
    connectionManager.setMaxTotal(MAX_TOTAL_CONNECTIONS);
    connectionManager.setDefaultMaxPerRoute(MAX_TOTAL_CONNECTIONS);

    HttpClientBuilder clientBuilder = HttpClients.custom().setConnectionManager(connectionManager);

    httpClient = clientBuilder.build();
}

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

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

    try {/*from   w  w w . ja  va2s  .  c  o m*/
        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:com.normalexception.app.rx8club.html.LoginFactory.java

/**
 * Initialize the client, cookie store, and context
 *///from w w  w  .  ja v a 2 s.  co m
private void initializeClientInformation() {
    Log.d(TAG, "Initializing Client...");

    /*
    Log.d(TAG, "Creating Custom Cache Configuration");
    CacheConfig cacheConfig = CacheConfig.custom()
      .setMaxCacheEntries(1000)
      .setMaxObjectSize(8192)
      .build();
    */

    Log.d(TAG, "Creating Custom Request Configuration");
    RequestConfig rConfig = RequestConfig.custom().setCircularRedirectsAllowed(true)
            .setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build();

    cookieStore = new BasicCookieStore();
    httpContext = new BasicHttpContext();

    Log.d(TAG, "Building Custom HTTP Client");
    HttpClientBuilder httpclientbuilder = HttpClients.custom();
    //httpclientbuilder.setCacheConfig(cacheConfig);
    httpclientbuilder.setDefaultRequestConfig(rConfig);
    httpclientbuilder.setDefaultCookieStore(cookieStore);

    Log.d(TAG, "Connection Manager Initializing");
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(200);
    cm.setDefaultMaxPerRoute(20);
    httpclientbuilder.setConnectionManager(cm);

    Log.d(TAG, "Enable GZIP Compression");
    httpclientbuilder.addInterceptorLast(new HttpRequestInterceptor() {

        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
            }
        }

    });
    httpclientbuilder.addInterceptorLast(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;
                        }
                    }
                }
            }
        }

    });

    // Follow Redirects
    Log.d(TAG, "Registering Redirect Strategy");
    httpclientbuilder.setRedirectStrategy(new RedirectStrategy());

    // Setup retry handler
    Log.d(TAG, "Registering Retry Handler");
    httpclientbuilder.setRetryHandler(new RetryHandler());

    // Setup KAS
    Log.d(TAG, "Registering Keep Alive Strategy");
    httpclientbuilder.setKeepAliveStrategy(new KeepAliveStrategy());

    httpclient = httpclientbuilder.build();

    //httpclient.log.enableDebug(
    //      MainApplication.isHttpClientLogEnabled());

    isInitialized = true;
}

From source file:com.muk.services.configuration.ServiceConfig.java

@Bean
public HttpClientConnectionManager genericConnectionManager() {
    final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    connManager.setMaxTotal(10);/*from  www .  j ava 2s.  c  o  m*/
    connManager.setDefaultMaxPerRoute(4);

    return connManager;
}

From source file:com.muk.services.configuration.ServiceConfig.java

@Bean
public HttpClientConnectionManager poolingConnectionManager() {
    final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    connManager.setMaxTotal(200);/*www  .  ja  va 2 s  .  co  m*/
    connManager.setDefaultMaxPerRoute(20);

    return connManager;
}