Example usage for org.apache.http.impl.client HttpClientBuilder setSSLSocketFactory

List of usage examples for org.apache.http.impl.client HttpClientBuilder setSSLSocketFactory

Introduction

In this page you can find the example usage for org.apache.http.impl.client HttpClientBuilder setSSLSocketFactory.

Prototype

public final HttpClientBuilder setSSLSocketFactory(final LayeredConnectionSocketFactory sslSocketFactory) 

Source Link

Document

Assigns LayeredConnectionSocketFactory instance.

Usage

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

/**
 * Creates the HTTP client.//from w ww.  j a  va2 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.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);
            }/* w w  w  .  j a  v  a2s  .  c o  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.floragunn.searchguard.test.helper.rest.RestHelper.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(FileHelper.getAbsoluteFilePathFromClassPath(truststore)),
                "changeit".toCharArray());

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

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

        if (trustHTTPServerCertificate) {
            sslContextbBuilder.loadTrustMaterial(myTrustStore);
        }/*from w w w.  ja 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.floragunn.searchguard.ssl.AbstractUnitTest.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(getAbsoluteFilePathFromClassPath("truststore.jks")),
                "changeit".toCharArray());

        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(getAbsoluteFilePathFromClassPath("node-0-keystore.jks")),
                "changeit".toCharArray());

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

        if (trustHTTPServerCertificate) {
            sslContextbBuilder.loadTrustMaterial(myTrustStore);
        }/*ww  w . ja  v a  2  s .  co 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:org.apache.sling.discovery.etcd.EtcdDiscoveryService.java

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

    boolean hasKeyStore = !isEmpty(keystoreFilePath);

    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)
            .setConnectTimeout(connectionTimeout).setRedirectsEnabled(true).setStaleConnectionCheckEnabled(true)
            .build();/* w  w  w .j a v  a  2 s.co  m*/

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

    if (hasKeyStore) {

        final SSLContextBuilder sslContextBuilder = SSLContexts.custom();

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

            builder.setSSLSocketFactory(sslConnectionSocketFactory);

            connectionManager = new PoolingHttpClientConnectionManager(connectionSocketFactory);

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

    } else {
        connectionManager = new PoolingHttpClientConnectionManager();
    }

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

From source file:com.floragunn.searchguard.AbstractUnitTest.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(getAbsoluteFilePathFromClassPath("truststore.jks")),
                "changeit".toCharArray());

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

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

        if (trustHTTPServerCertificate) {
            sslContextbBuilder.loadTrustMaterial(myTrustStore);
        }//from   www  . j a v  a2  s  .co  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: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  w  w . ja  v  a 2s. c  om

        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.hpe.elderberry.TaxiiConnection.java

public RestTemplate getRestTemplate() {
    if (restTemplate == null) {
        HttpClientBuilder builder = custom();

        if (useProxy) {
            if ("".equals(proxyHost)) {
                proxyHost = System.getProperty(discoveryUrl.getScheme() + ".proxyHost");
            }/*  w  w  w. j  a  v a2 s  . c  om*/

            if (proxyPort == 0) {
                proxyPort = Integer.parseInt(System.getProperty(discoveryUrl.getScheme() + ".proxyPort", "0"));
            }

            if ("".equals(proxyHost) || proxyHost == null || proxyPort == 0) {
                log.warn("proxy requested, but not setup, not using a proxy");
            } else {
                log.info("using " + discoveryUrl.getScheme() + " proxy: " + proxyHost + ":" + proxyPort);
                HttpHost proxy = new HttpHost(proxyHost, proxyPort);
                DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
                builder.setRoutePlanner(routePlanner);
            }
        }

        if (getTrustStore() != null || getKeyStore() != null) {
            SSLContext sslContext;
            try {
                sslContext = SSLContexts.custom()
                        .loadTrustMaterial(getTrustStore(), new TrustSelfSignedStrategy())
                        .loadKeyMaterial(getKeyStore(), keyPassword).build();
            } catch (Exception e) {
                log.error("unable to create SSL context, " + e.getMessage(), e);
                throw new RuntimeException(e);
            }
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
            builder.setSSLSocketFactory(sslsf);
        }

        if (!"".equals(username)) {
            restTemplate = new RestTemplate(
                    new PreemptiveAuthHttpRequestFactor(username, password, builder.build()));
        } else {
            restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(builder.build()));
        }

        if (marshaller == null) {
            marshaller = new Jaxb2Marshaller();
            marshaller.setPackagesToScan("org.mitre");
            try {
                marshaller.afterPropertiesSet();
            } catch (Exception e) {
                log.error("unable to create Jaxb2 Marshaller: " + e.getMessage(), e);
                throw new RuntimeException(e);
            }
        }

        MarshallingHttpMessageConverter converter = new MarshallingHttpMessageConverter(marshaller);
        converter.setSupportedMediaTypes(singletonList(APPLICATION_XML));
        //noinspection unchecked
        restTemplate.setMessageConverters(Collections.<HttpMessageConverter<?>>singletonList(converter));
    }

    return restTemplate;
}

