Example usage for org.apache.http.impl.client HttpClientBuilder setConnectionManager

List of usage examples for org.apache.http.impl.client HttpClientBuilder setConnectionManager

Introduction

In this page you can find the example usage for org.apache.http.impl.client HttpClientBuilder setConnectionManager.

Prototype

public final HttpClientBuilder setConnectionManager(final HttpClientConnectionManager connManager) 

Source Link

Document

Assigns HttpClientConnectionManager instance.

Usage

From source file:com.twinsoft.convertigo.engine.util.HttpUtils.java

@SuppressWarnings("deprecation")
public static CloseableHttpClient makeHttpClient4(boolean usePool) {
    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    httpClientBuilder.setDefaultRequestConfig(
            RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build());

    if (usePool) {
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();

        int maxTotalConnections = 100;
        try {//from   w w w  .  j a  v  a  2s.c om
            maxTotalConnections = new Integer(
                    EnginePropertiesManager.getProperty(PropertyName.HTTP_CLIENT_MAX_TOTAL_CONNECTIONS))
                            .intValue();
        } catch (NumberFormatException e) {
            Engine.logEngine.warn("Unable to retrieve the max number of connections; defaults to 100.");
        }

        int maxConnectionsPerHost = 50;
        try {
            maxConnectionsPerHost = new Integer(
                    EnginePropertiesManager.getProperty(PropertyName.HTTP_CLIENT_MAX_CONNECTIONS_PER_HOST))
                            .intValue();
        } catch (NumberFormatException e) {
            Engine.logEngine
                    .warn("Unable to retrieve the max number of connections per host; defaults to 100.");
        }

        connManager.setDefaultMaxPerRoute(maxConnectionsPerHost);
        connManager.setMaxTotal(maxTotalConnections);

        httpClientBuilder.setConnectionManager(connManager);
    }

    return httpClientBuilder.build();
}

From source file:org.elasticsearch.client.SSLSocketFactoryHttpConfigCallback.java

@Override
public void customizeHttpClient(HttpClientBuilder httpClientBuilder) {
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry);/*from  ww w  .j  a va2  s  . c o m*/
    //default settings may be too constraining
    connectionManager.setDefaultMaxPerRoute(10);
    connectionManager.setMaxTotal(30);
    httpClientBuilder.setConnectionManager(connectionManager);
}

From source file:com.microsoft.windowsazure.core.pipeline.apache.ApacheConfigSettings.java

/**
 * Update the given {@link HttpClientBuilder} object with the appropriate
 * settings from configuration./*from   www . j a va  2s .com*/
 * 
 * @param httpClientBuilder
 *            The object to update.
 * @return The updates httpClientBuilder
 */
