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:com.ittm_solutions.ipacore.IpaApi.java

/**
 * Returns the connection manager used for all connections to the IPA
 * server.// w w  w  .  j  ava  2s .  c o m
 * <p>
 * This method initializes the connection manager on its first call,
 * subsequent calls return the same instance.
 *
 * @return connection manager
 */
private PoolingHttpClientConnectionManager connectionManager() {
    if (connectionManager == null) {
        connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(10);
        // There must be only one connection as IPA fails otherwise
        connectionManager.setDefaultMaxPerRoute(1);
    }

    return connectionManager;
}

From source file:com.floragunn.searchguard.HeaderAwareJestClientFactory.java

protected HttpClientConnectionManager createConnectionManager() {
    if (httpClientConfig.isMultiThreaded()) {
        log.debug("Multi-threaded http connection manager created");
        final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        final Integer maxTotal = httpClientConfig.getMaxTotalConnection();
        if (maxTotal != null) {
            cm.setMaxTotal(maxTotal);//from w  ww .  ja  v a2s  .c  om
        }
        final Integer defaultMaxPerRoute = httpClientConfig.getDefaultMaxTotalConnectionPerRoute();
        if (defaultMaxPerRoute != null) {
            cm.setDefaultMaxPerRoute(defaultMaxPerRoute);
        }
        final Map<HttpRoute, Integer> maxPerRoute = httpClientConfig.getMaxTotalConnectionPerRoute();
        for (final HttpRoute route : maxPerRoute.keySet()) {
            cm.setMaxPerRoute(route, maxPerRoute.get(route));
        }
        return cm;
    }
    log.debug("Default http connection is created without multi threaded option");
    return new BasicHttpClientConnectionManager();
}

From source file:com.redhat.red.offliner.ftest.SinglePlaintextDownloadOfTarballFTest.java

@Test
public void testGenericTarballDownload() throws Exception {
    // Generate some test content
    String path = contentGenerator.newArtifactPath("tar.gz");
    Map<String, byte[]> entries = new HashMap<>();
    entries.put(contentGenerator.newArtifactPath("jar"), contentGenerator.newBinaryContent(2400));
    entries.put(contentGenerator.newArtifactPath("jar"), contentGenerator.newBinaryContent(2400));

    final File tgz = makeTarball(entries);

    System.out.println("tar content array has length: " + tgz.length());

    // We only need one repo server.
    ExpectationServer server = new ExpectationServer();
    server.start();//from  ww  w  .  j a v a  2s.  co  m

    String url = server.formatUrl(path);

    // Register the generated content by writing it to the path within the repo server's dir structure.
    // This way when the path is requested it can be downloaded instead of returning a 404.
    server.expect("GET", url, (req, resp) -> {
        //            Content-Length: 47175
        //            Content-Type: application/x-gzip
        resp.setHeader("Content-Encoding", "x-gzip");
        resp.setHeader("Content-Type", "application/x-gzip");

        byte[] raw = FileUtils.readFileToByteArray(tgz);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GzipCompressorOutputStream gzout = new GzipCompressorOutputStream(baos);
        gzout.write(raw);
        gzout.finish();

        byte[] content = baos.toByteArray();

        resp.setHeader("Content-Length", Long.toString(content.length));
        OutputStream respStream = resp.getOutputStream();
        respStream.write(content);
        respStream.flush();

        System.out.println("Wrote content with length: " + content.length);
    });

    final PoolingHttpClientConnectionManager ccm = new PoolingHttpClientConnectionManager();
    ccm.setMaxTotal(1);

    final HttpClientBuilder builder = HttpClients.custom().setConnectionManager(ccm);
    CloseableHttpClient client = builder.build();

    HttpGet get = new HttpGet(url);
    //        get.setHeader( "Accept-Encoding", "gzip,deflate" );

    Boolean result = client.execute(get, (response) -> {
        Arrays.stream(response.getAllHeaders()).forEach((h) -> System.out.println("Header:: " + h));

        Header contentEncoding = response.getEntity().getContentEncoding();
        if (contentEncoding == null) {
            contentEncoding = response.getFirstHeader("Content-Encoding");
        }

        System.out.printf("Got content encoding: %s\n",
                contentEncoding == null ? "None" : contentEncoding.getValue());

        byte[] content = IOUtils.toByteArray(response.getEntity().getContent());

        try (TarArchiveInputStream tarIn = new TarArchiveInputStream(
                new GzipCompressorInputStream(new ByteArrayInputStream(content)))) {
            TarArchiveEntry entry = null;
            while ((entry = tarIn.getNextTarEntry()) != null) {
                System.out.printf("Got tar entry: %s\n", entry.getName());
                byte[] entryData = new byte[(int) entry.getSize()];
                int read = tarIn.read(entryData, 0, entryData.length);
            }
        }

        return false;
    });
}

