Example usage for org.apache.http.conn.socket PlainConnectionSocketFactory PlainConnectionSocketFactory

List of usage examples for org.apache.http.conn.socket PlainConnectionSocketFactory PlainConnectionSocketFactory

Introduction

In this page you can find the example usage for org.apache.http.conn.socket PlainConnectionSocketFactory PlainConnectionSocketFactory.

Prototype

public PlainConnectionSocketFactory() 

Source Link

Usage

From source file:de.tudarmstadt.ukp.shibhttpclient.ShibHttpClient.java

/**
 * Create a new client (with an explicit proxy and possibly transparent authentication)
 * //www .j a  v a 2  s  .  com
 * @param aIdpUrl
 *            the URL of the IdP. Should probably be something ending in "/SAML2/SOAP/ECP"
 * @param aUsername
 *            the user name to log into the IdP.
 * @param aPassword
 *            the password to log in to the IdP.
 * @param aProxy
 *            if not {@code null}, use this proxy instead of the default system proxy (if any)
 * @param anyCert
 *            if {@code true}, accept any certificate from any remote host. Otherwise,
 *            certificates need to be installed in the JRE.
 * @param transparentAuth
 *            if {@code true} (default), add a HttpRequestPostProcessor to transparently 
 *            authenticate. Otherwise, you must handle the authentication process yourself.
 */
public ShibHttpClient(String aIdpUrl, String aUsername, String aPassword, HttpHost aProxy, boolean anyCert,
        boolean transparentAuth) {

    setIdpUrl(aIdpUrl);
    setUsername(aUsername);
    setPassword(aPassword);

    // Use a pooling connection manager, because we'll have to do a call out to the IdP
    // while still being in a connection with the SP
    PoolingHttpClientConnectionManager connMgr;
    if (anyCert) {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory>create().register("http", new PlainConnectionSocketFactory())
                    .register("https", new SSLConnectionSocketFactory(builder.build(),
                            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER))
                    .build();
            connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        } catch (GeneralSecurityException e) {
            // There shouldn't be any of these exceptions, because we do not use an actual
            // keystore
            throw new IllegalStateException(e);
        }
    } else {
        connMgr = new PoolingHttpClientConnectionManager();
    }
    connMgr.setMaxTotal(10);
    connMgr.setDefaultMaxPerRoute(5);

    // The client needs to remember the auth cookie
    cookieStore = new BasicCookieStore();
    RequestConfig globalRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
            .build();

    // Let's throw all common client elements into one builder object
    HttpClientBuilder customClient = HttpClients.custom().setConnectionManager(connMgr)
            // The client needs to remember the auth cookie
            .setDefaultRequestConfig(globalRequestConfig).setDefaultCookieStore(cookieStore)
            // Add the ECP/PAOS headers - needs to be added first so the cookie we get from
            // the authentication can be handled by the RequestAddCookies interceptor later
            .addInterceptorFirst(new HttpRequestPreprocessor());

    // Automatically log into IdP if transparent Shibboleth authentication handling is requested (default)
    if (transparentAuth) {
        customClient = customClient.addInterceptorFirst(new HttpRequestPostprocessor());
    }

    // Build the client with/without proxy settings 
    if (aProxy == null) {
        // use the proxy settings of the JVM, if specified 
        client = customClient.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()))
                .build();
    } else {
        // use the explicit proxy
        client = customClient.setProxy(aProxy).build();
    }

    parserPool = new BasicParserPool();
    parserPool.setNamespaceAware(true);
}

From source file:org.infinispan.server.test.rest.security.RESTCertSecurityTest.java

