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:org.openo.nfvo.monitor.umc.drill.wrapper.resources.config.ClientConfigFactory.java

/**
 * create the ClientConfig for JerseyClient
 *
 * @return//from w  w w.  ja  va 2 s .  c o m
 */
public static ClientConfig createClientConfig() {
    // create the apache PoolingHttpClient
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setDefaultMaxPerRoute(10);

    ClientConfig clientConfig = new ClientConfig().connectorProvider(new ApacheConnectorProvider())
            // specify the PoolingHttpClientConnectionManager manager
            .property(ApacheClientProperties.CONNECTION_MANAGER, connectionManager)
            .property(ClientProperties.CONNECT_TIMEOUT, "2000").property(ClientProperties.READ_TIMEOUT, "3000")
            // config the serialization / deserialization provider for json
            .register(JacksonJsonProvider.class);
    return clientConfig;
}

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

/**
 * Returns a {@link HttpClientConnectionManager}.
 * <p>/*from  ww  w. j  a 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:org.terasology.telemetry.TelemetryEmitter.java

private static HttpClientAdapter getDefaultAdapter(URL url) {

    // Make a new client with custom concurrency rules
    PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();
    manager.setDefaultMaxPerRoute(50);

    // Make the client
    CloseableHttpClient client = HttpClients.custom().setConnectionManager(manager).build();

    // Build the adapter
    return ApacheHttpClientAdapter.builder().url(url.toString()).httpClient(client).build();
}

From source file:com.johnson.grab.browser.HttpClientHolder.java

private static void init() {
    // custom builder
    builder = HttpClients.custom();/*from   w w  w.  j  av  a 2  s .  co m*/
    PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();
    manager.setDefaultMaxPerRoute(DEFAULT_MAX_NUM_PER_ROUTE);
    manager.setMaxTotal(DEFAULT_MAX_TOTAL_NUM);
    builder.setConnectionManager(manager);
    builder.setMaxConnPerRoute(DEFAULT_MAX_NUM_PER_ROUTE);
    builder.setMaxConnTotal(DEFAULT_MAX_TOTAL_NUM);
    // headers
    List<Header> headers = new ArrayList<Header>();
    headers.add(new BasicHeader("Accept",
            "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg,"
                    + " application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint,"
                    + " application/msword, */*"));
    headers.add(new BasicHeader("Accept-Language", "zh-cn,en-us,zh-tw,en-gb,en;"));
    headers.add(new BasicHeader("Accept-Charset", "gbk,gb2312,utf-8,BIG5,ISO-8859-1;"));
    headers.add(new BasicHeader("Connection", "Close"));
    headers.add(new BasicHeader("Cache-Control", "no-cache"));
    headers.add(new BasicHeader("User-Agent",
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; CIBA)"));
    headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate,sdch"));
    headers.add(new BasicHeader("Connection", "close"));
    builder.setDefaultHeaders(headers);

    // retry handler
    builder.setRetryHandler(new HttpRequestRetryHandler() {
        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount >= MAX_EXECUTION_NUM) {
                return false;
            }
            if (exception instanceof ConnectTimeoutException) {
                return false;
            }
            if (exception instanceof InterruptedIOException) {
                return false;
            }
            if (exception instanceof UnknownHostException) {
                return false;
            }
            if (exception instanceof NoHttpResponseException) {
                return false;
            }
            if (exception instanceof SSLException) {
                return false;
            }
            HttpClientContext clientContext = HttpClientContext.adapt(context);
            HttpRequest request = clientContext.getRequest();
            if (!(request instanceof HttpEntityEnclosingRequest)) {
                return true;
            }
            return false;
        }
    });

    // build client
    client = builder.build();
}

From source file:tv.icntv.common.HttpClientHolder.java

