Example usage for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory

List of usage examples for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory

Introduction

In this page you can find the example usage for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory.

Prototype

public SSLConnectionSocketFactory(final javax.net.ssl.SSLSocketFactory socketfactory,
            final X509HostnameVerifier hostnameVerifier) 

Source Link

Usage

From source file:com.xebialabs.overthere.winrm.WinRmClient.java

private void configureTrust(final HttpClientBuilder httpclientBuilder)
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {

    if (!"https".equalsIgnoreCase(targetURL.getProtocol())) {
        return;//  ww  w  .ja v  a 2 s .com
    }

    final TrustStrategy trustStrategy = httpsCertTrustStrategy.getStrategy();
    SSLContext sslContext = SSLContextBuilder.create().loadTrustMaterial(trustStrategy).build();
    final HostnameVerifier hostnameVerifier = httpsHostnameVerifyStrategy.getVerifier();
    final SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext,
            hostnameVerifier);
    httpclientBuilder.setSSLSocketFactory(socketFactory);
}

From source file:org.bonitasoft.connectors.rest.RESTConnector.java

/**
 * Set the request builder based on the request
 * /*ww w.j a  v  a 2s .c  om*/
 * @param ssl The request SSL options
 * @param httpClientBuilder The request builder
 * @throws Exception
 */
private void setSSL(final SSL ssl, final HttpClientBuilder httpClientBuilder) throws Exception {
    if (ssl != null) {
        final SSLContextBuilder sslContextBuilder = new SSLContextBuilder();

        if (ssl.getTrustStore() != null) {
            final KeyStore trustStore = ssl.getTrustStore().generateKeyStore();
            if (ssl.isUseSelfSignedCertificate()) {
                sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
            } else {
                sslContextBuilder.loadTrustMaterial(trustStore);
            }
        }

        if (ssl.getKeyStore() != null) {
            final KeyStore keyStore = ssl.getKeyStore().generateKeyStore();
            final String keyStorePassword = ssl.getKeyStore().getPassword();
            sslContextBuilder.loadKeyMaterial(keyStore, keyStorePassword.toCharArray());
        }

        sslContextBuilder.setSecureRandom(null);

        if (ssl.isUseTLS()) {
            sslContextBuilder.useTLS();
        } else {
            sslContextBuilder.useSSL();
        }

        final SSLVerifier verifier = ssl.getSslVerifier();
        X509HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER;
        switch (verifier) {
        case BROWSER:
            hostnameVerifier = SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
            break;
        case ALLOW:
            hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
            break;
        case STRICT:
            hostnameVerifier = SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER;
            break;
        default:
            hostnameVerifier = SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER;
            break;
        }

        final SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
                sslContextBuilder.build(), hostnameVerifier);
        httpClientBuilder.setSSLSocketFactory(socketFactory);
    }
}

From source file:com.clustercontrol.http.util.GetHttpResponse.java

private CloseableHttpClient getHttpClient()
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    if (m_client == null) {
        List<Header> headers = new ArrayList<>();

        HttpClientBuilder builder = HttpClients.custom().setDefaultCredentialsProvider(m_cledentialProvider)
                .setDefaultHeaders(headers);

        if (!this.m_needAuthSSLCert) {
            // SSL ??
            TrustStrategy trustStrategy = new TrustStrategy() {
                @Override/* w  ww . ja v  a  2s  .c  o  m*/
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            };
            builder.setSSLSocketFactory(new SSLConnectionSocketFactory(
                    new SSLContextBuilder().loadTrustMaterial(null, trustStrategy).build(),
                    new NoopHostnameVerifier()));
        }
        RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT)
                .setConnectTimeout(m_connectTimeout).setSocketTimeout(m_requestTimeout).build();
        builder.setDefaultRequestConfig(requestConfig);

        if (m_proxyHost != null) {
            HttpHost proxy = new HttpHost(m_proxyHost, m_proxyPort,
                    m_proxyScheme == null ? "https" : m_proxyScheme);
            if (m_proxyUser != null && m_proxyPassword != null) {
                m_cledentialProvider.setCredentials(new AuthScope(proxy.getHostName(), proxy.getPort()),
                        new UsernamePasswordCredentials(m_proxyUser, m_proxyPassword));
            }
            builder.setProxy(proxy);
        }

        if (m_userAgent != null) {
            headers.add(new BasicHeader(HTTP.USER_AGENT, m_userAgent));
        }

        if (m_cancelProxyCache) {
            // ?
            // https://www.ipa.go.jp/security/awareness/vendor/programmingv2/contents/405.html
            headers.add(new BasicHeader("Cache-Control", "no-cache"));
            headers.add(new BasicHeader("Pragma", "no-cache"));
        }

        if (keepAlive) {
            headers.add(new BasicHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE));
        } else {
            headers.add(new BasicHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE));
        }
        m_client = builder.build();
    }

    return m_client;
}