From source file:com.hp.mqm.client.AbstractMqmRestClient.java

/**
 * Constructor for AbstractMqmRestClient.
 *
 * @param connectionConfig MQM connection configuration, Fields 'location', 'domain', 'project' and 'clientType' must not be null or empty.
 *///from w ww.  ja va2  s .  c o  m
protected AbstractMqmRestClient(MqmConnectionConfig connectionConfig) {
    checkNotEmpty("Parameter 'location' must not be null or empty.", connectionConfig.getLocation());
    checkNotEmpty("Parameter 'sharedSpace' must not be null or empty.", connectionConfig.getSharedSpace());
    checkNotEmpty("Parameter 'clientType' must not be null or empty.", connectionConfig.getClientType());
    clientType = connectionConfig.getClientType();
    location = connectionConfig.getLocation();
    sharedSpace = connectionConfig.getSharedSpace();
    username = connectionConfig.getUsername();
    password = connectionConfig.getPassword();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(20);
    cm.setDefaultMaxPerRoute(20);
    cookieStore = new BasicCookieStore();

    if (connectionConfig.getProxyHost() != null && !connectionConfig.getProxyHost().isEmpty()) {
        HttpHost proxy = new HttpHost(connectionConfig.getProxyHost(), connectionConfig.getProxyPort());

        RequestConfig requestConfig = RequestConfig.custom().setProxy(proxy)
                .setConnectTimeout(connectionConfig.getDefaultConnectionTimeout() != null
                        ? connectionConfig.getDefaultConnectionTimeout()
                        : DEFAULT_CONNECTION_TIMEOUT)
                .setSocketTimeout(connectionConfig.getDefaultSocketTimeout() != null
                        ? connectionConfig.getDefaultSocketTimeout()
                        : DEFAULT_SO_TIMEOUT)
                .build();

        if (connectionConfig.getProxyCredentials() != null) {
            AuthScope proxyAuthScope = new AuthScope(connectionConfig.getProxyHost(),
                    connectionConfig.getProxyPort());
            Credentials credentials = proxyCredentialsToCredentials(connectionConfig.getProxyCredentials());

            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(proxyAuthScope, credentials);

            httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultCookieStore(cookieStore)
                    .setDefaultCredentialsProvider(credsProvider).setDefaultRequestConfig(requestConfig)
                    .build();
        } else {
            httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultCookieStore(cookieStore)
                    .setDefaultRequestConfig(requestConfig).build();
        }
    } else {
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(connectionConfig.getDefaultConnectionTimeout() != null
                        ? connectionConfig.getDefaultConnectionTimeout()
                        : DEFAULT_CONNECTION_TIMEOUT)
                .setSocketTimeout(connectionConfig.getDefaultSocketTimeout() != null
                        ? connectionConfig.getDefaultSocketTimeout()
                        : DEFAULT_SO_TIMEOUT)
                .build();
        httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultCookieStore(cookieStore)
                .setDefaultRequestConfig(requestConfig).build();
    }
}

From source file:org.geosdi.geoplatform.experimental.openam.support.config.connector.secure.OpenAMAuthorizedConnector.java

protected OpenAMAuthorizedConnector(GPConnectorSettings theOpenAMConnectorSettings) {
    Preconditions.checkNotNull(theOpenAMConnectorSettings, "The OpenAMConnectorSettings must not be null.");
    this.openAMConnectorSettings = theOpenAMConnectorSettings;
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(this.openAMConnectorSettings.getMaxTotalConnections());
    cm.setDefaultMaxPerRoute(this.openAMConnectorSettings.getDefaultMaxPerRoute());
    this.httpClient = HttpClients.custom().setConnectionManager(cm)
            .setRetryHandler(new OpenAMHttpRequestRetryHandler(5)).build();
}

