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

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

Introduction

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

Prototype

public void setDefaultSocketConfig(final SocketConfig defaultSocketConfig) 

Source Link

Usage

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

private HttpClientConnectionManager getClientConnectionManager() throws Exception {
    RegistryBuilder<ConnectionSocketFactory> sfr = RegistryBuilder.create();

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

    if (SystemProperties.isSslEnabled()) {
        sfr.register("https", createSSLSocketFactory());
    }/*from w  ww .  ja  v  a 2  s. c o  m*/

    SocketConfig.Builder sockBuilder = SocketConfig.custom().setTcpNoDelay(true);
    sockBuilder.setSoLinger(SystemProperties.getClientProxyHttpClientSoLinger());
    sockBuilder.setSoTimeout(SystemProperties.getClientProxyHttpClientTimeout());
    SocketConfig socketConfig = sockBuilder.build();

    PoolingHttpClientConnectionManager poolingManager = new PoolingHttpClientConnectionManager(sfr.build());
    poolingManager.setMaxTotal(SystemProperties.getClientProxyPoolTotalMaxConnections());
    poolingManager.setDefaultMaxPerRoute(SystemProperties.getClientProxyPoolDefaultMaxConnectionsPerRoute());
    poolingManager.setDefaultSocketConfig(socketConfig);
    poolingManager.setValidateAfterInactivity(
            SystemProperties.getClientProxyValidatePoolConnectionsAfterInactivityMs());

    return poolingManager;
}

From source file:com.aliyun.oss.common.comm.DefaultServiceClient.java

protected HttpClientConnectionManager createHttpClientConnectionManager() {
    SSLContext sslContext = null;
    try {//w w  w. ja va2 s.  co m
        sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }

        }).build();

    } catch (Exception e) {
        throw new ClientException(e.getMessage());
    }

    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
            NoopHostnameVerifier.INSTANCE);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register(Protocol.HTTP.toString(), PlainConnectionSocketFactory.getSocketFactory())
            .register(Protocol.HTTPS.toString(), sslSocketFactory).build();

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry);
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnections());
    connectionManager.setMaxTotal(config.getMaxConnections());
    connectionManager.setValidateAfterInactivity(config.getValidateAfterInactivity());
    connectionManager.setDefaultSocketConfig(
            SocketConfig.custom().setSoTimeout(config.getSocketTimeout()).setTcpNoDelay(true).build());
    if (config.isUseReaper()) {
        IdleConnectionReaper.setIdleConnectionTime(config.getIdleConnectionTime());
        IdleConnectionReaper.registerConnectionManager(connectionManager);
    }
    return connectionManager;
}

From source file:com.baidubce.http.BceHttpClient.java

/**
 * Create connection manager for http client.
 *
 * @return The connection manager for http client.
 *///from w w  w.  ja  v a2  s . c om
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.iipg.hurricane.jmx.client.JMXClientBuilder.java

private PoolingHttpClientConnectionManager createPoolingConnectionManager() {
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
            getSocketFactoryRegistry(), getConnectionFactory());
    connManager.setDefaultSocketConfig(createSocketConfig());
    connManager.setDefaultConnectionConfig(createConnectionConfig());
    if (maxTotalConnections != 0) {
        connManager.setMaxTotal(maxTotalConnections);
    }/*  w w  w.ja  v a2  s  .  co  m*/
    return connManager;
}

From source file:org.duniter.core.client.service.HttpServiceImpl.java

protected PoolingHttpClientConnectionManager createConnectionManager(int maxTotalConnections,
        int maxConnectionsPerRoute, int timeout) {
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(maxTotalConnections);
    connectionManager.setDefaultMaxPerRoute(maxConnectionsPerRoute);
    connectionManager.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(timeout).build());
    return connectionManager;
}

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

