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.nominanuda.web.http.HttpCoreHelper.java

public HttpClient createClient(int maxConnPerRoute, long connTimeoutMillis, long soTimeoutMillis,
        @Nullable String proxyHostAnPort) {
    Registry<ConnectionSocketFactory> defaultRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", SSLConnectionSocketFactory.getSocketFactory()).build();
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(defaultRegistry);
    connMgr.setDefaultMaxPerRoute(maxConnPerRoute);
    SocketConfig sCfg = SocketConfig.custom().setSoTimeout((int) soTimeoutMillis)
            .setSoTimeout((int) connTimeoutMillis).build();
    connMgr.setDefaultSocketConfig(sCfg);
    HttpClientBuilder hcb = HttpClientBuilder.create();
    hcb.setDefaultSocketConfig(sCfg).setConnectionManager(connMgr);
    if (proxyHostAnPort == null) {
    } else if ("jvm".equalsIgnoreCase(proxyHostAnPort)) {
        SystemDefaultRoutePlanner rp = new SystemDefaultRoutePlanner(ProxySelector.getDefault());
        hcb.setRoutePlanner(rp);/* w w  w  .ja v a  2 s  .  c  om*/
    } else {
        String[] hostAndPort = proxyHostAnPort.split(":");
        Check.illegalargument.assertTrue(hostAndPort.length < 3, "wrong hostAndPort:" + proxyHostAnPort);
        String host = hostAndPort[0];
        int port = 80;
        if (hostAndPort.length > 1) {
            port = Integer.valueOf(hostAndPort[1]);
        }
        HttpHost proxy = new HttpHost(host, port);
        hcb.setProxy(proxy);
    }
    HttpClient httpClient = hcb.build();
    return httpClient;
}

From source file:groovyx.net.http.ApacheHttpBuilder.java

/**
 * Creates a new `HttpBuilder` based on the Apache HTTP client. While it is acceptable to create a builder with this method, it is generally
 * preferred to use one of the `static` `configure(...)` methods.
 *
 * @param config the configuration object
 *///from  www  .j  a va 2  s.  c om
public ApacheHttpBuilder(final HttpObjectConfig config) {
    super(config);

    this.proxyInfo = config.getExecution().getProxyInfo();
    this.config = new HttpConfigs.ThreadSafeHttpConfig(config.getChainedConfig());
    this.executor = config.getExecution().getExecutor();
    this.clientConfig = config.getClient();

    final HttpClientBuilder myBuilder = HttpClients.custom();

    final Registry<ConnectionSocketFactory> registry = registry(config);

    if (config.getExecution().getMaxThreads() > 1) {
        final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
        cm.setMaxTotal(config.getExecution().getMaxThreads());
        cm.setDefaultMaxPerRoute(config.getExecution().getMaxThreads());
        myBuilder.setConnectionManager(cm);
    } else {
        final BasicHttpClientConnectionManager cm = new BasicHttpClientConnectionManager(registry);
        myBuilder.setConnectionManager(cm);
    }

    final SSLContext sslContext = config.getExecution().getSslContext();
    if (sslContext != null) {
        myBuilder.setSSLContext(sslContext);
        myBuilder.setSSLSocketFactory(
                new SSLConnectionSocketFactory(sslContext, config.getExecution().getHostnameVerifier()));
    }

    myBuilder.addInterceptorFirst((HttpResponseInterceptor) (response, context) -> {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            Header ceheader = entity.getContentEncoding();
            if (ceheader != null) {
                HeaderElement[] codecs = ceheader.getElements();
                for (HeaderElement codec : codecs) {
                    if (codec.getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }
        }
    });

    final Consumer<Object> clientCustomizer = clientConfig.getClientCustomizer();
    if (clientCustomizer != null) {
        clientCustomizer.accept(myBuilder);
    }

    this.client = myBuilder.build();
}

From source file:com.mirth.connect.client.core.ServerConnection.java

public ServerConnection(int timeout, String[] httpsProtocols, String[] httpsCipherSuites, boolean allowHTTP) {
    SSLContext sslContext = null;
    try {// w w  w  .  j a v a  2 s . co m
        sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
    } catch (Exception e) {
        logger.error("Unable to build SSL context.", e);
    }

    String[] enabledProtocols = MirthSSLUtil.getEnabledHttpsProtocols(httpsProtocols);
    String[] enabledCipherSuites = MirthSSLUtil.getEnabledHttpsCipherSuites(httpsCipherSuites);
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
            enabledProtocols, enabledCipherSuites, NoopHostnameVerifier.INSTANCE);
    RegistryBuilder<ConnectionSocketFactory> builder = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslConnectionSocketFactory);
    if (allowHTTP) {
        builder.register("http", PlainConnectionSocketFactory.getSocketFactory());
    }
    Registry<ConnectionSocketFactory> socketFactoryRegistry = builder.build();

    PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry);
    httpClientConnectionManager.setDefaultMaxPerRoute(5);
    httpClientConnectionManager.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(timeout).build());
    // MIRTH-3962: The stale connection settings has been deprecated, and this is recommended instead
    httpClientConnectionManager.setValidateAfterInactivity(5000);

    HttpClientBuilder clientBuilder = HttpClients.custom().setConnectionManager(httpClientConnectionManager);
    HttpUtil.configureClientBuilder(clientBuilder);

    client = clientBuilder.build();
    requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
            .setConnectionRequestTimeout(CONNECT_TIMEOUT).setSocketTimeout(timeout).build();
}