From source file:eu.vital.TrustManager.connectors.dms.DMSManager.java

private String query2(String DMS_endpoint, String postObject)
        throws NoSuchAlgorithmException, KeyStoreException, IOException, KeyManagementException {

    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustStrategy() {
        @Override/*w  w w .  j  ava 2 s  . c om*/
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    });

    SSLConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(builder.build(),
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    CloseableHttpClient httpClient = HttpClients.custom().setRedirectStrategy(new LaxRedirectStrategy())
            .setSSLSocketFactory(sslSF).build();

    HttpPost postRequest = new HttpPost(dms_URL + "/" + DMS_endpoint);
    postRequest.addHeader("Content-Type", "application/json");
    postRequest.addHeader("vitalAccessToken", cookie.substring(17));

    HttpEntity entityPost = new StringEntity(postObject, StandardCharsets.UTF_8);
    postRequest.setEntity(entityPost);

    CloseableHttpResponse response = httpClient.execute(postRequest);

    try {
        //(CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(postRequest)) 
        //System.out.println(response.getStatusLine());
        HttpEntity entity = response.getEntity();
        if (entity == null)
            return null;
        return EntityUtils.toString(entity);
        //EntityUtils.consume(entity);
    } catch (IOException | ParseException e) {
        //logger.error(e.toString());
        //throw new ConnectionErrorException("Error in connection with DMSManager");
    }
    return null;
}

From source file:org.archive.modules.fetcher.FetchHTTPRequest.java

protected HttpClientConnectionManager buildConnectionManager() {
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE).register("https",
                    new SSLConnectionSocketFactory(fetcher.sslContext(), new AllowAllHostnameVerifier()) {

                        @Override
                        public Socket createLayeredSocket(final Socket socket, final String target,
                                final int port, final HttpContext context) throws IOException {

                            return super.createLayeredSocket(socket, isDisableSNI() ? "" : target, port,
                                    context);
                        }//from w w  w. j a va  2s .com
                    })
            .build();

    DnsResolver dnsResolver = new ServerCacheResolver(fetcher.getServerCache());

    ManagedHttpClientConnectionFactory connFactory = new ManagedHttpClientConnectionFactory() {
        private static final int DEFAULT_BUFSIZE = 8 * 1024;

        @Override
        public ManagedHttpClientConnection create(HttpRoute route, ConnectionConfig config) {
            final ConnectionConfig cconfig = config != null ? config : ConnectionConfig.DEFAULT;
            CharsetDecoder chardecoder = null;
            CharsetEncoder charencoder = null;
            final Charset charset = cconfig.getCharset();
            final CodingErrorAction malformedInputAction = cconfig.getMalformedInputAction() != null
                    ? cconfig.getMalformedInputAction()
                    : CodingErrorAction.REPORT;
            final CodingErrorAction unmappableInputAction = cconfig.getUnmappableInputAction() != null
                    ? cconfig.getUnmappableInputAction()
                    : CodingErrorAction.REPORT;
            if (charset != null) {
                chardecoder = charset.newDecoder();
                chardecoder.onMalformedInput(malformedInputAction);
                chardecoder.onUnmappableCharacter(unmappableInputAction);
                charencoder = charset.newEncoder();
                charencoder.onMalformedInput(malformedInputAction);
                charencoder.onUnmappableCharacter(unmappableInputAction);
            }
            return new RecordingHttpClientConnection(DEFAULT_BUFSIZE, DEFAULT_BUFSIZE, chardecoder, charencoder,
                    cconfig.getMessageConstraints(), null, null, DefaultHttpRequestWriterFactory.INSTANCE,
                    DefaultHttpResponseParserFactory.INSTANCE);
        }
    };
    BasicHttpClientConnectionManager connMan = new BasicHttpClientConnectionManager(socketFactoryRegistry,
            connFactory, null, dnsResolver);

    SocketConfig.Builder socketConfigBuilder = SocketConfig.custom();
    socketConfigBuilder.setSoTimeout(fetcher.getSoTimeoutMs());
    connMan.setSocketConfig(socketConfigBuilder.build());

    return connMan;
}

