Java Examples for org.apache.http.pool.PoolStats

The following java examples will help you to understand the usage of org.apache.http.pool.PoolStats. These source code samples are taken from different open source projects.

Example 1
Project: liferay-portal-master  File: HttpImpl.java View source code
public void destroy() {
    int retry = 0;
    while (retry < 10) {
        PoolStats poolStats = _poolingHttpClientConnectionManager.getTotalStats();
        int availableConnections = poolStats.getAvailable();
        if (availableConnections <= 0) {
            break;
        }
        if (_log.isDebugEnabled()) {
            _log.debug(toString() + " is waiting on " + availableConnections + " connections");
        }
        _poolingHttpClientConnectionManager.closeIdleConnections(200, TimeUnit.MILLISECONDS);
        try {
            Thread.sleep(500);
        } catch (InterruptedException ie) {
        }
        retry++;
    }
    _poolingHttpClientConnectionManager.shutdown();
}
Example 2
Project: uw-android-master  File: ClientEvictExpiredConnections.java View source code
public static void main(String[] args) throws Exception {
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(100);
    CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).evictExpiredConnections().evictIdleConnections(5L, TimeUnit.SECONDS).build();
    try {
        // create an array of URIs to perform GETs on
        String[] urisToGet = { "http://hc.apache.org/", "http://hc.apache.org/httpcomponents-core-ga/", "http://hc.apache.org/httpcomponents-client-ga/" };
        for (int i = 0; i < urisToGet.length; i++) {
            String requestURI = urisToGet[i];
            HttpGet request = new HttpGet(requestURI);
            System.out.println("Executing request " + requestURI);
            CloseableHttpResponse response = httpclient.execute(request);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                EntityUtils.consume(response.getEntity());
            } finally {
                response.close();
            }
        }
        PoolStats stats1 = cm.getTotalStats();
        System.out.println("Connections kept alive: " + stats1.getAvailable());
        // Sleep 10 sec and let the connection evictor do its job
        Thread.sleep(10000);
        PoolStats stats2 = cm.getTotalStats();
        System.out.println("Connections kept alive: " + stats2.getAvailable());
    } finally {
        httpclient.close();
    }
}
Example 3
Project: critter-master  File: HttpClient.java View source code
public Response forward(HttpContext ctx, HttpRequestBase forwardRequest, URI forwardURI, byte[] requestEntityContent) {
    // get
    ContainerRequest containerRequest = (ContainerRequest) ctx.getRequest();
    forwardRequest.setURI(forwardURI);
    if (forwardRequest instanceof HttpEntityEnclosingRequestBase) {
        HttpEntityEnclosingRequestBase encloser = (HttpEntityEnclosingRequestBase) forwardRequest;
        encloser.setEntity(new InputStreamEntity(new ByteArrayInputStream(requestEntityContent), requestEntityContent.length));
    }
    // copy headers
    for (Entry<String, List<String>> each : containerRequest.getRequestHeaders().entrySet()) {
        // omit proxy headers
        if ("Proxy-Connection.Host.Content-Length".indexOf(each.getKey()) == -1) {
            for (String other : each.getValue()) {
                LOG.trace("Forward copy header:{}", each);
                forwardRequest.addHeader(each.getKey(), other);
            }
        } else {
            LOG.trace("Skip forward header:{}", each);
        }
    }
    HttpResponse forwardResponse = null;
    try {
        forwardResponse = httpClient.execute(forwardRequest);
    } catch (UnknownHostException uhe) {
        return Response.status(404).entity("Unknown host: " + uhe.getMessage()).build();
    } catch (Exception ex) {
        LOG.error(forwardRequest.getRequestLine().toString());
        LOG.trace(forwardRequest.getRequestLine().toString(), ex);
        return Response.serverError().entity(ex.getMessage()).build();
    }
    Response.ResponseBuilder containerResponse = Response.status(forwardResponse.getStatusLine().getStatusCode());
    // copy headers
    for (Header each : forwardResponse.getAllHeaders()) {
        if ("Transfer-Encoding".indexOf(each.getName()) == -1) {
            LOG.trace("Backward copy header:" + each.toString());
            containerResponse.header(each.getName(), each.getValue());
        } else {
            LOG.trace("Skip backward header:" + each.toString());
        }
    }
    try {
        if (forwardResponse.getEntity() != null) {
            containerResponse.entity(forwardResponse.getEntity().getContent());
        }
        return containerResponse.build();
    } catch (Exception ex) {
        try {
            EntityUtils.consume(forwardResponse.getEntity());
        } catch (IOException ioex) {
            LOG.error("Consuming content from response failed", ioex);
        }
        LOG.error("Reading response failed", ex);
        return Response.serverError().entity(ex.getMessage()).build();
    } finally {
        PoolStats totalStats = connectionManager.getTotalStats();
        LOG.trace("Connections in pool:{}", totalStats);
        MonitorFactory.add("--critter.http.pool.size", "count", (totalStats.getAvailable() + totalStats.getLeased()) * 1.0d);
    }
}
Example 4
Project: lightmtp-master  File: MailIOSessionManager.java View source code
private String formatStats(final SessionEndpoint endpoint) {
    final StringBuilder buf = new StringBuilder();
    final PoolStats totals = this.pool.getTotalStats();
    final PoolStats stats = this.pool.getStats(endpoint);
    buf.append("[total kept alive: ").append(totals.getAvailable()).append("; ");
    buf.append("address allocated: ").append(stats.getLeased() + stats.getAvailable());
    buf.append(" of ").append(stats.getMax()).append("; ");
    buf.append("total allocated: ").append(totals.getLeased() + totals.getAvailable());
    buf.append(" of ").append(totals.getMax()).append("]");
    return buf.toString();
}
Example 5
Project: strongbox-master  File: HttpConnectionPoolConfigurationManagementController.java View source code
@ApiOperation(value = "Get proxy repository pool stats")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Proxy repository pool stats where retrieved."), @ApiResponse(code = 500, message = "An error occurred.") })
@RequestMapping(value = "{storageId}/{repositoryId}", method = RequestMethod.GET, produces = MediaType.TEXT_PLAIN_VALUE)
public ResponseEntity getPoolStatsForProxyRepository(@PathVariable(value = "storageId") String storageId, @PathVariable(value = "repositoryId") String repositoryId) {
    Storage storage = getConfiguration().getStorage(storageId);
    if (storage == null) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body("The storage does not exist!");
    }
    Repository repository = storage.getRepository(repositoryId);
    if (repository == null) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body("The repository does not exist!");
    }
    if (storage.getRepository(repositoryId).getRemoteRepository() == null) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Repository doesn't have remote repository!");
    }
    PoolStats poolStats = proxyRepositoryConnectionPoolConfigurationService.getPoolStats(repository.getRemoteRepository().getUrl());
    return ResponseEntity.ok(poolStats.toString());
}
Example 6
Project: hera-master  File: HttpClientPoolCollector.java View source code
@Override
public void doCollect() {
    for (Map.Entry<String, ConnPoolControl<HttpRoute>> each : pool.entrySet()) {
        Map<String, String> tags = new LinkedHashMap<String, String>();
        Map<String, Object> props = new LinkedHashMap<String, Object>();
        tags.put("name", each.getKey());
        ConnPoolControl<HttpRoute> connPoolControl = each.getValue();
        PoolStats stats = connPoolControl.getTotalStats();
        props.put("available", stats.getAvailable());
        props.put("leased", stats.getLeased());
        props.put("max", stats.getMax());
        props.put("pending", stats.getPending());
        handler.handle(MetricQuota.HTTPCLIENT, tags, props);
        //资源已满打印堆栈
        if (stats.getMax() == stats.getLeased()) {
            Collection<StackTraceElement[]> stackTraces = ((HttpClientStackTraceRepository) connPoolControl).getBlockingStackTrace();
            blockingStackTraceCollector.collect(MetricQuota.HTTPCLIENT, each.getKey(), stackTraces);
        }
    }
}
Example 7
Project: lucene-solr-master  File: HttpSolrClientConPoolTest.java View source code
public void testPoolSize() throws SolrServerException, IOException {
    PoolingHttpClientConnectionManager pool = HttpClientUtil.createPoolingConnectionManager();
    final HttpSolrClient client1;
    final String fooUrl;
    {
        fooUrl = jetty.getBaseUrl().toString() + "/" + "collection1";
        CloseableHttpClient httpClient = HttpClientUtil.createClient(new ModifiableSolrParams(), pool, false);
        client1 = getHttpSolrClient(fooUrl, httpClient);
        client1.setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT);
    }
    final String barUrl = yetty.getBaseUrl().toString() + "/" + "collection1";
    {
        client1.setBaseURL(fooUrl);
        client1.deleteByQuery("*:*");
        client1.setBaseURL(barUrl);
        client1.deleteByQuery("*:*");
    }
    List<String> urls = new ArrayList<>();
    for (int i = 0; i < 17; i++) {
        urls.add(fooUrl);
    }
    for (int i = 0; i < 31; i++) {
        urls.add(barUrl);
    }
    Collections.shuffle(urls, random());
    try {
        int i = 0;
        for (String url : urls) {
            if (!client1.getBaseURL().equals(url)) {
                client1.setBaseURL(url);
            }
            client1.add(new SolrInputDocument("id", "" + (i++)));
        }
        client1.setBaseURL(fooUrl);
        client1.commit();
        assertEquals(17, client1.query(new SolrQuery("*:*")).getResults().getNumFound());
        client1.setBaseURL(barUrl);
        client1.commit();
        assertEquals(31, client1.query(new SolrQuery("*:*")).getResults().getNumFound());
        PoolStats stats = pool.getTotalStats();
        assertEquals("oh " + stats, 2, stats.getAvailable());
    } finally {
        for (HttpSolrClient c : new HttpSolrClient[] { client1 }) {
            HttpClientUtil.close(c.getHttpClient());
            c.close();
        }
    }
}
Example 8
Project: Jest-master  File: JestClientFactoryIntegrationTest.java View source code
/**
     * Forgive me these sins.  This is the only way I can think of to determine the *actual* size of the connection pool
     * without wrapping large quantities of the underlying client.
     * <p>
     * This whole method is cheating and full of bad examples.  Don't copy this.  You've been warned.
     */