From source file:org.ambraproject.rhino.config.RhinoConfiguration.java

@Bean
public CloseableHttpClient httpClient(RuntimeConfiguration runtimeConfiguration) {
    PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();

    Integer maxTotal = runtimeConfiguration.getHttpConnectionPoolConfiguration().getMaxTotal();
    manager.setMaxTotal(maxTotal == null ? 400 : maxTotal);

    Integer defaultMaxPerRoute = runtimeConfiguration.getHttpConnectionPoolConfiguration()
            .getDefaultMaxPerRoute();/*from w w w . j a va2  s  . c om*/
    manager.setDefaultMaxPerRoute(defaultMaxPerRoute == null ? 20 : defaultMaxPerRoute);

    return HttpClientBuilder.create().setConnectionManager(manager).build();
}

From source file:com.networknt.client.Client.java

private CloseableHttpClient httpClient() throws ClientException {

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry());

    Map<String, Object> httpClientMap = (Map<String, Object>) config.get(SYNC);
    connectionManager.setMaxTotal((Integer) httpClientMap.get(MAX_CONNECTION_TOTAL));
    connectionManager.setDefaultMaxPerRoute((Integer) httpClientMap.get(MAX_CONNECTION_PER_ROUTE));
    // Now handle all the specific route defined.
    Map<String, Object> routeMap = (Map<String, Object>) httpClientMap.get(ROUTES);
    Iterator<String> it = routeMap.keySet().iterator();
    while (it.hasNext()) {
        String route = it.next();
        Integer maxConnection = (Integer) routeMap.get(route);
        connectionManager.setMaxPerRoute(new HttpRoute(new HttpHost(route)), maxConnection);
    }//from   w w  w. j a v  a  2s .co m
    final int timeout = (Integer) httpClientMap.get(TIMEOUT);
    RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).setSocketTimeout(timeout).build();
    final long keepAliveMilliseconds = (Integer) httpClientMap.get(KEEP_ALIVE);
    return HttpClientBuilder.create().setConnectionManager(connectionManager)
            .setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
                @Override
                public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                    HeaderElementIterator it = new BasicHeaderElementIterator(
                            response.headerIterator(HTTP.CONN_KEEP_ALIVE));
                    while (it.hasNext()) {
                        HeaderElement he = it.nextElement();
                        String param = he.getName();
                        String value = he.getValue();
                        if (value != null && param.equalsIgnoreCase("timeout")) {
                            try {
                                logger.trace("Use server timeout for keepAliveMilliseconds");
                                return Long.parseLong(value) * 1000;
                            } catch (NumberFormatException ignore) {
                            }
                        }
                    }
                    //logger.trace("Use keepAliveMilliseconds from config " + keepAliveMilliseconds);
                    return keepAliveMilliseconds;
                }
            }).setDefaultRequestConfig(config).build();
}

From source file:com.joyent.manta.http.MantaConnectionFactory.java