From source file:com.lehman.ic9.net.httpClient.java

/**
 * Build client method is used initialize the HTTP client and is 
 * called from perform request./*from w w w  .  j  av a 2s  .  co m*/
 * @param httpGet is a HttpRequest object with the request.
 * @throws NoSuchAlgorithmException Exception
 * @throws KeyStoreException Exception
 * @throws KeyManagementException Exception
 * @throws AuthenticationException Exception
 */
private void buildClient(HttpRequest httpGet)
        throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException, AuthenticationException {
    this.hcb = HttpClients.custom();
    this.hcb.setDefaultCookieStore(this.cs);
    this.hcb.setDefaultCredentialsProvider(this.cp);
    this.hcb.setDefaultRequestConfig(this.rcb.build());

    if (this.allowSelfSigned) {
        SSLContextBuilder sslBuilder = new SSLContextBuilder();
        sslBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslBuilder.build(),
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        this.hcb.setSSLSocketFactory(sslsf);
    }

    this.buildAuth(httpGet);

    if (this.tcpNoDelay) {
        SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
        this.hcb.setDefaultSocketConfig(socketConfig);
    }

    this.cli = hcb.build();
}

From source file:org.apache.manifoldcf.crawler.connectors.livelink.LivelinkConnector.java

protected void getSession() throws ManifoldCFException, ServiceInterruption {
    getSessionParameters();/*from   w w  w.j  a va  2  s . c o  m*/
    if (hasConnected == false) {
        int socketTimeout = 900000;
        int connectionTimeout = 300000;

        // Set up connection manager
        connectionManager = new PoolingHttpClientConnectionManager();

        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        // Set up ingest ssl if indicated
        SSLConnectionSocketFactory myFactory = null;
        if (ingestKeystoreManager != null) {
            myFactory = new SSLConnectionSocketFactory(
                    new InterruptibleSocketFactory(ingestKeystoreManager.getSecureSocketFactory(),
                            connectionTimeout),
                    new BrowserCompatHostnameVerifier());
        }

        // Set up authentication to use
        if (ingestNtlmDomain != null) {
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new NTCredentials(ingestNtlmUsername, ingestNtlmPassword, currentHost, ingestNtlmDomain));
        }

        HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connectionManager)
                .setMaxConnTotal(1).disableAutomaticRetries()
                .setDefaultRequestConfig(RequestConfig.custom().setCircularRedirectsAllowed(true)
                        .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true)
                        .setExpectContinueEnabled(true).setConnectTimeout(connectionTimeout)
                        .setConnectionRequestTimeout(socketTimeout).build())
                .setDefaultSocketConfig(
                        SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
                .setDefaultCredentialsProvider(credentialsProvider)
                .setRequestExecutor(new HttpRequestExecutor(socketTimeout))
                .setRedirectStrategy(new DefaultRedirectStrategy());

        if (myFactory != null)
            builder.setSSLSocketFactory(myFactory);

        httpClient = builder.build();

        // System.out.println("Connection server object = "+llServer.toString());

        // Establish the actual connection
        int sanityRetryCount = FAILURE_RETRY_COUNT;
        while (true) {
            GetSessionThread t = new GetSessionThread();
            try {
                t.start();
                t.finishUp();
                hasConnected = true;
                break;
            } catch (InterruptedException e) {
                t.interrupt();
                throw new ManifoldCFException("Interrupted: " + e.getMessage(), e,
                        ManifoldCFException.INTERRUPTED);
            } catch (RuntimeException e2) {
                sanityRetryCount = handleLivelinkRuntimeException(e2, sanityRetryCount, true);
            }
        }
    }
    expirationTime = System.currentTimeMillis() + expirationInterval;
}

