Example usage for org.apache.http.impl.conn PoolingClientConnectionManager PoolingClientConnectionManager

List of usage examples for org.apache.http.impl.conn PoolingClientConnectionManager PoolingClientConnectionManager

Introduction

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

Prototype

public PoolingClientConnectionManager(final SchemeRegistry schreg) 

Source Link

Usage

From source file:org.craftercms.profile.impl.ProfileRestClientService.java

private DefaultHttpClient getHttpClient(int connectionTimeOut, int sockeTimeOut) {
    try {//from  w  ww. ja  v a2s . c o  m

        HttpParams httpParams = new BasicHttpParams();

        setParams(httpParams, connectionTimeOut, sockeTimeOut);

        SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", port, PlainSocketFactory.getSocketFactory()));
        registry.register(new Scheme("https", sslPort, sf));

        PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(registry);
        HttpHost localhost = new HttpHost(host, port);
        ccm.setMaxPerRoute(new HttpRoute(localhost), maxPerRoute);
        ccm.setMaxTotal(maxTotal);
        ccm.setDefaultMaxPerRoute(defaultMaxPerRoute);
        return new DefaultHttpClient(ccm, httpParams);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return new DefaultHttpClient();
    }
}

From source file:org.jboss.as.test.manualmode.web.ssl.SSLTruststoreUtil.java

public static DefaultHttpClient getHttpClientWithSSL(File keyStoreFile, String keyStorePassword,
        File trustStoreFile, String trustStorePassword) {

    try {//w  w w .j  a  va 2  s  .  c o  m
        final KeyStore truststore = loadKeyStore(trustStoreFile, trustStorePassword.toCharArray());
        final KeyStore keystore = keyStoreFile != null
                ? loadKeyStore(keyStoreFile, keyStorePassword.toCharArray())
                : null;
        final SSLSocketFactory ssf = new SSLSocketFactory(SSLSocketFactory.TLS, keystore, keyStorePassword,
                truststore, null, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", CustomCLIExecutor.MANAGEMENT_HTTP_PORT,
                PlainSocketFactory.getSocketFactory()));
        registry.register(new Scheme("https", CustomCLIExecutor.MANAGEMENT_HTTPS_PORT, ssf));
        for (int port : HTTPSWebConnectorTestCase.HTTPS_PORTS) {
            registry.register(new Scheme("https", port, ssf));
        }
        ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);
        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        LOGGER.error(
                "Creating HttpClient with customized SSL failed. We are returning the default one instead.", e);
        return new DefaultHttpClient();
    }
}

From source file:org.mule.modules.freshbooks.api.DefaultFreshBooksClient.java

/**
 * Constructor for Authentication Token mechanism
 * //from  w ww .ja va2  s.  c  o  m
 * @param apiUrl
 *            url for API
 * @param authenticationToken
 *            authentication token value
 * @param maxTotalConnection
 *            max total connections for client
 * @param defaultMaxConnectionPerRoute
 *            default max connection per route for client
 */
public DefaultFreshBooksClient(String apiUrl, String authenticationToken, int maxTotalConnection,
        int defaultMaxConnectionPerRoute) {
    Validate.notEmpty(apiUrl);
    Validate.notEmpty(authenticationToken);
    try {
        this.apiUrl = new URL(apiUrl);
    } catch (MalformedURLException e) {
        throw new FreshBooksException(e.getMessage());
    }

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

    PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
    // max total connections
    cm.setMaxTotal(maxTotalConnection);
    // default max connection per route
    cm.setDefaultMaxPerRoute(defaultMaxConnectionPerRoute);

    client = new DefaultHttpClient(cm);
    this.client.getCredentialsProvider().setCredentials(
            new AuthScope(this.apiUrl.getHost(), 443, AuthScope.ANY_REALM),
            new UsernamePasswordCredentials(authenticationToken, ""));

    client.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {

        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount > 3) {
                logger.warn("Maximum tries reached for client http pool ");
                return false;
            }
            if (exception instanceof org.apache.http.NoHttpResponseException) {
                logger.warn("No response from server on " + executionCount + " call");
                return true;
            }
            return false;
        }
    });
}

From source file:org.mule.modules.freshbooks.api.DefaultFreshBooksClient.java

/**
 * Constructor for OAuth1.0a mechanism// ww  w  .j  av  a2  s  .com
 * 
 * @param apiUrl
 *            url for API
 * @param consumerKey
 *            consumerKey value
 * @param consumerSecret
 *            consumerSecret value
 * @param maxTotalConnection
 *            max total connections for client
 * @param defaultMaxConnectionPerRoute
 *            default max connection per route for client
 */