public static CloseableHttpClient securedClient(String alias) {
    try {/*from ww w. j  av  a  2  s.  co  m*/
        SSLContext ctx = SSLContext.getInstance("TLS");
        JBossJSSESecurityDomain jsseSecurityDomain = new JBossJSSESecurityDomain("client_cert_auth");
        jsseSecurityDomain.setKeyStorePassword("changeit");
        ClassLoader tccl = Thread.currentThread().getContextClassLoader();
        URL keystore = tccl.getResource("client.keystore");
        jsseSecurityDomain.setKeyStoreURL(keystore.getPath());
        jsseSecurityDomain.setClientAlias(alias);
        jsseSecurityDomain.reloadKeyAndTrustStore();
        KeyManager[] keyManagers = jsseSecurityDomain.getKeyManagers();
        TrustManager[] trustManagers = jsseSecurityDomain.getTrustManagers();
        ctx.init(keyManagers, trustManagers, null);
        X509HostnameVerifier verifier = new X509HostnameVerifier() {

            @Override
            public void verify(String s, SSLSocket sslSocket) throws IOException {
            }

            @Override
            public void verify(String s, X509Certificate x509Certificate) throws SSLException {
            }

            @Override
            public void verify(String s, String[] strings, String[] strings1) throws SSLException {
            }

            @Override
            public boolean verify(String string, SSLSession ssls) {
                return true;
            }
        };
        ConnectionSocketFactory sslssf = new SSLConnectionSocketFactory(ctx, verifier);//SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ConnectionSocketFactory plainsf = new PlainConnectionSocketFactory();
        Registry<ConnectionSocketFactory> sr = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", plainsf).register("https", sslssf).build();
        HttpClientConnectionManager pcm = new PoolingHttpClientConnectionManager(sr);
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(pcm).build();

        return httpClient;
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:com.liferay.jsonwebserviceclient.JSONWebServiceClientImpl.java

protected Registry<ConnectionSocketFactory> getSocketFactoryRegistry() {
    RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder
            .<ConnectionSocketFactory>create();

    registryBuilder.register("http", new PlainConnectionSocketFactory());
    registryBuilder.register("https", getSSLConnectionSocketFactory());

    return registryBuilder.build();
}

From source file:org.apache.metron.dataloads.taxii.TaxiiHandler.java

private static HttpClient buildClient(URL proxy, String username, String password) throws Exception {
    HttpClient client = new HttpClient(); // Start with a default TAXII HTTP client.

    // Create an Apache HttpClientBuilder to be customized by the command line arguments.
    HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties();

    // Proxy/*  w ww.ja  v  a2 s . c  o m*/
    if (proxy != null) {
        HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort(), proxy.getProtocol());
        builder.setProxy(proxyHost);
    }

    // Basic authentication. User & Password
    if (username != null ^ password != null) {
        throw new Exception("'username' and 'password' arguments are required to appear together.");
    }

    // from:  http://stackoverflow.com/questions/19517538/ignoring-ssl-certificate-in-apache-httpclient-4-3
    SSLContextBuilder ssbldr = new SSLContextBuilder();
    ssbldr.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ssbldr.build(),
            SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", new PlainConnectionSocketFactory()).register("https", sslsf).build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
    cm.setMaxTotal(20);//max connection

    System.setProperty("jsse.enableSNIExtension", "false"); //""
    CloseableHttpClient httpClient = builder.setSSLSocketFactory(sslsf).setConnectionManager(cm).build();

    client.setHttpclient(httpClient);
    return client;
}

From source file:com.liferay.sync.engine.session.Session.java

private HttpClientConnectionManager _getHttpClientConnectionManager(boolean trustSelfSigned) {

    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connectionFactory = new SyncManagedHttpClientConnectionFactory();

    try {/*  w w  w.  j  a  v  a  2  s .  c  om*/
        RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();

        registryBuilder.register("http", new PlainConnectionSocketFactory());

        if (trustSelfSigned) {
            registryBuilder.register("https", _getTrustingSSLSocketFactory());
        } else {
            registryBuilder.register("https", _getDefaultSSLSocketFactory());
        }

        Registry<ConnectionSocketFactory> registry = registryBuilder.build();

        return new PoolingHttpClientConnectionManager(registry, connectionFactory);
    } catch (Exception e) {
        _logger.error(e.getMessage(), e);
    }

    return new PoolingHttpClientConnectionManager(connectionFactory);
}

From source file:com.kixeye.chassis.transport.HttpTransportTest.java

@Test
public void testHttpServiceWithJsonWithHTTPSAndHTTP() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();

    properties.put("http.enabled", "true");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");

    properties.put("https.enabled", "true");
    properties.put("https.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("https.hostname", "localhost");
    properties.put("https.selfSigned", "true");

    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    StandardEnvironment environment = new StandardEnvironment();
    environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
    context.setEnvironment(environment);
    context.register(PropertySourcesPlaceholderConfigurer.class);
    context.register(TransportConfiguration.class);
    context.register(TestRestService.class);

    try {//from  www. j  ava 2  s  . c  o m
        context.refresh();

        final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class);

        SSLContextBuilder builder = SSLContexts.custom();
        builder.loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        });
        SSLContext sslContext = builder.build();
        SSLConnectionSocketFactory sslsf = 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;
                    }
                });

        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create().register("https", sslsf)
                .register("http", new PlainConnectionSocketFactory()).build();

        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);

        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(HttpClients.custom().setConnectionManager(cm).build());

        RestTemplate httpClient = new RestTemplate(requestFactory);
        httpClient.setErrorHandler(new ResponseErrorHandler() {
            public boolean hasError(ClientHttpResponse response) throws IOException {
                return response.getRawStatusCode() == HttpStatus.OK.value();
            }

            public void handleError(ClientHttpResponse response) throws IOException {

            }
        });

        httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
        httpClient.setMessageConverters(new ArrayList<HttpMessageConverter<?>>(
                Lists.newArrayList(new SerDeHttpMessageConverter(serDe))));

        TestObject response = httpClient.getForObject(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.postForObject(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/"),
                new TestObject("more stuff"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.getForObject(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        response = httpClient.getForObject(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/getFuture"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        response = httpClient.getForObject(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/getObservable"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        ResponseEntity<ServiceError> error = httpClient.postForEntity(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/"),
                new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code);

        error = httpClient.getForEntity(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/expectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode());
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description);

        error = httpClient.getForEntity(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/unexpectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        response = httpClient.postForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), new TestObject("stuff"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/getFuture"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/getObservable"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        error = httpClient.postForEntity(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"),
                new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code);

        error = httpClient.getForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/expectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode());
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description);

        error = httpClient.getForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/unexpectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code);
    } finally {
        context.close();
    }
}

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