From source file:org.elasticsearch.xpack.security.authc.saml.SamlRealm.java

private static Tuple<AbstractReloadingMetadataResolver, Supplier<EntityDescriptor>> parseHttpMetadata(
        String metadataUrl, RealmConfig config, SSLService sslService)
        throws ResolverException, ComponentInitializationException, PrivilegedActionException {
    final String entityId = require(config, IDP_ENTITY_ID);

    HttpClientBuilder builder = HttpClientBuilder.create();
    // ssl setup//w  w w  .j a v  a  2s.  co  m
    Settings sslSettings = config.settings().getByPrefix(SamlRealmSettings.SSL_PREFIX);
    boolean isHostnameVerificationEnabled = sslService.getVerificationMode(sslSettings, Settings.EMPTY)
            .isHostnameVerificationEnabled();
    HostnameVerifier verifier = isHostnameVerificationEnabled ? new DefaultHostnameVerifier()
            : NoopHostnameVerifier.INSTANCE;
    SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(
            sslService.sslSocketFactory(sslSettings), verifier);
    builder.setSSLSocketFactory(factory);

    HTTPMetadataResolver resolver = new PrivilegedHTTPMetadataResolver(builder.build(), metadataUrl);
    TimeValue refresh = IDP_METADATA_HTTP_REFRESH.get(config.settings());
    resolver.setMinRefreshDelay(refresh.millis());
    resolver.setMaxRefreshDelay(refresh.millis());
    initialiseResolver(resolver, config);

    return new Tuple<>(resolver, () -> {
        // for some reason the resolver supports its own trust engine and custom socket factories.
        // we do not use these as we'd rather rely on the JDK versions for TLS security!
        SpecialPermission.check();
        try {
            return AccessController.doPrivileged(
                    (PrivilegedExceptionAction<EntityDescriptor>) () -> resolveEntityDescriptor(resolver,
                            entityId, metadataUrl));
        } catch (PrivilegedActionException e) {
            throw ExceptionsHelper.convertToRuntime((Exception) ExceptionsHelper.unwrapCause(e));
        }
    });
}

From source file:com.ibm.team.build.internal.hjplugin.util.HttpUtils.java

private static synchronized SSLConnectionSocketFactory getSSLConnectionSocketFactory()
        throws GeneralSecurityException {
    if (SSL_CONNECTION_SOCKET_FACTORY == null) {

        /** Create a trust manager that does not validate certificate chains */
        TrustManager trustManager = new X509TrustManager() {
            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                /** Ignore Method Call */
            }/*from   w  w w . j a  v a 2  s .  c o m*/

            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                /** Ignore Method Call */
            }

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        SSLContext sslContext = SSLContextUtil.createSSLContext(trustManager);
        SSL_CONNECTION_SOCKET_FACTORY = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {
            @Override
            public void verify(String host, SSLSocket ssl) throws IOException {
            }

            @Override
            public void verify(String host, X509Certificate cert) throws SSLException {
            }

            @Override
            public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
            }

            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });
    }
    return SSL_CONNECTION_SOCKET_FACTORY;
}

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.//  ww w. j av  a2 s.  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;
}