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 SSLContext sslContext) 

Source Link

Usage

From source file:de.codecentric.boot.admin.zuul.filters.route.SimpleHostRoutingFilter.java

protected PoolingHttpClientConnectionManager newConnectionManager() {
    try {//from w  ww . ja  v  a  2 s  .  com
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                    throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
                    throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } }, new SecureRandom());

        RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder
                .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE);
        if (this.sslHostnameValidationEnabled) {
            registryBuilder.register("https", new SSLConnectionSocketFactory(sslContext));
        } else {
            registryBuilder.register("https",
                    new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE));
        }
        final Registry<ConnectionSocketFactory> registry = registryBuilder.build();

        this.connectionManager = new PoolingHttpClientConnectionManager(registry);
        this.connectionManager.setMaxTotal(this.hostProperties.getMaxTotalConnections());
        this.connectionManager.setDefaultMaxPerRoute(this.hostProperties.getMaxPerRouteConnections());
        return this.connectionManager;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:eu.europa.esig.dss.client.http.commons.CommonsDataLoader.java

private RegistryBuilder<ConnectionSocketFactory> setConnectionManagerSchemeHttps(
        RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistryBuilder) throws DSSException {
    try {//from   w  ww .j a va2s  . c  om

        SSLContext sslContext = null;
        if (StringUtils.isEmpty(sslKeystorePath)) {
            LOG.debug("Use default SSL configuration");
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() },
                    new SecureRandom());
            SSLContext.setDefault(sslContext);
        } else {
            LOG.debug("Use specific SSL configuration with keystore");
            FileInputStream fis = new FileInputStream(new File(sslKeystorePath));
            KeyStore keystore = KeyStore.getInstance(sslKeystoreType);
            keystore.load(fis, sslKeystorePassword.toCharArray());
            IOUtils.closeQuietly(fis);
            sslContext = SSLContexts.custom().loadTrustMaterial(keystore).useTLS().build();
        }

        final SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                sslContext);
        return socketFactoryRegistryBuilder.register("https", sslConnectionSocketFactory);
    } catch (Exception e) {
        throw new DSSException(e);
    }
}

From source file:cn.org.once.cstack.utils.JSONClient.java

private static Registry<ConnectionSocketFactory> getSslFactoryRegistry(String certPath) throws IOException {
    try {//from   w w  w  .j  a  va 2s .  c  o m
        KeyStore keyStore = KeyStoreUtils.createDockerKeyStore(certPath);

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

        SSLConnectionSocketFactory sslsf =

                new SSLConnectionSocketFactory(sslContext);
        return RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslsf).build();
    } catch (GeneralSecurityException e) {
        throw new IOException(e);
    }
}

From source file:org.wso2.apiManager.plugin.client.APIManagerClient.java

/**
 * Method to initialize the http client. We use only one instance of http client since there can not be concurrent
 * invocations/*  w  w  w.  ja v  a2s  .com*/
 *
 * @return @link{HttpClient} httpClient instance
 */
private HttpClient getHttpClient() {
    if (httpClient == null) {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                    builder.build());
            httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
        } catch (NoSuchAlgorithmException e) {
            SoapUI.logError(e, "Unable to load the trust store");
        } catch (KeyStoreException e) {
            SoapUI.logError(e, "Unable to get the key store instance");
        } catch (KeyManagementException e) {
            SoapUI.logError(e, "Unable to load trust store material");
        }
    }
    return httpClient;
}

From source file:com.esri.geoevent.test.performance.provision.GeoEventProvisioner.java

private SSLConnectionSocketFactory getSSLSocketFactory() {
    KeyStore trustStore;/*from w  w  w  .  j a v  a  2 s  .  com*/
    try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        TrustStrategy trustStrategy = new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }

        };

        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.loadTrustMaterial(trustStore, trustStrategy);
        sslContextBuilder.useTLS();
        SSLContext sslContext = sslContextBuilder.build();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);
        return sslSocketFactory;
    } catch (GeneralSecurityException | IOException e) {
        System.err.println("SSL Error : " + e.getMessage());
    }
    return null;
}

From source file:fr.treeptik.cloudunit.docker.JSONClient.java

private static Registry<ConnectionSocketFactory> getSslFactoryRegistry(String certPath) throws IOException {
    try {/*  w w  w  . j a v a  2s . c om*/
        KeyStore keyStore = KeyStoreUtils.createDockerKeyStore(certPath);

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

        SSLConnectionSocketFactory sslsf =

                new SSLConnectionSocketFactory(sslContext);
        return RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslsf).build();
    } catch (GeneralSecurityException e) {
        // this isn't ideal but the net effect is the same
        throw new IOException(e);
    }
}

From source file:org.piwigo.remotesync.api.client.WSClient.java

