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 String[] supportedProtocols, final String[] supportedCipherSuites,
            final X509HostnameVerifier hostnameVerifier) 

Source Link

Usage

From source file:run.var.teamcity.cloud.docker.client.apcon.ApacheConnector.java

private HttpClientConnectionManager createConnectionManager(final Client client, final Configuration config,
        final SSLContext sslContext, final boolean useSystemProperties) {

    final String[] supportedProtocols = useSystemProperties ? split(System.getProperty("https.protocols"))
            : null;/*  www . j ava2s .  c om*/
    final String[] supportedCipherSuites = useSystemProperties ? split(System.getProperty("https.cipherSuites"))
            : null;

    HostnameVerifier hostnameVerifier = client.getHostnameVerifier();

    final LayeredConnectionSocketFactory sslSocketFactory;
    if (sslContext != null) {
        sslSocketFactory = new SSLConnectionSocketFactory(sslContext, supportedProtocols, supportedCipherSuites,
                hostnameVerifier);
    } else {
        if (useSystemProperties) {
            sslSocketFactory = new SSLConnectionSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault(),
                    supportedProtocols, supportedCipherSuites, hostnameVerifier);
        } else {
            sslSocketFactory = new SSLConnectionSocketFactory(
                    org.apache.http.conn.ssl.SSLContexts.createDefault(), hostnameVerifier);
        }
    }

    final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();

    final Integer chunkSize = ClientProperties.getValue(config.getProperties(),
            ClientProperties.CHUNKED_ENCODING_SIZE, ClientProperties.DEFAULT_CHUNK_SIZE, Integer.class);

    final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
            registry, new ConnectionFactory(chunkSize));

    if (useSystemProperties) {
        String s = System.getProperty("http.keepAlive", "true");
        if ("true".equalsIgnoreCase(s)) {
            s = System.getProperty("http.maxConnections", "5");
            final int max = Integer.parseInt(s);
            connectionManager.setDefaultMaxPerRoute(max);
            connectionManager.setMaxTotal(2 * max);
        }
    }

    return connectionManager;
}

From source file:com.cognitivemedicine.nifi.http.PostAdvancedHTTP.java

private Config getConfig(final String url, final ProcessContext context) {
    final String baseUrl = getBaseUrl(url);
    Config config = configMap.get(baseUrl);
    if (config != null) {
        return config;
    }/*from  www. j a v a 2 s.  c  om*/

    final PoolingHttpClientConnectionManager conMan;
    final SSLContextService sslContextService = context.getProperty(SSL_CONTEXT_SERVICE)
            .asControllerService(SSLContextService.class);
    if (sslContextService == null) {
        conMan = new PoolingHttpClientConnectionManager();
    } else {
        final SSLContext sslContext;
        try {
            sslContext = createSSLContext(sslContextService);
        } catch (final Exception e) {
            throw new ProcessException(e);
        }

        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                new String[] { "TLSv1" }, null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

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

        conMan = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    }

    conMan.setDefaultMaxPerRoute(context.getMaxConcurrentTasks());
    conMan.setMaxTotal(context.getMaxConcurrentTasks());
    config = new Config(conMan);
    final Config existingConfig = configMap.putIfAbsent(baseUrl, config);

    return (existingConfig == null) ? config : existingConfig;
}

From source file:com.hp.ov.sdk.rest.http.core.client.HttpRestClient.java

/**
 * Creates the HTTP client./*from w  ww . j  av  a  2 s. c  o m*/
 *
 * @param params
 *  connection parameters.
 * @return
 *  A HTTP client.
 */
private CloseableHttpClient buildHttpClient(RestParams params) {
    HttpClientBuilder clientBuilder = HttpClients.custom();

    // We dont need to set it the best available is used.
    // See SSLContext.init()
    TrustManager[] trustManagers = null;

    // If they want a different manager we need to use that.
    if (params.hasTrustManager()) {
        LOGGER.debug("Using user supplied trust manager: " + params.getTrustManager().getClass().getName());
        trustManagers = new TrustManager[] { params.getTrustManager() };
    }

    try {
        SSLContext sc = SSLContext.getInstance("TLSv1.2");
        sc.init(null, // Use the best available key manager
                trustManagers, // If null best available is used
                new java.security.SecureRandom());

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

        clientBuilder.setSSLSocketFactory(sslsf);

    } catch (NoSuchAlgorithmException ex) {
        LOGGER.error("Unable to set TrustManager", ex);
    } catch (KeyManagementException ex) {
        LOGGER.error("Unable to set TrustManager", ex);
    }

    // Use a different host verifier?
    if (params.hasHostnameVerifier()) {
        LOGGER.debug("Using user supplied host verifier: " + params.getHostnameVerifier().getClass().getName());
        clientBuilder.setSSLHostnameVerifier(params.getHostnameVerifier());
    }

    return clientBuilder.build();
}

From source file:org.gtri.fhir.api.vistaex.resource.impl.VistaExResourceImpl.java

/**
 * Creates and configures a {@link SSLConnectionSocketFactory} to use in the application
 * @return/*from  ww  w  .  ja  va 2s.c o  m*/
 */