private int getPoolSize(JestHttpClient client) throws Exception {
    try {
        Field fieldHttpClient = client.getClass().getDeclaredField("httpClient");
        fieldHttpClient.setAccessible(true);
        Object objInternalHttpClient = fieldHttpClient.get(client);
        Field fieldConnectionManager = objInternalHttpClient.getClass().getDeclaredField("connManager");
        fieldConnectionManager.setAccessible(true);
        PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = (PoolingHttpClientConnectionManager) fieldConnectionManager.get(objInternalHttpClient);
        PoolStats poolStats = poolingHttpClientConnectionManager.getTotalStats();
        return poolStats.getAvailable() + poolStats.getLeased();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return -1;
}
Example 9
Project: Sql4D-master  File: DruidNodeAccessor.java View source code
public static Map<String, Integer> getConnectionPoolStats() {
    Map<String, Integer> stats = new HashMap<>();
    PoolStats poolStats = pool.getTotalStats();
    stats.put("availableConnections", poolStats.getAvailable());
    stats.put("maxConnections", poolStats.getMax());
    stats.put("leasedConnections", poolStats.getLeased());
    stats.put("pendingConnections", poolStats.getPending());
    stats.put("defaultMaxPerRoute", pool.getDefaultMaxPerRoute());
    return stats;
}
Example 10
Project: jmeter-master  File: JMeterPoolingClientConnectionManager.java View source code
private String formatStats(final HttpRoute route) {
    final StringBuilder buf = new StringBuilder();
    final PoolStats totals = this.pool.getTotalStats();
    final PoolStats stats = this.pool.getStats(route);
    buf.append("[total kept alive: ").append(totals.getAvailable()).append("; ");
    buf.append("route allocated: ").append(stats.getLeased() + stats.getAvailable());
    buf.append(" of ").append(stats.getMax()).append("; ");
    buf.append("total allocated: ").append(totals.getLeased() + totals.getAvailable());
    buf.append(" of ").append(totals.getMax()).append("]");
    return buf.toString();
}
Example 11
Project: httpasyncclient-master  File: PoolingClientConnectionManager.java View source code
private String formatStats(final HttpRoute route) {
    StringBuilder buf = new StringBuilder();
    PoolStats totals = this.pool.getTotalStats();
    PoolStats stats = this.pool.getStats(route);
    buf.append("[total kept alive: ").append(totals.getAvailable()).append("; ");
    buf.append("route allocated: ").append(stats.getLeased() + stats.getAvailable());
    buf.append(" of ").append(stats.getMax()).append("; ");
    buf.append("total allocated: ").append(totals.getLeased() + totals.getAvailable());
    buf.append(" of ").append(totals.getMax()).append("]");
    return buf.toString();
}
Example 12
Project: bugvm-master  File: PoolingHttpClientConnectionManager.java View source code
private String formatStats(final HttpRoute route) {
    final StringBuilder buf = new StringBuilder();
    final PoolStats totals = this.pool.getTotalStats();
    final PoolStats stats = this.pool.getStats(route);
    buf.append("[total kept alive: ").append(totals.getAvailable()).append("; ");
    buf.append("route allocated: ").append(stats.getLeased() + stats.getAvailable());
    buf.append(" of ").append(stats.getMax()).append("; ");
    buf.append("total allocated: ").append(totals.getLeased() + totals.getAvailable());
    buf.append(" of ").append(totals.getMax()).append("]");
    return buf.toString();
}
Example 13
Project: Ginkou-master  File: NHttpReverseProxy.java View source code
@Override
public void release(final BasicNIOPoolEntry entry, boolean reusable) {
    System.out.println("[proxy->origin] connection released " + entry.getConnection());
    super.release(entry, reusable);
    StringBuilder buf = new StringBuilder();
    PoolStats totals = getTotalStats();
    buf.append("[total kept alive: ").append(totals.getAvailable()).append("; ");
    buf.append("total allocated: ").append(totals.getLeased() + totals.getAvailable());
    buf.append(" of ").append(totals.getMax()).append("]");
    System.out.println("[proxy->origin] " + buf.toString());
}
Example 14
Project: aether-core-master  File: HttpTransporterTest.java View source code
@Test
public void testConnectionReuse() throws Exception {
    httpServer.addSslConnector();
    session.setCache(new DefaultRepositoryCache());
    for (int i = 0; i < 3; i++) {
        newTransporter(httpServer.getHttpsUrl());
        GetTask task = new GetTask(URI.create("repo/file.txt"));
        transporter.get(task);
        assertEquals("test", task.getDataString());
    }
    PoolStats stats = ((ConnPoolControl<?>) ((HttpTransporter) transporter).getState().getConnectionManager()).getTotalStats();
    assertEquals(stats.toString(), 1, stats.getAvailable());
}
Example 15
Project: aws-sdk-java-master  File: AmazonHttpClient.java View source code
/**
         * Captures the connection pool metrics.
         */
private void captureConnectionPoolMetrics() {
    if (awsRequestMetrics.isEnabled() && httpClient.getHttpClientConnectionManager() instanceof ConnPoolControl<?>) {
        final PoolStats stats = ((ConnPoolControl<?>) httpClient.getHttpClientConnectionManager()).getTotalStats();
        awsRequestMetrics.withCounter(HttpClientPoolAvailableCount, stats.getAvailable()).withCounter(HttpClientPoolLeasedCount, stats.getLeased()).withCounter(HttpClientPoolPendingCount, stats.getPending());
    }
}
Example 16
Project: aws-java-sdk-master  File: AmazonHttpClient.java View source code
/**
         * Captures the connection pool metrics.
         */
private void captureConnectionPoolMetrics() {
    if (awsRequestMetrics.isEnabled() && httpClient.getHttpClientConnectionManager() instanceof ConnPoolControl<?>) {
        final PoolStats stats = ((ConnPoolControl<?>) httpClient.getHttpClientConnectionManager()).getTotalStats();
        awsRequestMetrics.withCounter(HttpClientPoolAvailableCount, stats.getAvailable()).withCounter(HttpClientPoolLeasedCount, stats.getLeased()).withCounter(HttpClientPoolPendingCount, stats.getPending());
    }
}
Example 17
Project: stability-utils-master  File: PooledHttpClientStrategy.java View source code
public PoolStats getPoolStats() {
    return getConnectionManager().getTotalStats();
}
Example 18
Project: docker-client-master  File: DefaultDockerClientTest.java View source code
private PoolStats getClientConnectionPoolStats(final DefaultDockerClient client) {
    return ((PoolingHttpClientConnectionManager) client.getClient().getConfiguration().getProperty(ApacheClientProperties.CONNECTION_MANAGER)).getTotalStats();
}