From source file:com.cisco.oss.foundation.http.apache.ApacheHttpClient.java

@Override
protected void configureClient() {

    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder.setConnectTimeout(metadata.getConnectTimeout());
    requestBuilder = requestBuilder.setSocketTimeout(metadata.getReadTimeout());
    requestBuilder = requestBuilder.setStaleConnectionCheckEnabled(metadata.isStaleConnectionCheckEnabled());

    RequestConfig requestConfig = requestBuilder.build();

    boolean addSslSupport = StringUtils.isNotEmpty(metadata.getKeyStorePath())
            && StringUtils.isNotEmpty(metadata.getKeyStorePassword());

    boolean addTrustSupport = StringUtils.isNotEmpty(metadata.getTrustStorePath())
            && StringUtils.isNotEmpty(metadata.getTrustStorePassword());

    autoCloseable = metadata.isAutoCloseable();

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    SSLContext sslContext = null;

    try {//from ww  w .  ja v a 2  s .  co  m

        String keystoreType = "JKS";
        if (addSslSupport && addTrustSupport) {

            KeyStore keyStore = KeyStore.getInstance(keystoreType);
            keyStore.load(new FileInputStream(metadata.getKeyStorePath()),
                    metadata.getKeyStorePassword().toCharArray());

            KeyStore trustStore = KeyStore.getInstance(keystoreType);
            trustStore.load(new FileInputStream(metadata.getTrustStorePath()),
                    metadata.getTrustStorePassword().toCharArray());

            sslContext = SSLContexts.custom().useProtocol("TLS")
                    .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray())
                    .loadTrustMaterial(trustStore, null).build();

        } else if (addSslSupport) {

            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());

            KeyStore keyStore = KeyStore.getInstance(keystoreType);
            keyStore.load(new FileInputStream(metadata.getKeyStorePath()),
                    metadata.getKeyStorePassword().toCharArray());

            tmf.init(keyStore);

            sslContext = SSLContexts.custom().useProtocol("SSL")
                    .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray()).build();

            sslContext.init(null, tmf.getTrustManagers(), null);

            SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);

            httpClientBuilder.setSSLSocketFactory(sf);

        } else if (addTrustSupport) {

            KeyStore trustStore = KeyStore.getInstance(keystoreType);
            trustStore.load(new FileInputStream(metadata.getTrustStorePath()),
                    metadata.getTrustStorePassword().toCharArray());

            sslContext = SSLContexts.custom().useProtocol("TLS").loadTrustMaterial(trustStore, null).build();

        }

        if (addSslSupport | addTrustSupport) {
            SSLContext.setDefault(sslContext);
            httpClientBuilder.setSslcontext(sslContext);
        }

    } catch (Exception e) {
        LOGGER.error("can't set TLS Support. Error is: {}", e, e);
    }

    httpClientBuilder.setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress())
            .setMaxConnTotal(metadata.getMaxConnectionsTotal()).setDefaultRequestConfig(requestConfig)
            .evictExpiredConnections().evictIdleConnections(metadata.getIdleTimeout(), TimeUnit.MILLISECONDS)
            .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout()));

    HttpAsyncClientBuilder httpAsyncClientBuilder = HttpAsyncClients.custom();

    httpAsyncClientBuilder.setDefaultRequestConfig(requestConfig)
            .setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress())
            .setMaxConnTotal(metadata.getMaxConnectionsTotal())
            .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout()))
            .setSSLContext(sslContext);

    if (metadata.isDisableCookies()) {
        httpClientBuilder.disableCookieManagement();
        httpAsyncClientBuilder.disableCookieManagement();
    }

    if (hostnameVerifier != null) {
        httpClientBuilder.setSSLHostnameVerifier(hostnameVerifier);
        httpAsyncClientBuilder.setSSLHostnameVerifier(hostnameVerifier);
    }

    if (!followRedirects) {
        httpClientBuilder.disableRedirectHandling();
    }

    httpClient = httpClientBuilder.build();

    httpAsyncClient = httpAsyncClientBuilder.build();

    httpAsyncClient.start();

}