public ServerConnection(int timeout, String[] httpsProtocols, String[] httpsCipherSuites, boolean allowHTTP) {
    SSLContext sslContext = null;
    try {//from   w w  w. j  av  a2 s  .  c  o 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:com.github.lpezet.antiope.dao.DefaultHttpClientFactory.java

@Override
public HttpClient createHttpClient(APIConfiguration pConfiguration) {

    // Use a custom connection factory to customize the process of
    // initialization of outgoing HTTP connections. Beside standard connection
    // configuration parameters HTTP connection factory can define message
    // parser / writer routines to be employed by individual connections.
    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> oConnFactory = new ManagedHttpClientConnectionFactory(
            new DefaultHttpRequestWriterFactory(), new DefaultHttpResponseParserFactory());

    SSLContext oSslContext = null;
    X509HostnameVerifier oHostnameVerifier = null;
    if (pConfiguration.isCheckSSLCertificates()) {
        oSslContext = SSLContexts.createSystemDefault();
        oHostnameVerifier = new BrowserCompatHostnameVerifier();
    } else {/* ww  w  .  jav a  2s  .c  o m*/
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
            }

            @Override
            public void checkServerTrusted(final X509Certificate[] chain, final String authType) {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };

        // Install the all-trusting trust manager
        try {
            final SSLContext sslContext = SSLContext.getInstance(SSL);
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // Create an ssl socket factory with our all-trusting manager
            //final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            oSslContext = sslContext;
        } catch (NoSuchAlgorithmException e) {
            throw new APIClientException(e);
        } catch (KeyManagementException e) {
            throw new APIClientException(e);
        }
        oHostnameVerifier = new AllowAllHostnameVerifier();
    }

    // Create a registry of custom connection socket factories for supported
    // protocol schemes.
    Registry<ConnectionSocketFactory> oSocketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register(HTTP, PlainConnectionSocketFactory.INSTANCE)
            .register(HTTPS, new SSLConnectionSocketFactory(oSslContext, oHostnameVerifier)).build();

    // Use custom DNS resolver to override the system DNS resolution.
    DnsResolver oDnsResolver = new SystemDefaultDnsResolver(); /* {
                                                               @Override
                                                               public InetAddress[] resolve(final String host) throws UnknownHostException {
                                                               if (host.equalsIgnoreCase("myhost")) {
                                                               return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) };
                                                               } else {
                                                               return super.resolve(host);
                                                               }
                                                               }
                                                               };*/

    // Create a connection manager with custom configuration.
    PoolingHttpClientConnectionManager oConnManager = new PoolingHttpClientConnectionManager(
            oSocketFactoryRegistry, oConnFactory, oDnsResolver);

    // Create socket configuration
    SocketConfig oSocketConfig = SocketConfig.custom().setTcpNoDelay(true)
            .setSoTimeout(pConfiguration.getSocketTimeout()).build();

    // Configure the connection manager to use socket configuration either
    // by default or for a specific host.
    oConnManager.setDefaultSocketConfig(oSocketConfig);
    // connManager.setSocketConfig(new HttpHost("somehost", 80), oSocketConfig);

    // Create message constraints
    MessageConstraints oMessageConstraints = MessageConstraints.custom().setMaxHeaderCount(200)
            .setMaxLineLength(2000).build();
    // Create connection configuration
    ConnectionConfig oConnectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8)
            .setMessageConstraints(oMessageConstraints).build();
    // Configure the connection manager to use connection configuration either
    // by default or for a specific host.
    oConnManager.setDefaultConnectionConfig(oConnectionConfig);
    // connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT);

    // Configure total max or per route limits for persistent connections
    // that can be kept in the pool or leased by the connection manager.
    oConnManager.setMaxTotal(100);
    oConnManager.setDefaultMaxPerRoute(10);
    //oConnManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20);

    // Use custom cookie store if necessary.
    CookieStore oCookieStore = new BasicCookieStore();
    // Use custom credentials provider if necessary.
    //
    // Create global request configuration
    RequestConfig oDefaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH)
            //.setExpectContinueEnabled(true)         // WARNING: setting it to true slows things down by 4s!!!!
            .setStaleConnectionCheckEnabled(true)
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
            .setConnectTimeout(pConfiguration.getConnectionTimeout()).build();

    CredentialsProvider oCredentialsProvider = new BasicCredentialsProvider();
    HttpHost oProxy = null;

    if (pConfiguration.getProxyHost() != null && pConfiguration.getProxyPort() > 0) {
        String proxyHost = pConfiguration.getProxyHost();
        int proxyPort = pConfiguration.getProxyPort();
        String proxyUsername = pConfiguration.getProxyUsername();
        String proxyPassword = pConfiguration.getProxyPassword();
        String proxyDomain = pConfiguration.getProxyDomain();
        String proxyWorkstation = pConfiguration.getProxyWorkstation();

        oProxy = new HttpHost(proxyHost, proxyPort);

        if (proxyUsername != null && proxyPassword != null) {
            oCredentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
        }
    }

    // Create an HttpClient with the given custom dependencies and configuration.
    CloseableHttpClient oHttpClient = HttpClients.custom().setConnectionManager(oConnManager)
            .setDefaultCookieStore(oCookieStore).setDefaultCredentialsProvider(oCredentialsProvider)
            .setProxy(oProxy).setDefaultRequestConfig(oDefaultRequestConfig).build();

    return oHttpClient;
    /*
    RequestConfig oRequestConfig = RequestConfig.custom()
    .setConnectTimeout(pConfiguration.getConnectionTimeout())
    .setSocketTimeout(pConfiguration.getSocketTimeout())
    .setStaleConnectionCheckEnabled(true)
    .build();
    */
}

From source file:com.gooddata.GoodData.java

private HttpClientBuilder createHttpClientBuilder(final GoodDataSettings settings) {
    final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setDefaultMaxPerRoute(settings.getMaxConnections());
    connectionManager.setMaxTotal(settings.getMaxConnections());

    final SocketConfig.Builder socketConfig = SocketConfig.copy(SocketConfig.DEFAULT);
    socketConfig.setSoTimeout(settings.getSocketTimeout());
    connectionManager.setDefaultSocketConfig(socketConfig.build());

    final RequestConfig.Builder requestConfig = RequestConfig.copy(RequestConfig.DEFAULT);
    requestConfig.setConnectTimeout(settings.getConnectionTimeout());
    requestConfig.setConnectionRequestTimeout(settings.getConnectionRequestTimeout());
    requestConfig.setSocketTimeout(settings.getSocketTimeout());

    return HttpClientBuilder.create()
            .setUserAgent(StringUtils.isNotBlank(settings.getUserAgent())
                    ? String.format("%s %s", settings.getUserAgent(), getUserAgent())
                    : getUserAgent())/*  ww  w  . ja v  a  2  s  .  c  o  m*/
            .setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig.build());
}

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);//from   w  ww.  j  a va 2  s  .c  o m
    } 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:com.joyent.manta.http.MantaConnectionFactory.java

/**
 * Configures a connection manager with all of the setting needed to connect
 * to Manta./*from  w  ww .  j  av  a 2s.  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;
}