public HttpClientBuilder applyConfig(HttpClientBuilder httpClientBuilder) {
    if (properties
            .containsKey(profile + ApacheConfigurationProperties.PROPERTY_SSL_CONNECTION_SOCKET_FACTORY)) {
        httpClientBuilder.setSSLSocketFactory((LayeredConnectionSocketFactory) properties
                .get(profile + ApacheConfigurationProperties.PROPERTY_SSL_CONNECTION_SOCKET_FACTORY));
    }

    if (properties.containsKey(profile + ApacheConfigurationProperties.PROPERTY_CONNECTION_MANAGER)) {
        httpClientBuilder.setConnectionManager((HttpClientConnectionManager) properties
                .get(profile + ApacheConfigurationProperties.PROPERTY_CONNECTION_MANAGER));
    }

    if (properties.containsKey(profile + ApacheConfigurationProperties.PROPERTY_PROXY_URI)) {
        httpClientBuilder.setProxy(new HttpHost(
                (String) properties.get(profile + ApacheConfigurationProperties.PROPERTY_PROXY_URI)));
    }

    if (properties.containsKey(profile + ApacheConfigurationProperties.PROPERTY_RETRY_HANDLER)) {
        httpClientBuilder.setRetryHandler((HttpRequestRetryHandler) properties
                .get(profile + ApacheConfigurationProperties.PROPERTY_RETRY_HANDLER));
    }

    if (properties.containsKey(profile + ApacheConfigurationProperties.PROPERTY_HTTP_CLIENT_BUILDER)) {
        return (HttpClientBuilder) properties
                .get(profile + ApacheConfigurationProperties.PROPERTY_HTTP_CLIENT_BUILDER);
    }

    if (properties.containsKey(profile + ApacheConfigurationProperties.PROPERTY_REDIRECT_STRATEGY)) {
        httpClientBuilder.setRedirectStrategy((DefaultRedirectStrategy) properties
                .get(profile + ApacheConfigurationProperties.PROPERTY_REDIRECT_STRATEGY));

        // Currently the redirect strategy, due to what seems to be a bug,
        // fails for post requests since it tries do double
        // add the content-length header. This workaround makes sure this header is always
        // removed before it is actually processed by apache
        httpClientBuilder.addInterceptorFirst(new HttpHeaderRemovalFilter());
    }

    if (properties.containsKey("AuthFilter")) {
        @SuppressWarnings("unchecked")
        ServiceRequestFilter filter = (ServiceRequestFilter) properties.get("AuthFilter");
        httpClientBuilder.addInterceptorFirst(new FilterInterceptor(filter));
    }

    if (properties.containsKey(profile + Configuration.PROPERTY_HTTP_PROXY_HOST)
            && properties.containsKey(profile + Configuration.PROPERTY_HTTP_PROXY_PORT)) {
        String proxyHost = (String) properties.get(profile + Configuration.PROPERTY_HTTP_PROXY_HOST);
        int proxyPort = Integer
                .parseInt((String) properties.get(profile + Configuration.PROPERTY_HTTP_PROXY_PORT));
        HttpHost proxy;
        if (properties.containsKey(profile + Configuration.PROPERTY_HTTP_PROXY_SCHEME)) {
            proxy = new HttpHost(proxyHost, proxyPort,
                    (String) properties.get(profile + Configuration.PROPERTY_HTTP_PROXY_SCHEME));
        } else {
            proxy = new HttpHost(proxyHost, proxyPort);
        }
        httpClientBuilder.setProxy(proxy);
    }

    return httpClientBuilder;
}

From source file:com.liferay.sync.engine.session.Session.java

public Session(URL url, String oAuthConsumerKey, String oAuthConsumerSecret, String oAuthToken,
        String oAuthTokenSecret, boolean trustSelfSigned, int maxConnections) {

    if (maxConnections == Integer.MAX_VALUE) {
        _executorService = Executors.newCachedThreadPool();
    } else {/*  w  ww  .  j a v a  2 s .  c  om*/
        _executorService = Executors.newFixedThreadPool(maxConnections);
    }

    HttpClientBuilder httpClientBuilder = createHttpClientBuilder(trustSelfSigned, maxConnections);

    httpClientBuilder.setConnectionManager(_getHttpClientConnectionManager(trustSelfSigned));

    _httpClient = httpClientBuilder.build();

    _httpHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());

    _oAuthConsumer = new CommonsHttpOAuthConsumer(oAuthConsumerKey, oAuthConsumerSecret);

    _oAuthConsumer.setTokenWithSecret(oAuthToken, oAuthTokenSecret);

    _oAuthEnabled = true;
}

From source file:com.liferay.sync.engine.session.Session.java

public Session(URL url, String login, String password, boolean trustSelfSigned, int maxConnections) {

    if (maxConnections == Integer.MAX_VALUE) {
        _executorService = Executors.newCachedThreadPool();
    } else {//from w  w  w . j  a  va 2 s .  c  o  m
        _executorService = Executors.newFixedThreadPool(maxConnections);
    }

    HttpClientBuilder httpClientBuilder = createHttpClientBuilder(trustSelfSigned, maxConnections);

    httpClientBuilder.setConnectionManager(_getHttpClientConnectionManager(trustSelfSigned));

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

    _httpHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());

    credentialsProvider.setCredentials(new AuthScope(_httpHost),
            new UsernamePasswordCredentials(login, password));

    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);

    _httpClient = httpClientBuilder.build();

    _oAuthEnabled = false;
}