public DefaultFreshBooksClient(String apiUrl, String consumerKey, String consumerSecret, int maxTotalConnection,
        int defaultMaxConnectionPerRoute) {
    Validate.notEmpty(apiUrl);

    try {
        this.apiUrl = new URL(apiUrl);
    } catch (MalformedURLException e) {
        throw new FreshBooksException(e.getMessage());
    }

    this.consumerKey = consumerKey;
    this.consumerSecret = consumerSecret;

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

    PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
    // max total connections
    cm.setMaxTotal(maxTotalConnection);
    // default max connection per route
    cm.setDefaultMaxPerRoute(defaultMaxConnectionPerRoute);

    client = new DefaultHttpClient(cm);
    client.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {

        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount > 3) {
                logger.warn("Maximum tries reached for client http pool ");
                return false;
            }
            if (exception instanceof org.apache.http.NoHttpResponseException) {
                logger.warn("No response from server on " + executionCount + " call");
                return true;
            }
            return false;
        }
    });
}

From source file:org.rhq.modules.plugins.wildfly10.ASConnection.java

public ASConnection(ASConnectionParams params) {
    asConnectionParams = params;//ww w  .j  a v  a2s  . c  om

    // Check and store the basic parameters
    if (asConnectionParams.getHost() == null) {
        throw new IllegalArgumentException("Management host cannot be null.");
    }
    if (asConnectionParams.getPort() <= 0 || asConnectionParams.getPort() > 65535) {
        throw new IllegalArgumentException("Invalid port: " + asConnectionParams.getPort());
    }

    UsernamePasswordCredentials credentials = null;
    if (asConnectionParams.getUsername() != null && asConnectionParams.getPassword() != null) {
        credentials = new UsernamePasswordCredentials(asConnectionParams.getUsername(),
                asConnectionParams.getPassword());
    }

    keepAliveTimeout = asConnectionParams.getKeepAliveTimeout();

    managementUri = buildManagementUri();

    // Each ASConnection instance will have its own HttpClient instance. Setup begins here

    SchemeRegistry schemeRegistry = new SchemeRegistryBuilder(asConnectionParams).buildSchemeRegistry();

    // HttpClient will use a pooling connection manager to allow concurrent request processing
    PoolingClientConnectionManager httpConnectionManager = new PoolingClientConnectionManager(schemeRegistry);
    httpConnectionManager.setDefaultMaxPerRoute(MAX_POOLED_CONNECTIONS);
    httpConnectionManager.setMaxTotal(MAX_POOLED_CONNECTIONS);

    httpClient = new DefaultHttpClient(httpConnectionManager);
    HttpParams httpParams = httpClient.getParams();

    // Disable stale connection checking on connection lease to get better performance
    // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html
    HttpConnectionParams.setStaleCheckingEnabled(httpParams, false);

    httpClient.setReuseStrategy(new CustomConnectionReuseStrategy(this));
    if (keepAliveTimeout > 0) {
        httpClient.setKeepAliveStrategy(new CustomConnectionKeepAliveStrategy(this));
        // Initial schedule of a cleaning task. Subsequent executions will be scheduled as needed.
        // See ConnectionManagerCleaner implementation.
        cleanerExecutor.schedule(new ConnectionManagerCleaner(this), keepAliveTimeout / 2,
                TimeUnit.MILLISECONDS);
    }

    HttpClientParams.setRedirecting(httpParams, false);

    if (credentials != null) {
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(asConnectionParams.getHost(), asConnectionParams.getPort()), credentials);
    }

    mapper = new ObjectMapper();
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    shutdown = false;
}

From source file:rapture.common.client.BaseHttpApi.java

private static HttpClient getHttpClient() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

    PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
    // Increase max total connection to 200
    cm.setMaxTotal(200);/* w w  w  .j  ava 2s .  c  o  m*/
    // Increase default max connection per route to 20
    cm.setDefaultMaxPerRoute(20);
    // Increase max connections for localhost:80 to 50
    HttpHost localhost = new HttpHost("locahost", 80);
    cm.setMaxPerRoute(new HttpRoute(localhost), 50);

    DefaultHttpClient httpClient = new DefaultHttpClient(cm);
    // Use a proxy if it is defined - we need to pass this on to the
    // HttpClient
    if (System.getProperties().containsKey("http.proxyHost")) {
        String host = System.getProperty("http.proxyHost");
        String port = System.getProperty("http.proxyPort", "8080");
        HttpHost proxy = new HttpHost(host, Integer.parseInt(port));
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {

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

    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {

        @Override
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            if (log.isTraceEnabled()) {
                log.trace("Response Headers:");
                for (Header h : response.getAllHeaders()) {
                    log.trace(h.getName() + " : " + h.getValue());
                }
            }
            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;
                        }
                    }
                }
            }
        }

    });

    return httpClient;
}