private static void init() {
    // custom builder
    builder = HttpClients.custom();/*from ww w. ja  va  2  s.c o  m*/
    PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();
    manager.setDefaultMaxPerRoute(DEFAULT_MAX_NUM_PER_ROUTE);
    manager.setMaxTotal(DEFAULT_MAX_TOTAL_NUM);
    builder.setConnectionManager(manager);
    builder.setMaxConnPerRoute(DEFAULT_MAX_NUM_PER_ROUTE);
    builder.setMaxConnTotal(DEFAULT_MAX_TOTAL_NUM);
    // headers
    List<Header> headers = new ArrayList<Header>();
    headers.add(new BasicHeader("Accept",
            "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg,"
                    + " application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint,"
                    + " application/msword, */*"));
    //        headers.add(new BasicHeader("Content-Type","application/xml"));
    headers.add(new BasicHeader("Accept-Language", "zh-cn,en-us,zh-tw,en-gb,en;"));
    headers.add(new BasicHeader("Accept-Charset", "gbk,gb2312,utf-8,BIG5,ISO-8859-1;"));
    headers.add(new BasicHeader("Connection", "Close"));
    headers.add(new BasicHeader("Cache-Control", "no-cache"));
    headers.add(new BasicHeader("User-Agent",
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; CIBA)"));
    headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate,sdch"));
    headers.add(new BasicHeader("Connection", "close"));
    builder.setDefaultHeaders(headers);
    // retry handler
    builder.setRetryHandler(new HttpRequestRetryHandler() {
        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount >= MAX_EXECUTION_NUM) {
                return false;
            }
            if (exception instanceof ConnectTimeoutException) {
                return false;
            }
            if (exception instanceof InterruptedIOException) {
                return false;
            }
            if (exception instanceof UnknownHostException) {
                return false;
            }
            if (exception instanceof NoHttpResponseException) {
                return false;
            }
            if (exception instanceof SSLException) {
                return false;
            }
            HttpClientContext clientContext = HttpClientContext.adapt(context);
            HttpRequest request = clientContext.getRequest();
            if (!(request instanceof HttpEntityEnclosingRequest)) {
                return true;
            }
            return false;
        }
    });

    // build client
    client = builder.build();
}

From source file:utils.HttpClientGenerator.java

public static CloseableHttpClient getHttpClient(boolean checkCert) {

    if (checkCert == false) {
        HttpClientBuilder b = HttpClientBuilder.create();

        // setup a Trust Strategy that allows all certificates.
        SSLContext sslContext = null;
        try {/*from w  ww.  j a  v  a2s  .com*/
            sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                    return true;
                }
            }).build();
        } catch (NoSuchAlgorithmException e) {
            String err = "error occurred while creating SSL disables hhtp client";
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        b.setSslcontext(sslContext);

        // not to check Hostnames
        HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

        //       create an SSL Socket Factory, to use weakened "trust strategy";
        //       and create a Registry, to register it.
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                (X509HostnameVerifier) hostnameVerifier);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory).build();

        // creating connection-manager using our Registry.
        //      -- allows multi-threaded use
        PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(
                socketFactoryRegistry);
        connMgr.setDefaultMaxPerRoute(20);
        // Increase max connections for localhost:80 to 50
        HttpHost localhost = new HttpHost("localhost", 9443);
        connMgr.setMaxPerRoute(new HttpRoute(localhost), 10);
        b.setConnectionManager(connMgr);

        // finally, build the HttpClient;
        CloseableHttpClient client = b.build();
        return client;
    } else {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        // Increase default max connection per route to 20
        cm.setDefaultMaxPerRoute(20);
        // Increase max connections for localhost:80 to 50
        HttpHost localhost = new HttpHost("localhost", 9443);
        cm.setMaxPerRoute(new HttpRoute(localhost), 10);
        CloseableHttpClient client = HttpClients.custom().setConnectionManager(cm).build();
        return client;
    }
}

From source file:org.andstatus.app.net.http.MyHttpClientFactory.java

public static HttpClient getHttpClient(SslModeEnum sslMode) {
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", TlsSniSocketFactory.getInstance(sslMode)).build();
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
    // max.  3 connections in total
    connectionManager.setMaxTotal(3);//from   www .j  a v a2  s .c o  m
    // max.  2 connections per host
    connectionManager.setDefaultMaxPerRoute(2);

    // use request defaults from AndroidHttpClient
    RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT)
            .setConnectTimeout(MyPreferences.getConnectionTimeoutMs())
            .setSocketTimeout(2 * MyPreferences.getConnectionTimeoutMs()).setStaleConnectionCheckEnabled(false)
            .build();

    HttpClientBuilder builder = HttpClients.custom().useSystemProperties()
            .setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig)
            /* TODO maybe:  
            .setRetryHandler(DavHttpRequestRetryHandler.INSTANCE)
            .setRedirectStrategy(DavRedirectStrategy.INSTANCE)  
            */
            .disableRedirectHandling().setUserAgent(HttpConnection.USER_AGENT).disableCookieManagement();

    return builder.build();
}

From source file:io.fabric8.maven.docker.access.hc.http.HttpClientBuilder.java

private static HttpClientConnectionManager getPooledConnectionFactory(String certPath, int maxConnections)
        throws IOException {
    PoolingHttpClientConnectionManager ret = certPath != null
            ? new PoolingHttpClientConnectionManager(getSslFactoryRegistry(certPath))
            : new PoolingHttpClientConnectionManager();
    ret.setDefaultMaxPerRoute(maxConnections);
    ret.setMaxTotal(maxConnections);/* w w w .j a  v a 2  s  .co m*/
    return ret;
}

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