From source file:org.codelibs.solr.lib.server.SolrLibHttpSolrServer.java

public void init() {
    if (clientConnectionManager == null) {
        final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setDefaultMaxPerRoute(defaultMaxConnectionsPerHost);
        connectionManager.setMaxTotal(maxTotalConnections);
        idleConnectionMonitorThread = new IdleConnectionMonitorThread(connectionManager,
                connectionMonitorInterval, connectionIdelTimeout);
        idleConnectionMonitorThread.start();
        clientConnectionManager = connectionManager;
    }/*from w w  w  .j  ava  2  s.  c  om*/

    requestConfigBuilder.setRedirectsEnabled(followRedirects);

    final HttpClientBuilder builder = HttpClients.custom();

    if (allowCompression) {
        builder.addInterceptorLast(new UseCompressionRequestInterceptor());
        builder.addInterceptorLast(new UseCompressionResponseInterceptor());
    }

    for (final HttpRequestInterceptor iterceptor : httpRequestInterceptorList) {
        builder.addInterceptorLast(iterceptor);
    }

    init(builder.setConnectionManager(clientConnectionManager)
            .setDefaultRequestConfig(requestConfigBuilder.build()).build());

}

From source file:org.apache.dubbo.rpc.protocol.rest.RestProtocol.java

@Override
protected <T> T doRefer(Class<T> serviceType, URL url) throws RpcException {
    if (connectionMonitor == null) {
        connectionMonitor = new ConnectionMonitor();
    }//ww w .  jav  a2 s .  c  o m

    // TODO more configs to add
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    // 20 is the default maxTotal of current PoolingClientConnectionManager
    connectionManager.setMaxTotal(url.getParameter(Constants.CONNECTIONS_KEY, 20));
    connectionManager.setDefaultMaxPerRoute(url.getParameter(Constants.CONNECTIONS_KEY, 20));

    connectionMonitor.addConnectionManager(connectionManager);
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT))
            .setSocketTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)).build();

    SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(true).setTcpNoDelay(true).build();

    CloseableHttpClient httpClient = HttpClientBuilder.create()
            .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")) {
                            return Long.parseLong(value) * 1000;
                        }
                    }
                    // TODO constant
                    return 30 * 1000;
                }
            }).setDefaultRequestConfig(requestConfig).setDefaultSocketConfig(socketConfig).build();

    ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient/*, localContext*/);

    ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
    clients.add(client);

    client.register(RpcContextFilter.class);
    for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) {
        if (!StringUtils.isEmpty(clazz)) {
            try {
                client.register(Thread.currentThread().getContextClassLoader().loadClass(clazz.trim()));
            } catch (ClassNotFoundException e) {
                throw new RpcException("Error loading JAX-RS extension class: " + clazz.trim(), e);
            }
        }
    }

    // TODO protocol
    ResteasyWebTarget target = client
            .target("http://" + url.getHost() + ":" + url.getPort() + "/" + getContextPath(url));
    return target.proxy(serviceType);
}

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);//from w ww.  ja v  a2 s  .c  om
    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("/$", "");
    }
}

From source file:org.glassfish.jersey.apache.connector.HelloWorldTest.java

public void _testConnectionPoolSharing(final boolean sharingEnabled) throws Exception {

    final HttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();

    final ClientConfig cc = new ClientConfig();
    cc.property(ApacheClientProperties.CONNECTION_MANAGER, connectionManager);
    cc.property(ApacheClientProperties.CONNECTION_MANAGER_SHARED, sharingEnabled);
    cc.connectorProvider(new ApacheConnectorProvider());

    final Client clientOne = ClientBuilder.newClient(cc);
    WebTarget target = clientOne.target(getBaseUri()).path(ROOT_PATH);
    target.request().get();/*from   w w w  .jav  a  2 s .co  m*/
    clientOne.close();

    final boolean exceptionExpected = !sharingEnabled;

    final Client clientTwo = ClientBuilder.newClient(cc);
    target = clientTwo.target(getBaseUri()).path(ROOT_PATH);
    try {
        target.request().get();
        if (exceptionExpected) {
            Assert.fail("Exception expected");
        }
    } catch (Exception e) {
        if (!exceptionExpected) {
            Assert.fail("Exception not expected");
        }
    } finally {
        clientTwo.close();
    }

    if (sharingEnabled) {
        connectionManager.shutdown();
    }
}