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(
            final HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory) 

Source Link

Usage

From source file:com.wudaosoft.net.httpclient.Request.java

protected void init() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException,
        CertificateException, IOException {

    Args.notNull(hostConfig, "Host config");

    SSLConnectionSocketFactory sslConnectionSocketFactory = null;

    if (sslcontext == null) {

        if (hostConfig.getCA() != null) {
            // Trust root CA and all self-signed certs
            SSLContext sslcontext1 = SSLContexts.custom().loadTrustMaterial(hostConfig.getCA(),
                    hostConfig.getCAPassword(), TrustSelfSignedStrategy.INSTANCE).build();

            // Allow TLSv1 protocol only
            sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext1, new String[] { "TLSv1" },
                    null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        } else {/*from  w  ww  .j  a v  a2 s .  c  om*/

            if (isTrustAll) {

                SSLContext sslcontext1 = SSLContext.getInstance("TLS");

                TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    @Override
                    public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                            throws CertificateException {

                    }

                    @Override
                    public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                            throws CertificateException {
                    }

                } };

                sslcontext1.init(null, trustAllCerts, null);

                sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext1,
                        NoopHostnameVerifier.INSTANCE);
            } else {
                sslConnectionSocketFactory = SSLConnectionSocketFactory.getSocketFactory();
            }
        }
    } else {

        sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    }

    if (keepAliveStrategy == null) {
        keepAliveStrategy = new ConnectionKeepAliveStrategy() {

            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                // Honor 'keep-alive' header
                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")) {
                        try {
                            return Long.parseLong(value) * 1000;
                        } catch (NumberFormatException ignore) {
                        }
                    }
                }
                // HttpHost target = (HttpHost)
                // context.getAttribute(HttpClientContext.HTTP_TARGET_HOST);
                // if
                // ("xxxxx".equalsIgnoreCase(target.getHostName()))
                // {
                // // Keep alive for 5 seconds only
                // return 3 * 1000;
                // } else {
                // // otherwise keep alive for 30 seconds
                // return 30 * 1000;
                // }

                return 30 * 1000;
            }

        };
    }

    if (retryHandler == null) {
        retryHandler = new HttpRequestRetryHandler() {

            public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
                if (executionCount >= 3) {
                    // Do not retry if over max retry count
                    return false;
                }
                if (exception instanceof InterruptedIOException) {
                    // Timeout
                    return false;
                }
                if (exception instanceof UnknownHostException) {
                    // Unknown host
                    return false;
                }
                if (exception instanceof ConnectTimeoutException) {
                    // Connection refused
                    return false;
                }
                if (exception instanceof SSLException) {
                    // SSL handshake exception
                    return false;
                }
                HttpClientContext clientContext = HttpClientContext.adapt(context);
                HttpRequest request = clientContext.getRequest();
                boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
                if (idempotent) {
                    // Retry if the request is considered idempotent
                    return true;
                }
                return false;
            }
        };
    }

    connManager = new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslConnectionSocketFactory).build());

    if (hostConfig.getHost() != null) {

        connManager.setMaxTotal(hostConfig.getPoolSize() + 60);

        connManager.setMaxPerRoute(
                new HttpRoute(hostConfig.getHost(), null,
                        !HttpHost.DEFAULT_SCHEME_NAME.equals(hostConfig.getHost().getSchemeName())),
                hostConfig.getPoolSize());

        connManager.setDefaultMaxPerRoute(20);
    } else {
        connManager.setMaxTotal(hostConfig.getPoolSize());
        int hostCount = hostConfig.getHostCount() == 0 ? 10 : hostConfig.getHostCount();
        connManager.setDefaultMaxPerRoute(hostConfig.getPoolSize() / hostCount);
    }

    // connManager.setValidateAfterInactivity(2000);

    // Create socket configuration
    SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).setSoKeepAlive(isKeepAlive).build();
    connManager.setDefaultSocketConfig(socketConfig);

    // Create connection configuration
    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE)
            .setCharset(hostConfig.getCharset() == null ? Consts.UTF_8 : hostConfig.getCharset()).build();
    connManager.setDefaultConnectionConfig(connectionConfig);

    new IdleConnectionMonitorThread(connManager).start();

    if (requestInterceptor == null) {
        requestInterceptor = new SortHeadersInterceptor(hostConfig);
    }

    if (!hostConfig.isMulticlient()) {
        defaultHttpContext = HttpClientContext.create();
        httpClient = create();
    }
}

From source file:nl.armatiek.xslweb.configuration.WebApp.java

