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

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

Introduction

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

Prototype

public void setDefaultSocketConfig(final SocketConfig defaultSocketConfig) 

Source Link

Usage

From source file:org.dcache.srm.client.HttpClientSender.java

/**
 * Creates the connection manager to be used to manage connections to SOAP servers.
 *//*w  ww . jav  a2 s. c o m*/
protected PoolingHttpClientConnectionManager createConnectionManager() {
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(
            createSocketFactoryRegistry());
    cm.setMaxTotal(clientProperties.getMaximumTotalConnections());
    cm.setDefaultMaxPerRoute(clientProperties.getMaximumConnectionsPerHost());
    SocketConfig.Builder socketOptions = SocketConfig.custom();
    if (clientProperties.getDefaultSoTimeout() > 0) {
        socketOptions.setSoTimeout(clientProperties.getDefaultSoTimeout());
    }
    cm.setDefaultSocketConfig(socketOptions.build());
    return cm;
}

From source file:com.tremolosecurity.proxy.filter.PostProcess.java

public CloseableHttpClient getHttp(String finalURL, HttpServletRequest request, ConfigManager cfgMgr) {
    HttpSession session = request.getSession();
    PoolingHttpClientConnectionManager phcm = (PoolingHttpClientConnectionManager) session
            .getAttribute("TREMOLO_HTTP_POOL");
    CloseableHttpClient http = (CloseableHttpClient) session.getAttribute("TREMOLO_HTTP_CLIENT");
    if (http == null) {
        //create a new connection manager and client
        phcm = new PoolingHttpClientConnectionManager(cfgMgr.getHttpClientSocketRegistry());
        BigInteger num = cfgMgr.getCfg().getThreadsPerRoute();
        if (num == null) {
            phcm.setDefaultMaxPerRoute(6);
        } else {/*  w w w. ja  v  a2 s . c  om*/
            phcm.setDefaultMaxPerRoute(num.intValue());
        }
        phcm.setDefaultSocketConfig(SocketConfig.custom().setSoKeepAlive(true).build());
        http = HttpClients.custom().setConnectionManager(phcm)
                .setDefaultRequestConfig(cfgMgr.getGlobalHttpClientConfig()).build();

        session.setAttribute("TREMOLO_HTTP_POOL", phcm);
        session.setAttribute("TREMOLO_HTTP_CLIENT", http);

        LogoutUtil.insertFirstLogoutHandler(request, new CloseHttpConnectionsOnLogout(http, phcm));

    }

    return http;
}

From source file:org.apache.hadoop.gateway.shell.Hadoop.java

private CloseableHttpClient createClient(ClientContext clientContext) throws GeneralSecurityException {

    // SSL/*from   ww  w  .j  a va2 s.  c  om*/
    HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
    TrustStrategy trustStrategy = null;
    if (clientContext.connection().secure()) {
        hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();
    } else {
        trustStrategy = TrustSelfSignedStrategy.INSTANCE;
        System.out.println("**************** WARNING ******************\n"
                + "This is an insecure client instance and may\n"
                + "leave the interactions subject to a man in\n" + "the middle attack. Please use the login()\n"
                + "method instead of loginInsecure() for any\n" + "sensitive or production usecases.\n"
                + "*******************************************");
    }

    KeyStore trustStore = getTrustStore();
    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore, trustStrategy).build();
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", new SSLConnectionSocketFactory(sslContext, hostnameVerifier)).build();

    // Pool
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
    connectionManager.setMaxTotal(clientContext.pool().maxTotal());
    connectionManager.setDefaultMaxPerRoute(clientContext.pool().defaultMaxPerRoute());

    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setBufferSize(clientContext.connection().bufferSize()).build();
    connectionManager.setDefaultConnectionConfig(connectionConfig);

    SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(clientContext.socket().keepalive())
            .setSoLinger(clientContext.socket().linger())
            .setSoReuseAddress(clientContext.socket().reuseAddress())
            .setSoTimeout(clientContext.socket().timeout()).setTcpNoDelay(clientContext.socket().tcpNoDelay())
            .build();
    connectionManager.setDefaultSocketConfig(socketConfig);

    // Auth
    URI uri = URI.create(clientContext.url());
    host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());

    CredentialsProvider credentialsProvider = null;
    if (clientContext.username() != null && clientContext.password() != null) {
        credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(host.getHostName(), host.getPort()),
                new UsernamePasswordCredentials(clientContext.username(), clientContext.password()));

        AuthCache authCache = new BasicAuthCache();
        BasicScheme authScheme = new BasicScheme();
        authCache.put(host, authScheme);
        context = new BasicHttpContext();
        context.setAttribute(org.apache.http.client.protocol.HttpClientContext.AUTH_CACHE, authCache);
    }
    return HttpClients.custom().setConnectionManager(connectionManager)
            .setDefaultCredentialsProvider(credentialsProvider).build();

}

