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

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

Introduction

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

Prototype

public PoolingHttpClientConnectionManager() 

Source Link

Usage

From source file:org.sonatype.nexus.plugins.crowd.client.rest.RestClient.java

RestClient(CrowdPluginConfiguration config) throws URISyntaxException {
    crowdServer = new URI(config.getCrowdServerUrl()).resolve("rest/usermanagement/1/");

    crowdCreds = new UsernamePasswordCredentials(config.getApplicationName(), config.getApplicationPassword());

    // configure the http client
    RequestConfig.Builder reqConfigBuilder = RequestConfig.custom().setAuthenticationEnabled(true)
            .setConnectTimeout(config.getHttpTimeout()).setSocketTimeout(config.getHttpTimeout());

    cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(config.getHttpMaxConnections());
    cm.setDefaultMaxPerRoute(config.getHttpMaxConnections());

    // proxy settings
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    if (StringUtils.isNotBlank(config.getHttpProxyHost()) && config.getHttpProxyPort() > 0) {
        HttpHost proxy = new HttpHost(config.getHttpProxyHost(), config.getHttpProxyPort());
        reqConfigBuilder.setProxy(proxy);

        if (config.getHttpProxyUsername() != null && config.getHttpProxyPassword() != null) {
            credsProvider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials(
                    config.getHttpProxyUsername(), config.getHttpProxyPassword()));
        }//  ww w  . j  a v a 2s . c o m
    }

    RequestConfig reqConfig = reqConfigBuilder.build();
    HttpClientBuilder hcBuilder = HttpClients.custom().setMaxConnPerRoute(config.getHttpMaxConnections())
            .setMaxConnTotal(config.getHttpMaxConnections()).setConnectionManager(cm)
            .setDefaultCredentialsProvider(credsProvider).setDefaultRequestConfig(reqConfig);

    // handling of compressed responses
    hcBuilder.addInterceptorLast(new CompressedHttpResponseInterceptor());

    client = hcBuilder.build();

    if (LOG.isDebugEnabled()) {
        LOG.debug("HTTP Client config");
        LOG.debug(config.getCrowdServerUrl());
        LOG.debug("PROPERTY_THREADPOOL_SIZE:" + cm.getMaxTotal());
        LOG.debug("PROPERTY_READ_TIMEOUT:" + reqConfig.getSocketTimeout());
        LOG.debug("PROPERTY_CONNECT_TIMEOUT:" + reqConfig.getConnectTimeout());
        if (reqConfig.getProxy() != null) {
            LOG.debug("PROPERTY_PROXY_URI:" + reqConfig.getProxy().toString());
        }
        LOG.debug("Crowd application name:" + config.getApplicationName());
    }
}

From source file:org.apache.solr.client.solrj.ConnectionReuseTest.java

@Test
public void testConnectionReuse() throws Exception {

    URL url = cluster.getJettySolrRunners().get(0).getBaseUrl();
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();

    CloseableHttpClient httpClient = HttpClientUtil.createClient(null, cm);
    try (SolrClient client = buildClient(httpClient, url)) {

        HttpHost target = new HttpHost(url.getHost(), url.getPort(), isSSLMode() ? "https" : "http");
        HttpRoute route = new HttpRoute(target);

        ConnectionRequest mConn = getClientConnectionRequest(httpClient, route, cm);

        HttpClientConnection conn1 = getConn(mConn);
        headerRequest(target, route, conn1, cm);

        cm.releaseConnection(conn1, null, -1, TimeUnit.MILLISECONDS);

        int queueBreaks = 0;
        int cnt1 = atLeast(3);
        int cnt2 = atLeast(30);
        for (int j = 0; j < cnt1; j++) {
            boolean done = false;
            for (int i = 0; i < cnt2; i++) {
                AddUpdateCommand c = new AddUpdateCommand(null);
                c.solrDoc = sdoc("id", id.incrementAndGet());
                try {
                    client.add(c.solrDoc);
                } catch (Exception e) {
                    e.printStackTrace();
                }//from ww w.  ja va 2s.  c om
                if (!done && i > 0 && i < cnt2 - 1 && client instanceof ConcurrentUpdateSolrClient
                        && random().nextInt(10) > 8) {
                    queueBreaks++;
                    done = true;
                    Thread.sleep(350); // wait past streaming client poll time of 250ms
                }
            }
            if (client instanceof ConcurrentUpdateSolrClient) {
                ((ConcurrentUpdateSolrClient) client).blockUntilFinished();
            }
        }

        route = new HttpRoute(new HttpHost(url.getHost(), url.getPort(), isSSLMode() ? "https" : "http"));

        mConn = cm.requestConnection(route, null);

        HttpClientConnection conn2 = getConn(mConn);

        HttpConnectionMetrics metrics = conn2.getMetrics();
        headerRequest(target, route, conn2, cm);

        cm.releaseConnection(conn2, null, -1, TimeUnit.MILLISECONDS);

        assertNotNull(
                "No connection metrics found - is the connection getting aborted? server closing the connection? "
                        + client.getClass().getSimpleName(),
                metrics);

        // we try and make sure the connection we get has handled all of the requests in this test
        if (client instanceof ConcurrentUpdateSolrClient) {
            // we can't fully control queue polling breaking up requests - allow a bit of leeway
            int exp = cnt1 + queueBreaks + 2;
            assertTrue(
                    "We expected all communication via streaming client to use one connection! expected=" + exp
                            + " got=" + metrics.getRequestCount(),
                    Math.max(exp, metrics.getRequestCount()) - Math.min(exp, metrics.getRequestCount()) < 3);
        } else {
            assertTrue("We expected all communication to use one connection! "
                    + client.getClass().getSimpleName() + " " + metrics.getRequestCount(),
                    cnt1 * cnt2 + 2 <= metrics.getRequestCount());
        }

    } finally {
        HttpClientUtil.close(httpClient);
    }
}