private SSLConnectionSocketFactory createSSLConnectionSocketFactory() {
    File trustStore = getFileInClassPath("gtVistaExTrustStore");
    SSLContext sslcontext = null;
    SSLConnectionSocketFactory sslsf = null;
    try {
        //TODO: At some point configure to use trust store
        sslcontext = SSLContexts.custom()
                //.loadTrustMaterial(trustStore, "gtvistaex".toCharArray(),new TrustSelfSignedStrategy())
                .loadTrustMaterial(new TrustAllStrategy()).build();
        //TODO: Fix to use non-deprecated code
        // Allow TLSv1 protocol only
        sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return sslsf;
}

From source file:com.petalmd.armor.AbstractUnitTest.java

protected final HeaderAwareJestHttpClient getJestClient(final String serverUri, final String username,
        final String password) throws Exception {// http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html

    final CredentialsProvider credsProvider = new BasicCredentialsProvider();

    final HttpClientConfig clientConfig1 = new HttpClientConfig.Builder(serverUri).multiThreaded(true).build();

    // Construct a new Jest client according to configuration via factory
    final HeaderAwareJestClientFactory factory1 = new HeaderAwareJestClientFactory();

    factory1.setHttpClientConfig(clientConfig1);

    final HeaderAwareJestHttpClient c = factory1.getObject();

    final HttpClientBuilder hcb = HttpClients.custom();

    if (username != null) {
        credsProvider.setCredentials(new AuthScope(AuthScope.ANY),
                new UsernamePasswordCredentials(username, password));
    }/*  www. j  av a  2s . c o m*/

    if (useSpnego) {
        //SPNEGO/Kerberos setup
        log.debug("SPNEGO activated");
        final AuthSchemeProvider nsf = new SPNegoSchemeFactory(true, false);//  new NegotiateSchemeProvider();
        final Credentials jaasCreds = new JaasCredentials();
        credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.SPNEGO), jaasCreds);
        credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.NTLM),
                new NTCredentials("Guest", "Guest", "Guest", "Guest"));
        final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                .register(AuthSchemes.SPNEGO, nsf).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).build();

        hcb.setDefaultAuthSchemeRegistry(authSchemeRegistry);
    }

    hcb.setDefaultCredentialsProvider(credsProvider);

    if (serverUri.startsWith("https")) {
        log.debug("Configure Jest with SSL");

        final KeyStore myTrustStore = KeyStore.getInstance("JKS");
        myTrustStore.load(new FileInputStream(SecurityUtil.getAbsoluteFilePathFromClassPath("ArmorTS.jks")),
                "changeit".toCharArray());

        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(SecurityUtil.getAbsoluteFilePathFromClassPath("ArmorKS.jks")),
                "changeit".toCharArray());

        final SSLContext sslContext = SSLContexts.custom().useTLS()
                .loadKeyMaterial(keyStore, "changeit".toCharArray()).loadTrustMaterial(myTrustStore).build();

        String[] protocols = null;

        if (enableSSLv3Only) {
            protocols = new String[] { "SSLv3" };
        } else {
            protocols = SecurityUtil.ENABLED_SSL_PROTOCOLS;
        }

        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, protocols,
                SecurityUtil.ENABLED_SSL_CIPHERS, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        hcb.setSSLSocketFactory(sslsf);

    }

    hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build());

    final CloseableHttpClient httpClient = hcb.build();

    c.setHttpClient(httpClient);
    return c;

}

From source file:com.networknt.client.Client.java

private Registry<ConnectionSocketFactory> registry() throws ClientException {
    Registry<ConnectionSocketFactory> registry = null;
    try {//www. ja va 2  s.  c  om
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory(sslContext(),
                new String[] { "TLSv1" }, null, hostnameVerifier());
        // Create a registry of custom connection factory
        registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE).register("https", sslFactory).build();
    } catch (NoSuchAlgorithmException e) {
        logger.error("NoSuchAlgorithmException: in registry", e);
        throw new ClientException("NoSuchAlgorithmException: in registry", e);
    } catch (KeyManagementException e) {
        logger.error("KeyManagementException: in registry", e);
        throw new ClientException("KeyManagementException: in registry", e);
    } catch (IOException e) {
        logger.error("IOException: in registry", e);
        throw new ClientException("IOException: in registry", e);
    }
    return registry;
}

From source file:io.fabric8.elasticsearch.ElasticsearchIntegrationTest.java

protected final CloseableHttpClient getHttpClient() throws Exception {

    final HttpClientBuilder hcb = HttpClients.custom();

    if (enableHttpClientSSL) {

        log.debug("Configure HTTP client with SSL");

        final KeyStore myTrustStore = KeyStore.getInstance("JKS");
        myTrustStore.load(new FileInputStream(truststore), password.toCharArray());

        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(keystore), password.toCharArray());

        final SSLContextBuilder sslContextbBuilder = SSLContexts.custom().useTLS();

        if (trustHttpServerCertificate) {
            sslContextbBuilder.loadTrustMaterial(myTrustStore);
        }/*from  w ww. j a  v a 2 s.  c o m*/

        if (sendHttpClientCertificate) {
            sslContextbBuilder.loadKeyMaterial(keyStore, "changeit".toCharArray());
        }

        final SSLContext sslContext = sslContextbBuilder.build();

        String[] protocols = null;

        if (enableHttpClientSSLv3Only) {
            protocols = new String[] { "SSLv3" };
        } else {
            protocols = new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" };
        }

        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, protocols, null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        hcb.setSSLSocketFactory(sslsf);
    }

    hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build());

    return hcb.build();
}

From source file:com.sat.vcse.automation.utils.http.HttpClient.java

private CloseableHttpClient getClient() {
    CloseableHttpClient client = null;//from w  w  w.j a  va  2s.c  o  m

    if (this.isHttps) {
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(getSSLContext(),
                new String[] { this.cryptoProtocol }, this.cipherSuite, getHostnameVerifier());
        client = HttpClients.custom().setSSLSocketFactory(sslsf).build();

    } else {
        client = HttpClients.createDefault();
    }

    return client;

}

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

private CloseableHttpClient getHttpClientForSsl() {
    SSLContext sslContext = null;
    try {/*  ww  w  . j av  a2s .  com*/
        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();
}