public CloseableHttpClient getHttpClient() {
    if (httpClient == null) {
        PoolingHttpClientConnectionManager cm;
        if (Context.getInstance().getTrustAllCerts()) {
            try {
                SSLContextBuilder scb = SSLContexts.custom();
                scb.loadTrustMaterial(null, new TrustStrategy() {
                    @Override/*from   w  w w.  j a va 2s. c  om*/
                    public boolean isTrusted(X509Certificate[] chain, String authType)
                            throws CertificateException {
                        return true;
                    }
                });
                SSLContext sslContext = scb.build();
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                        SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                        .<ConnectionSocketFactory>create().register("https", sslsf)
                        .register("http", new PlainConnectionSocketFactory()).build();
                cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            } catch (Exception e) {
                logger.warn("Could not set HttpClient to trust all SSL certificates", e);
                cm = new PoolingHttpClientConnectionManager();
            }
        } else {
            cm = new PoolingHttpClientConnectionManager();
        }
        cm.setMaxTotal(200);
        cm.setDefaultMaxPerRoute(20);
        HttpHost localhost = new HttpHost("localhost", 80);
        cm.setMaxPerRoute(new HttpRoute(localhost), 50);
        HttpClientBuilder builder = HttpClients.custom().setConnectionManager(cm);
        builder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()));
        builder.setDefaultCookieStore(new BasicCookieStore());
        httpClient = builder.build();
    }
    return httpClient;
}

From source file:com.nominanuda.web.http.HttpCoreHelper.java

public HttpClient createClient(int maxConnPerRoute, long connTimeoutMillis, long soTimeoutMillis,
        @Nullable String proxyHostAnPort) {
    Registry<ConnectionSocketFactory> defaultRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", SSLConnectionSocketFactory.getSocketFactory()).build();
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(defaultRegistry);
    connMgr.setDefaultMaxPerRoute(maxConnPerRoute);
    SocketConfig sCfg = SocketConfig.custom().setSoTimeout((int) soTimeoutMillis)
            .setSoTimeout((int) connTimeoutMillis).build();
    connMgr.setDefaultSocketConfig(sCfg);
    HttpClientBuilder hcb = HttpClientBuilder.create();
    hcb.setDefaultSocketConfig(sCfg).setConnectionManager(connMgr);
    if (proxyHostAnPort == null) {
    } else if ("jvm".equalsIgnoreCase(proxyHostAnPort)) {
        SystemDefaultRoutePlanner rp = new SystemDefaultRoutePlanner(ProxySelector.getDefault());
        hcb.setRoutePlanner(rp);//from www  .j  a  v a  2 s  . co m
    } else {
        String[] hostAndPort = proxyHostAnPort.split(":");
        Check.illegalargument.assertTrue(hostAndPort.length < 3, "wrong hostAndPort:" + proxyHostAnPort);
        String host = hostAndPort[0];
        int port = 80;
        if (hostAndPort.length > 1) {
            port = Integer.valueOf(hostAndPort[1]);
        }
        HttpHost proxy = new HttpHost(host, port);
        hcb.setProxy(proxy);
    }
    HttpClient httpClient = hcb.build();
    return httpClient;
}

From source file:org.apache.sling.discovery.etcd.EtcdDiscoveryService.java

private void buildHttpClient(@Nonnull String keystoreFilePath, @Nonnull String keystorePwdFilePath) {

    boolean hasKeyStore = !isEmpty(keystoreFilePath);

    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)
            .setConnectTimeout(connectionTimeout).setRedirectsEnabled(true).setStaleConnectionCheckEnabled(true)
            .build();//  w w w .j  a v  a2  s .  c  om

    HttpClientBuilder builder = HttpClients.custom().setDefaultRequestConfig(requestConfig)
            .addInterceptorFirst(new GzipRequestInterceptor())
            .addInterceptorFirst(new GzipResponseInterceptor());

    if (hasKeyStore) {

        final SSLContextBuilder sslContextBuilder = SSLContexts.custom();

        LOG.info("Loading keystore from file: {}", keystoreFilePath);
        char[] pwd = readPwd(keystorePwdFilePath);
        try {
            KeyStore keystore = loadKeyStore(keystoreFilePath, pwd);
            sslContextBuilder.loadTrustMaterial(keystore);
            sslContextBuilder.loadKeyMaterial(keystore, pwd);
            LOG.info("Setup custom SSL context");
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                    sslContextBuilder.build());
            Registry<ConnectionSocketFactory> connectionSocketFactory = RegistryBuilder
                    .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE)
                    .register("https", sslConnectionSocketFactory).build();

            builder.setSSLSocketFactory(sslConnectionSocketFactory);

            connectionManager = new PoolingHttpClientConnectionManager(connectionSocketFactory);

        } catch (UnrecoverableKeyException e) {
            throw wrap(e);
        } catch (NoSuchAlgorithmException e) {
            throw wrap(e);
        } catch (KeyStoreException e) {
            throw wrap(e);
        } catch (KeyManagementException e) {
            throw wrap(e);
        } finally {
            reset(pwd);
        }

    } else {
        connectionManager = new PoolingHttpClientConnectionManager();
    }

    builder.setConnectionManager(connectionManager);
    httpClient = builder.build();
}

From source file:com.tremolosecurity.provisioning.core.providers.AlfrescoProviderREST.java