From source file:com.spectralogic.ds3client.NetworkClientImpl.java

private static CloseableHttpClient createDefaultClient(final ConnectionDetails connectionDetails) {
    final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setDefaultMaxPerRoute(MAX_CONNECTION_PER_ROUTE);
    connectionManager.setMaxTotal(MAX_CONNECTION_TOTAL);

    if (connectionDetails.isHttps() && !connectionDetails.isCertificateVerification()) {
        try {//from   w ww  . jav a2s.com

            final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(final X509Certificate[] chain, final String authType)
                        throws CertificateException {
                    return true;
                }
            }).useTLS().build();

            final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                    new AllowAllHostnameVerifier());
            return HttpClients.custom().setConnectionManager(connectionManager).setSSLSocketFactory(sslsf)
                    .build();

        } catch (final NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
            throw new SSLSetupException(e);
        }
    } else {
        return HttpClients.custom().setConnectionManager(connectionManager).build();
    }
}

From source file:org.cleverbus.core.common.ws.transport.http.CloseableHttpComponentsMessageSender.java

/**
 * Create a new instance of the {@code HttpClientMessageSender} with a default {@link HttpClient}
 * that uses a default {@link org.apache.http.impl.conn.PoolingHttpClientConnectionManager}.
 *//* www.  j  a v  a2s.co  m*/
public CloseableHttpComponentsMessageSender() {
    super();

    PoolingHttpClientConnectionManager connPoolControl = new PoolingHttpClientConnectionManager();
    connPoolControl.closeExpiredConnections();

    this.connPoolControl = connPoolControl;

    // default values which can be overridden
    setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT_MILLISECONDS);
    setReadTimeout(DEFAULT_READ_TIMEOUT_MILLISECONDS);

    clientBuilder.addInterceptorFirst(new RemoveSoapHeadersInterceptor()).setUserAgent(MACHINE_NAME);

    authCache.set(new BasicAuthCache());
}

From source file:org.osiam.client.AuthService.java

private AuthService(Builder builder) {
    endpoint = builder.endpoint;//from w w  w  . ja v a  2s .com
    clientId = builder.clientId;
    clientSecret = builder.clientSecret;
    clientRedirectUri = builder.clientRedirectUri;

    client = ClientBuilder.newClient(new ClientConfig().connectorProvider(new ApacheConnectorProvider())
            .property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.BUFFERED)
            .property(ClientProperties.CONNECT_TIMEOUT, CONNECT_TIMEOUT)
            .property(ClientProperties.READ_TIMEOUT, READ_TIMEOUT)
            .property(ApacheClientProperties.CONNECTION_MANAGER, new PoolingHttpClientConnectionManager())
            .register(HttpAuthenticationFeature.basic(clientId, clientSecret)));

    targetEndpoint = client.target(endpoint);
}

From source file:org.glassfish.jersey.examples.sseitemstore.jaxrs.JaxrsItemStoreResourceTest.java

@Override
protected void configureClient(ClientConfig config) {
    // using AHC as a test client connector to avoid issues with HttpUrlConnection socket management.
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();

    // adjusting max. connections just to be safe - the testEventSourceReconnect is quite greedy...
    cm.setMaxTotal(MAX_LISTENERS * MAX_ITEMS);
    cm.setDefaultMaxPerRoute(MAX_LISTENERS * MAX_ITEMS);

    config.property(ApacheClientProperties.CONNECTION_MANAGER, cm).property(ClientProperties.READ_TIMEOUT, 2000)
            .connectorProvider(new ApacheConnectorProvider());
}

From source file:org.jboss.additional.testsuite.jdkall.present.jaxrs.client.ApacheHttpClient432TestCase.java