protected CloseableHttpClient getHttpClient() throws Exception {
    if (httpClient == null) {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

        if (clientConfiguration.getUsesProxy()) {
            String proxyUrl = clientConfiguration.getProxyUrl();
            int proxyPort = clientConfiguration.getProxyPort();

            String proxyUsername = clientConfiguration.getProxyUsername();
            String proxyPassword = clientConfiguration.getProxyPassword();

            if (proxyUsername != null && proxyUsername.length() > 0 && proxyPassword != null
                    && proxyPassword.length() > 0) {
                CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(new AuthScope(proxyUrl, proxyPort),
                        new UsernamePasswordCredentials(proxyUsername, proxyPassword));
                httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }/*www .jav a  2s .co  m*/

            HttpHost proxy = new HttpHost(proxyUrl, proxyPort);
            requestConfig = RequestConfig.custom().setProxy(proxy).build();
        }

        if (clientConfiguration.getTrustSSLCertificates()) {
            SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
            sslContextBuilder.loadTrustMaterial(null, new TrustSSLCertificatesStrategy());
            httpClientBuilder.setSSLSocketFactory(new SSLConnectionSocketFactory(sslContextBuilder.build()));
        }

        httpClient = httpClientBuilder.build();
    }

    return httpClient;
}

From source file:com.jive.myco.seyren.core.util.graphite.GraphiteHttpClient.java

private HttpClientConnectionManager createConnectionManager() {
    PoolingHttpClientConnectionManager manager;
    if ("https".equals(graphiteScheme) && !StringUtils.isEmpty(graphiteKeyStore)
            && !StringUtils.isEmpty(graphiteKeyStorePassword) && !StringUtils.isEmpty(graphiteTrustStore)) {
        try {//from  w  w  w .  j a va 2  s .c  o  m
            KeyStore keyStore = loadKeyStore(graphiteKeyStore, graphiteKeyStorePassword);
            KeyStore trustStore = loadKeyStore(graphiteTrustStore, null);

            KeyManagerFactory keyManagerFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, graphiteKeyStorePassword.toCharArray());
            KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

            TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(trustStore);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(keyManagers, trustManagers, null);

            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);

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

            manager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        } catch (Exception e) {
            LOGGER.warn("A problem occurred when building SSLConnectionSocketFactory", e);
            throw new RuntimeException("Error while building SSLConnectionSocketFactory", e);
        }
    } else {
        manager = new PoolingHttpClientConnectionManager();
    }

    manager.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE);
    return manager;
}

From source file:edu.washington.shibboleth.attribute.resolver.dc.rws.HttpDataSource.java

/**
 * Generate a socket factory using supplied key and trust stores 
 *///  w  w w  . ja va 2s .c om
protected SSLConnectionSocketFactory getSocketFactory() throws IOException {
    TrustManager[] trustManagers = null;
    KeyManager[] keyManagers = null;

    try {
        /* trust managers */
        if (caCertificateFile != null) {
            KeyStore trustStore;
            int cn = 0;

            log.info("Setting x509 trust from " + caCertificateFile);

            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            FileInputStream in = new FileInputStream(caCertificateFile);
            Collection certs = cf.generateCertificates(in);

            trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);

            Iterator cit = certs.iterator();
            while (cit.hasNext()) {
                X509Certificate cert = (X509Certificate) cit.next();
                log.info(" adding " + cert.getSubjectX500Principal().toString());
                System.out.println(" adding " + cert.getSubjectX500Principal().toString());
                trustStore.setCertificateEntry("CACERT" + cn, cert);
                cn += 1;
            }
            tmf.init(trustStore);
            trustManagers = tmf.getTrustManagers();
        } else { // no verification
            trustManagers = new TrustManager[] { new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    return;
                }

                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    return;
                }
            } };
        }

        /* key manager */
        if (certificateFile != null && keyFile != null) {
            KeyStore keyStore;
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null, null);

            FileInputStream in = new FileInputStream(certificateFile);
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
            PKCS1 pkcs = new PKCS1();
            log.info("reading key file: " + keyFile);
            PrivateKey key = pkcs.readKey(keyFile);

            X509Certificate[] chain = new X509Certificate[1];
            chain[0] = cert;
            keyStore.setKeyEntry("CERT", (Key) key, "pw".toCharArray(), chain);
            kmf.init(keyStore, "pw".toCharArray());
            keyManagers = kmf.getKeyManagers();
        }

        /* socket factory */

        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(keyManagers, trustManagers, null);
        return new SSLConnectionSocketFactory(ctx);

    } catch (IOException e) {
        log.error("error reading cert or key error: " + e);
    } catch (KeyStoreException e) {
        log.error("keystore error: " + e);
    } catch (NoSuchAlgorithmException e) {
        log.error("sf error: " + e);
    } catch (KeyManagementException e) {
        log.error("sf error: " + e);
    } catch (CertificateException e) {
        log.error("sf error: " + e);
    } catch (UnrecoverableKeyException e) {
        log.error("sf error: " + e);
    }

    return null;

}