From source file:com.gargoylesoftware.htmlunit.HttpWebConnection.java

/**
 * Has the exact logic in HttpClientBuilder, but with the ability to configure
 * <code>socketFactory</code>.
 *//*from  ww w .  java2 s .  c  o  m*/
private PoolingHttpClientConnectionManager createConnectionManager(final HttpClientBuilder builder) {
    final ConnectionSocketFactory socketFactory = new SocksConnectionSocketFactory();

    LayeredConnectionSocketFactory sslSocketFactory;
    try {
        sslSocketFactory = (LayeredConnectionSocketFactory) FieldUtils.readDeclaredField(builder,
                "sslSocketFactory", true);
        final SocketConfig defaultSocketConfig = (SocketConfig) FieldUtils.readDeclaredField(builder,
                "defaultSocketConfig", true);
        final ConnectionConfig defaultConnectionConfig = (ConnectionConfig) FieldUtils
                .readDeclaredField(builder, "defaultConnectionConfig", true);
        final boolean systemProperties = (Boolean) FieldUtils.readDeclaredField(builder, "systemProperties",
                true);
        final int maxConnTotal = (Integer) FieldUtils.readDeclaredField(builder, "maxConnTotal", true);
        final int maxConnPerRoute = (Integer) FieldUtils.readDeclaredField(builder, "maxConnPerRoute", true);
        HostnameVerifier hostnameVerifier = (HostnameVerifier) FieldUtils.readDeclaredField(builder,
                "hostnameVerifier", true);
        final SSLContext sslcontext = (SSLContext) FieldUtils.readDeclaredField(builder, "sslContext", true);

        if (sslSocketFactory == null) {
            final String[] supportedProtocols = systemProperties
                    ? StringUtils.split(System.getProperty("https.protocols"), ',')
                    : null;
            final String[] supportedCipherSuites = systemProperties
                    ? StringUtils.split(System.getProperty("https.cipherSuites"), ',')
                    : null;
            if (hostnameVerifier == null) {
                hostnameVerifier = SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
            }
            if (sslcontext != null) {
                sslSocketFactory = new SSLConnectionSocketFactory(sslcontext, supportedProtocols,
                        supportedCipherSuites, hostnameVerifier);
            } else {
                if (systemProperties) {
                    sslSocketFactory = new SSLConnectionSocketFactory(
                            (SSLSocketFactory) SSLSocketFactory.getDefault(), supportedProtocols,
                            supportedCipherSuites, hostnameVerifier);
                } else {
                    sslSocketFactory = new SSLConnectionSocketFactory(SSLContexts.createDefault(),
                            hostnameVerifier);
                }
            }
        }

        final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
                RegistryBuilder.<ConnectionSocketFactory>create().register("http", socketFactory)
                        .register("https", sslSocketFactory).build());
        if (defaultSocketConfig != null) {
            connectionManager.setDefaultSocketConfig(defaultSocketConfig);
        }
        if (defaultConnectionConfig != null) {
            connectionManager.setDefaultConnectionConfig(defaultConnectionConfig);
        }
        if (systemProperties) {
            String s = System.getProperty("http.keepAlive", "true");
            if ("true".equalsIgnoreCase(s)) {
                s = System.getProperty("http.maxConnections", "5");
                final int max = Integer.parseInt(s);
                connectionManager.setDefaultMaxPerRoute(max);
                connectionManager.setMaxTotal(2 * max);
            }
        }
        if (maxConnTotal > 0) {
            connectionManager.setMaxTotal(maxConnTotal);
        }
        if (maxConnPerRoute > 0) {
            connectionManager.setDefaultMaxPerRoute(maxConnPerRoute);
        }
        return connectionManager;
    } catch (final IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

From source file:net.yacy.cora.protocol.http.HTTPClient.java

private static PoolingHttpClientConnectionManager initPoolingConnectionManager() {
    final PlainConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
    final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", plainsf).register("https", getSSLSocketFactory()).build();
    final PoolingHttpClientConnectionManager pooling = new PoolingHttpClientConnectionManager(registry, null,
            null, new DnsResolver() {
                @Override//  www .  j  a  v a 2  s  . c o  m
                public InetAddress[] resolve(final String host0) throws UnknownHostException {
                    final InetAddress ip = Domains.dnsResolve(host0);
                    if (ip == null)
                        throw new UnknownHostException(host0);
                    return new InetAddress[] { ip };
                }
            }, DEFAULT_POOLED_CONNECTION_TIME_TO_LIVE, TimeUnit.SECONDS);
    initPoolMaxConnections(pooling, maxcon);

    pooling.setValidateAfterInactivity(default_timeout); // on init set to default 5000ms
    final SocketConfig socketConfig = SocketConfig.custom()
            // Defines whether the socket can be bound even though a previous connection is still in a timeout state.
            .setSoReuseAddress(true)
            // SO_TIMEOUT: maximum period inactivity between two consecutive data packets in milliseconds
            .setSoTimeout(3000)
            // conserve bandwidth by minimizing the number of segments that are sent
            .setTcpNoDelay(false).build();
    pooling.setDefaultSocketConfig(socketConfig);

    return pooling;
}

From source file:com.unboundid.scim.tools.SCIMQueryRate.java

/**
 * Performs the actual processing for this tool.  In this case, it gets a
 * connection to the directory server and uses it to perform the requested
 * searches.//  www.jav  a 2s . c  o  m
 *
 * @return  The result code for the processing that was performed.
 */
@Override()
public ResultCode doToolProcessing() {
    //Initalize the Debugger
    Debug.setEnabled(true);
    Debug.getLogger().addHandler(new ConsoleHandler());
    Debug.getLogger().setUseParentHandlers(false);

    // Determine the random seed to use.
    final Long seed;
    if (randomSeed.isPresent()) {
        seed = Long.valueOf(randomSeed.getValue());
    } else {
        seed = null;
    }

    // Create a value pattern for the filter.
    final ValuePattern filterPattern;
    boolean isQuery = true;
    if (filter.isPresent()) {
        try {
            filterPattern = new ValuePattern(filter.getValue(), seed);
        } catch (ParseException pe) {
            Debug.debugException(pe);
            err(ERR_QUERY_TOOL_BAD_FILTER_PATTERN.get(pe.getMessage()));
            return ResultCode.PARAM_ERROR;
        }
    } else if (resourceId.isPresent()) {
        isQuery = false;
        try {
            filterPattern = new ValuePattern(resourceId.getValue());
        } catch (ParseException pe) {
            Debug.debugException(pe);
            err(ERR_QUERY_TOOL_BAD_RESOURCE_ID_PATTERN.get(pe.getMessage()));
            return ResultCode.PARAM_ERROR;
        }
    } else {
        filterPattern = null;
    }

    // Get the attributes to return.
    final String[] attrs;
    if (attributes.isPresent()) {
        final List<String> attrList = attributes.getValues();
        attrs = new String[attrList.size()];
        attrList.toArray(attrs);
    } else {
        attrs = NO_STRINGS;
    }

    // If the --ratePerSecond option was specified, then limit the rate
    // accordingly.
    FixedRateBarrier fixedRateBarrier = null;
    if (ratePerSecond.isPresent()) {
        final int intervalSeconds = collectionInterval.getValue();
        final int ratePerInterval = ratePerSecond.getValue() * intervalSeconds;

        fixedRateBarrier = new FixedRateBarrier(1000L * intervalSeconds, ratePerInterval);
    }

    // Determine whether to include timestamps in the output and if so what
    // format should be used for them.
    final boolean includeTimestamp;
    final String timeFormat;
    if (timestampFormat.getValue().equalsIgnoreCase("with-date")) {
        includeTimestamp = true;
        timeFormat = "dd/MM/yyyy HH:mm:ss";
    } else if (timestampFormat.getValue().equalsIgnoreCase("without-date")) {
        includeTimestamp = true;
        timeFormat = "HH:mm:ss";
    } else {
        includeTimestamp = false;
        timeFormat = null;
    }

    // Determine whether any warm-up intervals should be run.
    final long totalIntervals;
    final boolean warmUp;
    int remainingWarmUpIntervals = warmUpIntervals.getValue();
    if (remainingWarmUpIntervals > 0) {
        warmUp = true;
        totalIntervals = 0L + numIntervals.getValue() + remainingWarmUpIntervals;
    } else {
        warmUp = true;
        totalIntervals = 0L + numIntervals.getValue();
    }

    // Create the table that will be used to format the output.
    final OutputFormat outputFormat;
    if (csvFormat.isPresent()) {
        outputFormat = OutputFormat.CSV;
    } else {
        outputFormat = OutputFormat.COLUMNS;
    }

    final ColumnFormatter formatter = new ColumnFormatter(includeTimestamp, timeFormat, outputFormat, " ",
            new FormattableColumn(15, HorizontalAlignment.RIGHT, "Recent", "Queries/Sec"),
            new FormattableColumn(15, HorizontalAlignment.RIGHT, "Recent", "Avg Dur ms"),
            new FormattableColumn(15, HorizontalAlignment.RIGHT, "Recent", "Resources/Query"),
            new FormattableColumn(15, HorizontalAlignment.RIGHT, "Recent", "Errors/Sec"),
            new FormattableColumn(15, HorizontalAlignment.RIGHT, "Overall", "Queries/Sec"),
            new FormattableColumn(15, HorizontalAlignment.RIGHT, "Overall", "Avg Dur ms"));

    // Create values to use for statistics collection.
    final AtomicLong queryCounter = new AtomicLong(0L);
    final AtomicLong resourceCounter = new AtomicLong(0L);
    final AtomicLong errorCounter = new AtomicLong(0L);
    final AtomicLong queryDurations = new AtomicLong(0L);

    // Determine the length of each interval in milliseconds.
    final long intervalMillis = 1000L * collectionInterval.getValue();

    // We will use Apache's HttpClient library for this tool.
    SSLUtil sslUtil;
    try {
        sslUtil = createSSLUtil();
    } catch (LDAPException e) {
        debugException(e);
        err(e.getMessage());
        return e.getResultCode();
    }

    RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
    final String schemeName;
    if (sslUtil != null) {
        try {
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                    sslUtil.createSSLContext("TLS"), new NoopHostnameVerifier());
            schemeName = "https";
            registryBuilder.register(schemeName, sslConnectionSocketFactory);
        } catch (GeneralSecurityException e) {
            debugException(e);
            err(ERR_SCIM_TOOL_CANNOT_CREATE_SSL_CONTEXT.get(getExceptionMessage(e)));
            return ResultCode.LOCAL_ERROR;
        }
    } else {
        schemeName = "http";
        registryBuilder.register(schemeName, new PlainConnectionSocketFactory());
    }
    final Registry<ConnectionSocketFactory> socketFactoryRegistry = registryBuilder.build();

    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(30000)
            .setExpectContinueEnabled(true).build();

    SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(30000).setSoReuseAddress(true).build();

    final PoolingHttpClientConnectionManager mgr = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry);
    mgr.setMaxTotal(numThreads.getValue());
    mgr.setDefaultMaxPerRoute(numThreads.getValue());
    mgr.setDefaultSocketConfig(socketConfig);
    mgr.setValidateAfterInactivity(-1);

    ClientConfig jerseyConfig = new ClientConfig();

    jerseyConfig.property(ApacheClientProperties.CONNECTION_MANAGER, mgr);
    jerseyConfig.property(ApacheClientProperties.REQUEST_CONFIG, requestConfig);
    ApacheConnectorProvider connectorProvider = new ApacheConnectorProvider();
    jerseyConfig.connectorProvider(connectorProvider);

    if (authID.isPresent()) {
        try {
            final String password;
            if (authPassword.isPresent()) {
                password = authPassword.getValue();
            } else if (authPasswordFile.isPresent()) {
                password = authPasswordFile.getNonBlankFileLines().get(0);
            } else {
                password = null;
            }

            BasicCredentialsProvider provider = new BasicCredentialsProvider();
            provider.setCredentials(new AuthScope(host.getValue(), port.getValue()),
                    new UsernamePasswordCredentials(authID.getValue(), password));

            jerseyConfig.property(ApacheClientProperties.CREDENTIALS_PROVIDER, provider);
            jerseyConfig.property(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION, true);
        } catch (IOException e) {
            Debug.debugException(e);
            err(ERR_QUERY_TOOL_SET_BASIC_AUTH.get(e.getMessage()));
            return ResultCode.LOCAL_ERROR;
        }
    } else if (bearerToken.isPresent()) {
        jerseyConfig.register(new ClientRequestFilter() {
            public void filter(final ClientRequestContext clientRequestContext) throws IOException {
                try {
                    clientRequestContext.getHeaders().add("Authorization", "Bearer " + bearerToken.getValue());
                } catch (Exception ex) {
                    throw new RuntimeException("Unable to add authorization handler", ex);
                }
            }
        });
    }

    // Create the SCIM client to use for the queries.
    final URI uri;
    try {
        final String path;
        if (contextPath.getValue().startsWith("/")) {
            path = contextPath.getValue();
        } else {
            path = "/" + contextPath.getValue();
        }
        uri = new URI(schemeName, null, host.getValue(), port.getValue(), path, null, null);
    } catch (URISyntaxException e) {
        Debug.debugException(e);
        err(ERR_QUERY_TOOL_CANNOT_CREATE_URL.get(e.getMessage()));
        return ResultCode.OTHER;
    }
    final SCIMService service = new SCIMService(uri, jerseyConfig);

    if (xmlFormat.isPresent()) {
        service.setContentType(MediaType.APPLICATION_XML_TYPE);
        service.setAcceptType(MediaType.APPLICATION_XML_TYPE);
    }

    // Retrieve the resource schema.
    final ResourceDescriptor resourceDescriptor;
    try {
        resourceDescriptor = service.getResourceDescriptor(resourceName.getValue(), null);
        if (resourceDescriptor == null) {
            throw new ResourceNotFoundException(
                    "Resource " + resourceName.getValue() + " is not defined by the service provider");
        }
    } catch (SCIMException e) {
        Debug.debugException(e);
        err(ERR_QUERY_TOOL_RETRIEVE_RESOURCE_SCHEMA.get(e.getMessage()));
        return ResultCode.OTHER;
    }

    final SCIMEndpoint<? extends BaseResource> endpoint = service.getEndpoint(resourceDescriptor,
            BaseResource.BASE_RESOURCE_FACTORY);

    // Create the threads to use for the searches.
    final CyclicBarrier barrier = new CyclicBarrier(numThreads.getValue() + 1);
    final QueryRateThread[] threads = new QueryRateThread[numThreads.getValue()];
    for (int i = 0; i < threads.length; i++) {
        threads[i] = new QueryRateThread(i, isQuery, endpoint, filterPattern, attrs, barrier, queryCounter,
                resourceCounter, queryDurations, errorCounter, fixedRateBarrier);
        threads[i].start();
    }

    // Display the table header.
    for (final String headerLine : formatter.getHeaderLines(true)) {
        out(headerLine);
    }

    // Indicate that the threads can start running.
    try {
        barrier.await();
    } catch (Exception e) {
        Debug.debugException(e);
    }
    long overallStartTime = System.nanoTime();
    long nextIntervalStartTime = System.currentTimeMillis() + intervalMillis;

    boolean setOverallStartTime = false;
    long lastDuration = 0L;
    long lastNumEntries = 0L;
    long lastNumErrors = 0L;
    long lastNumSearches = 0L;
    long lastEndTime = System.nanoTime();
    for (long i = 0; i < totalIntervals; i++) {
        final long startTimeMillis = System.currentTimeMillis();
        final long sleepTimeMillis = nextIntervalStartTime - startTimeMillis;
        nextIntervalStartTime += intervalMillis;
        try {
            if (sleepTimeMillis > 0) {
                Thread.sleep(sleepTimeMillis);
            }
        } catch (Exception e) {
            Debug.debugException(e);
        }

        final long endTime = System.nanoTime();
        final long intervalDuration = endTime - lastEndTime;

        final long numSearches;
        final long numEntries;
        final long numErrors;
        final long totalDuration;
        if (warmUp && (remainingWarmUpIntervals > 0)) {
            numSearches = queryCounter.getAndSet(0L);
            numEntries = resourceCounter.getAndSet(0L);
            numErrors = errorCounter.getAndSet(0L);
            totalDuration = queryDurations.getAndSet(0L);
        } else {
            numSearches = queryCounter.get();
            numEntries = resourceCounter.get();
            numErrors = errorCounter.get();
            totalDuration = queryDurations.get();
        }

        final long recentNumSearches = numSearches - lastNumSearches;
        final long recentNumEntries = numEntries - lastNumEntries;
        final long recentNumErrors = numErrors - lastNumErrors;
        final long recentDuration = totalDuration - lastDuration;

        final double numSeconds = intervalDuration / 1000000000.0d;
        final double recentSearchRate = recentNumSearches / numSeconds;
        final double recentErrorRate = recentNumErrors / numSeconds;

        final double recentAvgDuration;
        final double recentEntriesPerSearch;
        if (recentNumSearches > 0L) {
            recentEntriesPerSearch = 1.0d * recentNumEntries / recentNumSearches;
            recentAvgDuration = 1.0d * recentDuration / recentNumSearches / 1000000;
        } else {
            recentEntriesPerSearch = 0.0d;
            recentAvgDuration = 0.0d;
        }

        if (warmUp && (remainingWarmUpIntervals > 0)) {
            out(formatter.formatRow(recentSearchRate, recentAvgDuration, recentEntriesPerSearch,
                    recentErrorRate, "warming up", "warming up"));

            remainingWarmUpIntervals--;
            if (remainingWarmUpIntervals == 0) {
                out(INFO_QUERY_TOOL_WARM_UP_COMPLETED.get());
                setOverallStartTime = true;
            }
        } else {
            if (setOverallStartTime) {
                overallStartTime = lastEndTime;
                setOverallStartTime = false;
            }

            final double numOverallSeconds = (endTime - overallStartTime) / 1000000000.0d;
            final double overallSearchRate = numSearches / numOverallSeconds;

            final double overallAvgDuration;
            if (numSearches > 0L) {
                overallAvgDuration = 1.0d * totalDuration / numSearches / 1000000;
            } else {
                overallAvgDuration = 0.0d;
            }

            out(formatter.formatRow(recentSearchRate, recentAvgDuration, recentEntriesPerSearch,
                    recentErrorRate, overallSearchRate, overallAvgDuration));

            lastNumSearches = numSearches;
            lastNumEntries = numEntries;
            lastNumErrors = numErrors;
            lastDuration = totalDuration;
        }

        lastEndTime = endTime;
    }

    // Stop all of the threads.
    ResultCode resultCode = ResultCode.SUCCESS;
    for (final QueryRateThread t : threads) {
        t.signalShutdown();
    }

    // Interrupt any blocked threads after a grace period.
    final WakeableSleeper sleeper = new WakeableSleeper();
    sleeper.sleep(1000);
    mgr.shutdown();

    for (final QueryRateThread t : threads) {
        final ResultCode r = t.waitForShutdown();
        if (resultCode == ResultCode.SUCCESS) {
            resultCode = r;
        }
    }

    return resultCode;
}