@Test
@OperateOnDeployment(DEPLOYMENT)//from   w  w  w .  ja  va  2 s  . co  m
public void apacheHttpClient4EngineServletTest(@ArquillianResource URL url) throws Exception {
    SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).setSoKeepAlive(true)
            .setSoReuseAddress(true).build();

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();

    connManager.setMaxTotal(100);

    connManager.setDefaultMaxPerRoute(100);

    connManager.setDefaultSocketConfig(socketConfig);

    RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(100)
            .setConnectionRequestTimeout(3000).setStaleConnectionCheckEnabled(true).build();

    CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig)
            .setConnectionManager(connManager).build();

    final ClientHttpEngine executor;

    executor = new ApacheHttpClient43Engine(httpClient);

    ResteasyClient client = new ResteasyClientBuilder().httpEngine(executor).build();

    final ApacheHttpClient43Resource proxy = client
            .target("http://127.0.0.1:8080/" + ApacheHttpClient432TestCase.class.getSimpleName())
            .proxy(ApacheHttpClient43Resource.class);

    WebTarget target = client
            .target("http://127.0.0.1:8080/" + ApacheHttpClient432TestCase.class.getSimpleName() + "/test2");

    Response response = target.request().get();
    Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());

    try {
        Response s = proxy.get();

        assertEquals(200, s.getStatus());
    } catch (ProcessingException e) {
        logger.warn("Exception occured." + e);

    } finally {
        if (response != null) {
            response.close();
        }
    }
}

From source file:com.continuuity.loom.scheduler.callback.HttpPostClusterCallback.java

public void initialize(Configuration conf, ClusterStoreService clusterStoreService) {
    this.clusterStoreService = clusterStoreService;
    this.onStartUrl = conf.get(Constants.HttpCallback.START_URL);
    this.onSuccessUrl = conf.get(Constants.HttpCallback.SUCCESS_URL);
    this.onFailureUrl = conf.get(Constants.HttpCallback.FAILURE_URL);
    this.startTriggerActions = parseActionsString(
            conf.get(Constants.HttpCallback.START_TRIGGERS, Constants.HttpCallback.DEFAULT_START_TRIGGERS));
    this.successTriggerActions = parseActionsString(
            conf.get(Constants.HttpCallback.SUCCESS_TRIGGERS, Constants.HttpCallback.DEFAULT_SUCCESS_TRIGGERS));
    this.failureTriggerActions = parseActionsString(
            conf.get(Constants.HttpCallback.FAILURE_TRIGGERS, Constants.HttpCallback.DEFAULT_FAILURE_TRIGGERS));
    if (onStartUrl != null) {
        LOG.debug("before hook will be triggered on actions {}", Joiner.on(',').join(startTriggerActions));
    }/*from   w w  w .ja v  a  2s  .c  om*/
    if (onSuccessUrl != null) {
        LOG.debug("after hook will be triggered on actions {}", Joiner.on(',').join(successTriggerActions));
    }
    if (onFailureUrl != null) {
        LOG.debug("after hook will be triggered on actions {}", Joiner.on(',').join(failureTriggerActions));
    }

    int maxConnections = conf.getInt(Constants.HttpCallback.MAX_CONNECTIONS,
            Constants.HttpCallback.DEFAULT_MAX_CONNECTIONS);
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setDefaultMaxPerRoute(maxConnections);
    connectionManager.setMaxTotal(maxConnections);

    SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(
            conf.getInt(Constants.HttpCallback.SOCKET_TIMEOUT, Constants.HttpCallback.DEFAULT_SOCKET_TIMEOUT))
            .build();
    connectionManager.setDefaultSocketConfig(socketConfig);
    this.httpClient = HttpClientBuilder.create().setConnectionManager(connectionManager).build();
}

From source file:org.apereo.portal.soffit.connector.SoffitConnectorController.java

@PostConstruct
public void init() {
    PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
    poolingHttpClientConnectionManager.setDefaultMaxPerRoute(maxConnectionsPerRoute);
    poolingHttpClientConnectionManager.setMaxTotal(maxConnectionsTotal);
    httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager);

    final Map<String, IHeaderProvider> beans = BeanFactoryUtils
            .beansOfTypeIncludingAncestors(applicationContext, IHeaderProvider.class);
    final List<IHeaderProvider> values = new ArrayList<>(beans.values());
    headerProviders = Collections.unmodifiableList(values);
}

From source file:dal.arris.DeviceDAO.java

private void prepare() {
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(1);/*from ww  w.j av a  2 s  . c  om*/
    cm.setDefaultMaxPerRoute(1);
    HttpHost ip = new HttpHost("10.200.6.150", 80);
    cm.setMaxPerRoute(new HttpRoute(ip), 50);

    // Cookies
    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

    httpclient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(globalConfig).build();

    String auth = end.getCred().getUser() + ":" + end.getCred().getPass();
    byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("UTF-8")));
    authHeader = "Basic " + new String(encodedAuth);

    localConfig = RequestConfig.copy(globalConfig).setCookieSpec(CookieSpecs.STANDARD_STRICT).build();

}