From source file:net.sf.jasperreports.data.http.HttpDataService.java

protected CloseableHttpClient createHttpClient(Map<String, Object> parameters) {
    HttpClientBuilder clientBuilder = HttpClients.custom();

    // single connection
    BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager();
    clientBuilder.setConnectionManager(connManager);

    // ignore cookies for now
    RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
    clientBuilder.setDefaultRequestConfig(requestConfig);

    setAuthentication(parameters, clientBuilder);

    CloseableHttpClient client = clientBuilder.build();
    return client;
}

From source file:leap.webunit.client.THttpClientImpl.java

protected HttpClient createDefaultHttpClient() {
    HttpClientBuilder cb = HttpClientBuilder.create();

    //TODO : small buffer size will cause socket closed when reading response entity?
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(getDefaultRegistry(),
            this.dnsResolver);
    //cm.setDefaultConnectionConfig(ConnectionConfig.custom().setBufferSize(1024 * 1024).build());

    cb.setConnectionManager(cm);
    cb.setDefaultCookieStore(this.cookieStore);
    cb.setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override//from w  w w  . ja v a2 s.  c  om
        public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                throws ProtocolException {
            if (!autoRedirect) {
                return false;
            }
            return super.isRedirected(request, response, context);
        }
    });

    return cb.build();
}

From source file:org.dasein.cloud.azure.Azure.java

public HttpClientBuilder getAzureClientBuilder() throws CloudException {
    try {/*from  w  w w . jav a  2s.co m*/
        HttpClientBuilder builder = HttpClientBuilder.create();
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", new AzureSSLSocketFactory(new AzureX509(this))).build();
        HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);
        builder.setConnectionManager(ccm);
        return builder;
    } catch (Exception e) {
        throw new CloudException(e.getMessage());
    }
}

From source file:org.duracloud.common.web.RestHttpHelper.java

private HttpResponse executeRequest(String url, Method method, HttpEntity requestEntity,
        Map<String, String> headers) throws IOException {
    if (url == null || url.length() == 0) {
        throw new IllegalArgumentException("URL must be a non-empty value");
    }/*from  w w w.j  a  va 2  s  .  c o m*/

    HttpRequestBase httpRequest = method.getMethod(url, requestEntity);

    if (headers != null && headers.size() > 0) {
        addHeaders(httpRequest, headers);
    }

    if (log.isDebugEnabled()) {
        log.debug(loggingRequestText(url, method, requestEntity, headers));
    }

    org.apache.http.HttpResponse response;
    if (null != credsProvider) {

        HttpClientBuilder builder = HttpClients.custom().setDefaultCredentialsProvider(credsProvider);

        if (socketTimeoutMs > -1) {
            BasicHttpClientConnectionManager cm = new BasicHttpClientConnectionManager();
            cm.setSocketConfig(SocketConfig.custom().setSoTimeout(socketTimeoutMs).build());
            builder.setConnectionManager(cm);
        }

        CloseableHttpClient httpClient = buildClient(builder, method);

        // Use preemptive basic auth
        URI requestUri = httpRequest.getURI();
        HttpHost target = new HttpHost(requestUri.getHost(), requestUri.getPort(), requestUri.getScheme());
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(target, basicAuth);
        HttpClientContext localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);
        response = httpClient.execute(httpRequest, localContext);
    } else {
        CloseableHttpClient httpClient = buildClient(HttpClients.custom(), method);
        response = httpClient.execute(httpRequest);
    }

    HttpResponse httpResponse = new HttpResponse(response);

    if (log.isDebugEnabled()) {
        log.debug(loggingResponseText(httpResponse));
    }

    return httpResponse;
}