/**
 * Configures a connection manager with all of the setting needed to connect
 * to Manta./*from  w  w  w .  ja va 2 s  .c  om*/
 *
 * @param metricConfig potentially-null configuration for tracking client metrics
 * @return fully configured connection manager
 */
protected HttpClientConnectionManager buildConnectionManager(
        final MantaClientMetricConfiguration metricConfig) {
    final int maxConns = ObjectUtils.firstNonNull(config.getMaximumConnections(),
            DefaultsConfigContext.DEFAULT_MAX_CONNS);

    final ConnectionSocketFactory sslConnectionSocketFactory = new MantaSSLConnectionSocketFactory(this.config);

    final RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();

    final Registry<ConnectionSocketFactory> socketFactoryRegistry = registryBuilder
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslConnectionSocketFactory).build();

    final HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory = buildHttpConnectionFactory();

    final PoolingHttpClientConnectionManager connManager;
    if (metricConfig != null) {
        connManager = new InstrumentedPoolingHttpClientConnectionManager(metricConfig.getRegistry(),
                socketFactoryRegistry, connFactory, null, DNS_RESOLVER, -1, TimeUnit.MILLISECONDS);
    } else {
        connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry, connFactory, DNS_RESOLVER);
    }

    connManager.setDefaultMaxPerRoute(maxConns);
    connManager.setMaxTotal(maxConns);
    connManager.setDefaultSocketConfig(buildSocketConfig());
    connManager.setDefaultConnectionConfig(buildConnectionConfig());

    return connManager;
}

From source file:org.wso2.carbon.mdm.mobileservices.windows.common.authenticator.OAuthTokenValidationStubFactory.java

/**
 * Creates an instance of PoolingHttpClientConnectionManager using HttpClient 4.x APIs
 *
 * @param properties Properties to configure PoolingHttpClientConnectionManager
 * @return An instance of properly configured PoolingHttpClientConnectionManager
 *///from   w w w  . j av  a  2s  .  c  o  m
private HttpClientConnectionManager createClientConnectionManager(Properties properties) {
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    if (properties != null) {
        String maxConnectionsPerHostParam = properties
                .getProperty(PluginConstants.AuthenticatorProperties.MAX_CONNECTION_PER_HOST);
        if (maxConnectionsPerHostParam == null || maxConnectionsPerHostParam.isEmpty()) {
            if (log.isDebugEnabled()) {
                log.debug("MaxConnectionsPerHost parameter is not explicitly defined. Therefore, the default, "
                        + "which is 2, will be used");
            }
        } else {
            connectionManager.setDefaultMaxPerRoute(Integer.parseInt(maxConnectionsPerHostParam));
        }

        String maxTotalConnectionsParam = properties
                .getProperty(PluginConstants.AuthenticatorProperties.MAX_TOTAL_CONNECTIONS);
        if (maxTotalConnectionsParam == null || maxTotalConnectionsParam.isEmpty()) {
            if (log.isDebugEnabled()) {
                log.debug("MaxTotalConnections parameter is not explicitly defined. Therefore, the default, "
                        + "which is 10, will be used");
            }
        } else {
            connectionManager.setMaxTotal(Integer.parseInt(maxTotalConnectionsParam));
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Properties, i.e. MaxTotalConnections/MaxConnectionsPerHost, required to tune the "
                    + "HttpClient used in OAuth token validation service stub instances are not provided. "
                    + "Therefore, the defaults, 2/10 respectively, will be used");
        }
    }
    return connectionManager;
}

From source file:org.apache.zeppelin.sap.universe.UniverseClient.java

public UniverseClient(String user, String password, String apiUrl, String authType, int queryTimeout) {
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(queryTimeout)
            .setSocketTimeout(queryTimeout).build();
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(100);//  ww w .  j  ava2s .com
    cm.setDefaultMaxPerRoute(100);
    cm.closeIdleConnections(10, TimeUnit.MINUTES);
    httpClient = HttpClientBuilder.create().setConnectionManager(cm).setDefaultRequestConfig(requestConfig)
            .build();

    this.user = user;
    this.password = password;
    this.authType = authType;
    if (StringUtils.isNotBlank(apiUrl)) {
        this.apiUrl = apiUrl.replaceAll("/$", "");
    }
}