From source file:com.ibm.og.client.ApacheClient.java

private HttpClientConnectionManager createConnectionManager() {
    final PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(
            RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", createPlainConnectionSocketFactory())
                    .register("https", createSslConnectionSocketFactory()).build(),
            null, null, null, -1, TimeUnit.MILLISECONDS);
    manager.setDefaultSocketConfig(createSocketConfig());
    manager.setMaxTotal(Integer.MAX_VALUE);
    manager.setDefaultMaxPerRoute(Integer.MAX_VALUE);
    manager.setValidateAfterInactivity(this.validateAfterInactivity);
    return manager;
}

From source file:com.jivesoftware.os.routing.bird.http.client.HttpClientFactoryProvider.java

public HttpClientFactory createHttpClientFactory(Collection<HttpClientConfiguration> configurations,
        boolean latentClient) {

    HttpClientConfig httpClientConfig = locateConfig(configurations, HttpClientConfig.class,
            HttpClientConfig.newBuilder().build());
    HttpClientSSLConfig sslConfig = locateConfig(configurations, HttpClientSSLConfig.class, null);

    String scheme;//w  ww.  j ava2  s.  c  om
    PoolingHttpClientConnectionManager poolingHttpClientConnectionManager;
    if (sslConfig != null && sslConfig.isUseSsl()) {
        LayeredConnectionSocketFactory sslSocketFactory;
        if (sslConfig.getCustomSSLSocketFactory() != null) {
            sslSocketFactory = sslConfig.getCustomSSLSocketFactory();
        } else {
            sslSocketFactory = SSLConnectionSocketFactory.getSocketFactory();
        }

        scheme = "https";
        poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(
                RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.getSocketFactory())
                        .register("https", sslSocketFactory).build());
    } else {
        scheme = "http";
        poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
    }

    if (httpClientConfig.getMaxConnections() > 0) {
        poolingHttpClientConnectionManager.setMaxTotal(httpClientConfig.getMaxConnections());
    } else {
        poolingHttpClientConnectionManager.setMaxTotal(Integer.MAX_VALUE);
    }

    if (httpClientConfig.getMaxConnectionsPerHost() > 0) {
        poolingHttpClientConnectionManager.setDefaultMaxPerRoute(httpClientConfig.getMaxConnectionsPerHost());
    } else {
        poolingHttpClientConnectionManager.setDefaultMaxPerRoute(Integer.MAX_VALUE);
    }

    poolingHttpClientConnectionManager.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(
            httpClientConfig.getSocketTimeoutInMillis() > 0 ? httpClientConfig.getSocketTimeoutInMillis() : 0)
            .build());

    Closeable closeable;
    HttpClientConnectionManager clientConnectionManager;
    clientConnectionManager = poolingHttpClientConnectionManager;
    closeable = poolingHttpClientConnectionManager;

    return (OAuthSigner signer, String host, int port) -> {
        HttpClientBuilder httpClientBuilder = HttpClients.custom()
                .setConnectionManager(clientConnectionManager);

        CloseableHttpClient client = httpClientBuilder.build();
        HttpClient httpClient = new ApacheHttpClient441BackedHttpClient(scheme, host, port, signer, client,
                closeable, httpClientConfig.getCopyOfHeadersForEveryRequest());

        if (latentClient) {
            httpClient = new LatentHttpClient(httpClient);
        }
        return httpClient;
    };
}