private HttpClientConnectionManager getHttpClientConnectionManager() {
    final Lookup<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
            .<ConnectionSocketFactory>create().register("http", new PlainConnectionSocketFactory() {
                @Override/*w  w w  .  j  av a 2s . co  m*/
                public Socket createSocket(HttpContext context) throws IOException {
                    return socketFactory.createSocket();
                }
            }).register("https", new SSLConnectionSocketFactory(SSLContexts.createDefault(),
                    SSLConnectionSocketFactory.getDefaultHostnameVerifier()) {
                @Override
                public Socket createSocket(HttpContext context) throws IOException {
                    return socketFactory.createSocket();
                }
            }).build();
    return new BasicHttpClientConnectionManager(socketFactoryRegistry);
}

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// w  w  w .  j ava 2s.  c  o m
                    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.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  ava2 s  . com*/
 *
 * @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:org.hyperledger.fabric_ca.sdk.HFCAClient.java

private void setUpSSL() throws InvalidArgumentException {

    if (cryptoPrimitives == null) {
        try {/*from www.  j a  v  a2s . c  o  m*/
            cryptoPrimitives = new CryptoPrimitives();
            cryptoPrimitives.init();
        } catch (Exception e) {
            throw new InvalidArgumentException(e);
        }
    }

    if (isSSL && null == registry) {
        if (!properties.containsKey("pemBytes") && !properties.containsKey("pemFile")) {

            logger.warn("SSL with no CA certficates in either pemBytes or pemFile");

        }
        try {

            if (properties.containsKey("pemBytes")) {
                byte[] permbytes = (byte[]) properties.get("pemBytes");

                try (BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(permbytes))) {
                    cryptoPrimitives.addCACertificatesToTrustStore(bis);
                }

            }

            if (properties.containsKey("pemFile")) {
                String pemFile = properties.getProperty("pemFile");
                if (pemFile != null) {
                    String[] pems = pemFile.split("[ \t]*,[ \t]*");

                    for (String pem : pems) {
                        if (null != pem && !pem.isEmpty()) {
                            try {
                                try (BufferedInputStream bis = new BufferedInputStream(
                                        new ByteArrayInputStream(Files.readAllBytes(Paths.get(pem))))) {
                                    cryptoPrimitives.addCACertificatesToTrustStore(bis);
                                }
                            } catch (IOException e) {
                                throw new InvalidArgumentException(
                                        format("Unable to add CA certificate, can't open certificate file %s",
                                                new File(pem).getAbsolutePath()));
                            }
                        }
                    }
                }
            }

            SSLContext sslContext = SSLContexts.custom()
                    .loadTrustMaterial(cryptoPrimitives.getTrustStore(), null).build();

            ConnectionSocketFactory sf;
            if (null != properties && "true".equals(properties.getProperty("allowAllHostNames"))) {
                AllHostsSSLSocketFactory msf = new AllHostsSSLSocketFactory(cryptoPrimitives.getTrustStore());
                msf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                sf = msf;
            } else {
                sf = new SSLConnectionSocketFactory(sslContext);
            }

            registry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sf)
                    .register("http", new PlainConnectionSocketFactory()).build();

        } catch (Exception e) {
            logger.error(e);
            throw new InvalidArgumentException(e);
        }
    }

}