@Override
public void init(Map<String, Attribute> cfg, ConfigManager cfgMgr, String name) throws ProvisioningException {

    this.name = name;

    this.loginId = cfg.get("adminUser").getValues().get(0);
    this.loginPwd = cfg.get("adminPwd").getValues().get(0);
    this.endpoint = cfg.get("url").getValues().get(0);
    this.uidAttrName = cfg.get("uidAttributeName").getValues().get(0);
    this.useLastMile = Boolean.parseBoolean(cfg.get("useLastMile").getValues().get(0));
    this.lastMileKeyAlias = cfg.get("lastMileKeyAlias").getValues().get(0);

    this.cfg = cfgMgr;

    phcm = new PoolingHttpClientConnectionManager(cfgMgr.getHttpClientSocketRegistry());
    httpclient = HttpClients.custom().setConnectionManager(phcm).build();

    WebServiceFactory.setEndpointAddress(this.endpoint);

}

From source file:nl.nn.adapterframework.http.HttpSenderBase.java

public void open() throws SenderException {
    // In order to support multiThreading and connectionPooling
    // If a sslSocketFactory has been defined, the connectionManager has to be initialized with the sslSocketFactory
    if (sslSocketFactory != null) {
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory).build();
        connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        log.debug(getLogPrefix()//from   www  . j a  va 2s.  com
                + "created PoolingHttpClientConnectionManager with custom SSLConnectionSocketFactory");
    } else {
        connectionManager = new PoolingHttpClientConnectionManager();
        log.debug(getLogPrefix() + "created default PoolingHttpClientConnectionManager");
    }

    connectionManager.setMaxTotal(getMaxConnections());

    log.debug(getLogPrefix() + "set up connectionManager, inactivity checking ["
            + connectionManager.getValidateAfterInactivity() + "]");
    boolean staleChecking = (connectionManager.getValidateAfterInactivity() >= 0);
    if (staleChecking != isStaleChecking()) {
        log.info(getLogPrefix() + "set up connectionManager, setting stale checking [" + isStaleChecking()
                + "]");
        connectionManager.setValidateAfterInactivity(getStaleTimeout());
    }

    httpClientBuilder.setConnectionManager(connectionManager);

    if (transformerPool != null) {
        try {
            transformerPool.open();
        } catch (Exception e) {
            throw new SenderException(getLogPrefix() + "cannot start TransformerPool", e);
        }
    }

    httpClient = httpClientBuilder.build();
}

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.//w  w  w . j av a2 s.co  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.github.sardine.impl.SardineImpl.java

/**
 * Use fail fast connection manager when connections are not released properly.
 *
 * @param schemeRegistry Protocol registry
 * @return Default connection manager// w  ww  . ja  va 2s  . c o m
 */
protected HttpClientConnectionManager createDefaultConnectionManager(
        Registry<ConnectionSocketFactory> schemeRegistry) {
    return new PoolingHttpClientConnectionManager(schemeRegistry);
}

From source file:org.openbaton.sdk.api.util.RestRequest.java

private CloseableHttpClient getHttpClientForSsl() {
    SSLContext sslContext = null;
    try {/*from   w  w w.  j av  a  2s .  co m*/
        sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
    } catch (NoSuchAlgorithmException e) {
        log.error("Could not initialize the HttpClient for SSL connections");
        log.error(e.getMessage(), e);
    } catch (KeyManagementException e) {
        log.error("Could not initialize the HttpClient for SSL connections");
        log.error(e.getMessage(), e);
    } catch (KeyStoreException e) {
        log.error("Could not initialize the HttpClient for SSL connections");
        log.error(e.getMessage(), e);
    }

    // necessary to trust self signed certificates
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
            new String[] { "TLSv1" }, null, new NoopHostnameVerifier());

    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslConnectionSocketFactory).build();

    return HttpClientBuilder.create().setDefaultRequestConfig(config)
            .setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryRegistry))
            .setSSLSocketFactory(sslConnectionSocketFactory).build();
}

From source file:org.openbaton.marketplace.core.VNFPackageManagement.java

private CloseableHttpClient getHttpClientForSsl(RequestConfig config) {
    SSLContext sslContext = null;
    try {/* ww  w .  j av a2s.c  om*/
        sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
    } catch (NoSuchAlgorithmException e) {
        log.error("Could not initialize the HttpClient for SSL connections");
        log.error(e.getMessage(), e);
    } catch (KeyManagementException e) {
        log.error("Could not initialize the HttpClient for SSL connections");
        log.error(e.getMessage(), e);
    } catch (KeyStoreException e) {
        log.error("Could not initialize the HttpClient for SSL connections");
        log.error(e.getMessage(), e);
    }

    // necessary to trust self signed certificates
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
            new String[] { "TLSv1" }, null, new NoopHostnameVerifier());

    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslConnectionSocketFactory).build();

    return HttpClientBuilder.create().setDefaultRequestConfig(config)
            .setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryRegistry))
            .setSSLSocketFactory(sslConnectionSocketFactory).build();
}