private static void createClient() throws Exception {
    RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
            .<ConnectionSocketFactory>create();

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

    socketFactoryRegistry.register("https", createSSLSocketFactory());

    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry.build());
    connMgr.setMaxTotal(CLIENT_MAX_TOTAL_CONNECTIONS);
    connMgr.setDefaultMaxPerRoute(CLIENT_MAX_CONNECTIONS_PER_ROUTE);

    int timeout = SystemProperties.getClientProxyTimeout();
    RequestConfig.Builder rb = RequestConfig.custom();
    rb.setConnectTimeout(timeout);//from  ww  w . j a  v a 2  s.co m
    rb.setConnectionRequestTimeout(timeout);
    rb.setSocketTimeout(timeout);

    HttpClientBuilder cb = HttpClients.custom();
    cb.setConnectionManager(connMgr);
    cb.setDefaultRequestConfig(rb.build());

    // Disable request retry
    cb.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));

    client = cb.build();
}

From source file:org.ops4j.pax.url.mvn.internal.HttpClients.java

private static PoolingHttpClientConnectionManager createConnManager(PropertyResolver resolver, String pid) {
    boolean SSL_INSECURE = getBoolean(resolver, "maven.wagon.http.ssl.insecure",
            !getBoolean(resolver, pid + "certificateCheck", false));
    boolean IGNORE_SSL_VALIDITY_DATES = getBoolean(resolver, "maven.wagon.http.ssl.ignore.validity.dates",
            false);//from   ww w  .java  2  s .  com
    boolean SSL_ALLOW_ALL = getBoolean(resolver, "maven.wagon.http.ssl.allowall",
            !getBoolean(resolver, pid + "certificateCheck", false));
    boolean PERSISTENT_POOL = getBoolean(resolver, "maven.wagon.http.pool", true);
    int MAX_CONN_PER_ROUTE = getInteger(resolver, "maven.wagon.httpconnectionManager.maxPerRoute", 20);
    int MAX_CONN_TOTAL = getInteger(resolver, "maven.wagon.httpconnectionManager.maxTotal", 40);

    String sslProtocolsStr = getProperty(resolver, "https.protocols", null);
    String cipherSuitesStr = getProperty(resolver, "https.cipherSuites", null);
    String[] sslProtocols = sslProtocolsStr != null ? sslProtocolsStr.split(" *, *") : null;
    String[] cipherSuites = cipherSuitesStr != null ? cipherSuitesStr.split(" *, *") : null;

    SSLConnectionSocketFactory sslConnectionSocketFactory;
    if (SSL_INSECURE) {
        try {
            SSLContext sslContext = new SSLContextBuilder().useSSL()
                    .loadTrustMaterial(null, new RelaxedTrustStrategy(IGNORE_SSL_VALIDITY_DATES)).build();
            sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, sslProtocols, cipherSuites,
                    SSL_ALLOW_ALL ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
                            : SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        } catch (Exception ex) {
            throw new SSLInitializationException(ex.getMessage(), ex);
        }
    } else {
        sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                HttpsURLConnection.getDefaultSSLSocketFactory(), sslProtocols, cipherSuites,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    }

    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", sslConnectionSocketFactory).build();

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
    if (PERSISTENT_POOL) {
        connManager.setDefaultMaxPerRoute(MAX_CONN_PER_ROUTE);
        connManager.setMaxTotal(MAX_CONN_TOTAL);
    } else {
        connManager.setMaxTotal(1);
    }

    boolean soKeepAlive = getBoolean(resolver, pid + ServiceConstants.PROPERTY_SOCKET_SO_KEEPALIVE, false);
    int soLinger = getInteger(resolver, pid + ServiceConstants.PROPERTY_SOCKET_SO_LINGER, -1);
    boolean soReuseAddress = getBoolean(resolver, pid + ServiceConstants.PROPERTY_SOCKET_SO_REUSEADDRESS,
            false);
    boolean soTcpNoDelay = getBoolean(resolver, pid + ServiceConstants.PROPERTY_SOCKET_TCP_NODELAY, true);
    //        int soTimeout = getInteger( resolver, pid + ServiceConstants.PROPERTY_SOCKET_SO_TIMEOUT, 0 );
    SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(soKeepAlive) // default false
            .setSoLinger(soLinger) // default -1
            .setSoReuseAddress(soReuseAddress) // default false
            .setTcpNoDelay(soTcpNoDelay) // default true
            .setSoTimeout(0) // default 0, but set in org.apache.http.impl.conn.CPoolProxy.setSocketTimeout()
            // this value is not used
            .build();
    connManager.setDefaultSocketConfig(socketConfig);

    int bufferSize = getInteger(resolver, pid + ServiceConstants.PROPERTY_CONNECTION_BUFFER_SIZE, 8192);
    ConnectionConfig connectionConfig = ConnectionConfig.custom().setBufferSize(bufferSize) // default 8192
            .setFragmentSizeHint(bufferSize) // default 'buffer size'
            .build();
    connManager.setDefaultConnectionConfig(connectionConfig);

    return connManager;
}