Search in sources :

Example 1 with PoolingHttpClientConnectionManager

use of org.apache.http.impl.conn.PoolingHttpClientConnectionManager in project jersey by jersey.

the class HelloWorldTest method _testConnectionPoolSharing.

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();
    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();
    }
}
Also used : WebTarget(javax.ws.rs.client.WebTarget) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) HttpClientConnectionManager(org.apache.http.conn.HttpClientConnectionManager) ClientConfig(org.glassfish.jersey.client.ClientConfig) Client(javax.ws.rs.client.Client) ConnectionPoolTimeoutException(org.apache.http.conn.ConnectionPoolTimeoutException) IOException(java.io.IOException) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) HttpException(org.apache.http.HttpException) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager)

Example 2 with PoolingHttpClientConnectionManager

use of org.apache.http.impl.conn.PoolingHttpClientConnectionManager in project voltdb by VoltDB.

the class HTTPBenchmark method runBenchmark.

/**
     * Core benchmark code. Connect. Initialize. Run the loop. Cleanup. Print Results.
     *
     * @throws Exception if anything unexpected happens.
     */
public void runBenchmark() throws Exception {
    System.out.print(HORIZONTAL_RULE);
    System.out.println(" Setup & Initialization");
    System.out.println(HORIZONTAL_RULE);
    // connect to one or more servers, loop until success
    connect(config.servers);
    // preload keys if requested
    System.out.println();
    if (config.preload) {
        System.out.println("Preloading data store...");
        for (int i = 0; i < config.poolsize; i++) {
            client.callProcedure(new NullCallback(), "Put", String.format(processor.KeyFormat, i), processor.generateForStore().getStoreValue());
        }
        client.drain();
        System.out.println("Preloading complete.\n");
    }
    System.out.print(HORIZONTAL_RULE);
    System.out.println(" Starting Benchmark");
    System.out.println(HORIZONTAL_RULE);
    // setup the HTTP connection pool that will be used by the threads
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(config.threads * 2);
    cm.setDefaultMaxPerRoute(config.threads);
    CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
    String[] servers = config.servers.split(",");
    // create/start the requested number of threads
    Thread[] kvThreads = new Thread[config.threads];
    for (int i = 0; i < config.threads; ++i) {
        HttpPost httppost = new HttpPost("http://" + servers[i % servers.length] + ":8080/api/1.0/");
        kvThreads[i] = new Thread(new KVThread(httpclient, httppost));
        kvThreads[i].start();
    }
    // Run the benchmark loop for the requested warmup time
    System.out.println("Warming up...");
    Thread.sleep(1000l * config.warmup);
    // signal to threads to end the warmup phase
    warmupComplete.set(true);
    // Run the benchmark loop for the requested warmup time
    System.out.println("\nRunning benchmark...");
    Thread.sleep(1000l * config.duration);
    // stop the threads
    benchmarkComplete.set(true);
    // cancel periodic stats printing
    // timer.cancel();
    // block until all outstanding txns return
    client.drain();
    // join on the threads
    for (Thread t : kvThreads) {
        t.join();
    }
    // print the summary results
    printResults();
    // close down the client connections
    client.close();
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) NullCallback(org.voltdb.client.NullCallback) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager)

Example 3 with PoolingHttpClientConnectionManager

use of org.apache.http.impl.conn.PoolingHttpClientConnectionManager in project voltdb by VoltDB.

the class TestJSONOverHttps method callProcOverJSON.

private String callProcOverJSON(String varString, final int expectedCode) throws Exception {
    URI uri = URI.create("https://localhost:" + m_port + "/api/1.0/");
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

        @Override
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();
    SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sf).build();
    // allows multi-threaded use
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    HttpClientBuilder b = HttpClientBuilder.create();
    b.setSslcontext(sslContext);
    b.setConnectionManager(connMgr);
    try (CloseableHttpClient httpclient = b.build()) {
        HttpPost post = new HttpPost(uri);
        // play nice by using HTTP 1.1 continue requests where the client sends the request headers first
        // to the server to see if the server is willing to accept it. This allows us to test large requests
        // without incurring server socket connection terminations
        RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setExpectContinueEnabled(true).build();
        post.setProtocolVersion(HttpVersion.HTTP_1_1);
        post.setConfig(rc);
        post.setEntity(new StringEntity(varString, utf8ApplicationFormUrlEncoded));
        ResponseHandler<String> rh = new ResponseHandler<String>() {

            @Override
            public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                assertEquals(expectedCode, status);
                if ((status >= 200 && status < 300) || status == 400) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                }
                return null;
            }
        };
        return httpclient.execute(post, rh);
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) ResponseHandler(org.apache.http.client.ResponseHandler) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) SSLContext(javax.net.ssl.SSLContext) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) URI(java.net.URI) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) StringEntity(org.apache.http.entity.StringEntity) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) SSLContextBuilder(org.apache.http.conn.ssl.SSLContextBuilder)

Example 4 with PoolingHttpClientConnectionManager

use of org.apache.http.impl.conn.PoolingHttpClientConnectionManager in project rhino by PLOS.

the class RhinoConfiguration method httpClient.

@Bean
public CloseableHttpClient httpClient(RuntimeConfiguration runtimeConfiguration) {
    PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();
    Integer maxTotal = runtimeConfiguration.getHttpConnectionPoolConfiguration().getMaxTotal();
    manager.setMaxTotal(maxTotal == null ? 400 : maxTotal);
    Integer defaultMaxPerRoute = runtimeConfiguration.getHttpConnectionPoolConfiguration().getDefaultMaxPerRoute();
    manager.setDefaultMaxPerRoute(defaultMaxPerRoute == null ? 20 : defaultMaxPerRoute);
    return HttpClientBuilder.create().setConnectionManager(manager).build();
}
Also used : PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) AnnotationSessionFactoryBean(org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean) Bean(org.springframework.context.annotation.Bean)

Example 5 with PoolingHttpClientConnectionManager

use of org.apache.http.impl.conn.PoolingHttpClientConnectionManager in project calcite-avatica by apache.

the class AvaticaCommonsHttpClientImpl method initializeClient.

private void initializeClient() {
    SSLConnectionSocketFactory sslFactory = null;
    if (null != truststore && null != truststorePassword) {
        try {
            SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(truststore, truststorePassword.toCharArray()).build();
            sslFactory = new SSLConnectionSocketFactory(sslcontext);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    } else {
        LOG.debug("Not configuring HTTPS because of missing truststore/password");
    }
    RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
    registryBuilder.register("http", PlainConnectionSocketFactory.getSocketFactory());
    // Only register the SSL factory when provided
    if (null != sslFactory) {
        registryBuilder.register("https", sslFactory);
    }
    pool = new PoolingHttpClientConnectionManager(registryBuilder.build());
    // Increase max total connection to 100
    final String maxCnxns = System.getProperty(MAX_POOLED_CONNECTIONS_KEY, MAX_POOLED_CONNECTIONS_DEFAULT);
    pool.setMaxTotal(Integer.parseInt(maxCnxns));
    // Increase default max connection per route to 25
    final String maxCnxnsPerRoute = System.getProperty(MAX_POOLED_CONNECTION_PER_ROUTE_KEY, MAX_POOLED_CONNECTION_PER_ROUTE_DEFAULT);
    pool.setDefaultMaxPerRoute(Integer.parseInt(maxCnxnsPerRoute));
    this.authCache = new BasicAuthCache();
    // A single thread-safe HttpClient, pooling connections via the ConnectionManager
    this.client = HttpClients.custom().setConnectionManager(pool).build();
}
Also used : PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) SSLContext(javax.net.ssl.SSLContext) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ClientProtocolException(org.apache.http.client.ClientProtocolException) URISyntaxException(java.net.URISyntaxException) NoHttpResponseException(org.apache.http.NoHttpResponseException) IOException(java.io.IOException) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager)

Aggregations

PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)180 SSLConnectionSocketFactory (org.apache.http.conn.ssl.SSLConnectionSocketFactory)63 ConnectionSocketFactory (org.apache.http.conn.socket.ConnectionSocketFactory)62 PlainConnectionSocketFactory (org.apache.http.conn.socket.PlainConnectionSocketFactory)54 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)52 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)42 SSLContext (javax.net.ssl.SSLContext)36 RequestConfig (org.apache.http.client.config.RequestConfig)31 IOException (java.io.IOException)29 Test (org.junit.Test)27 HttpHost (org.apache.http.HttpHost)21 HttpGet (org.apache.http.client.methods.HttpGet)18 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)17 AuthScope (org.apache.http.auth.AuthScope)16 SSLContextBuilder (org.apache.http.ssl.SSLContextBuilder)16 HttpResponse (org.apache.http.HttpResponse)15 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)14 CredentialsProvider (org.apache.http.client.CredentialsProvider)14 HostnameVerifier (javax.net.ssl.HostnameVerifier)13 HttpClient (org.apache.http.client.HttpClient)12