Example usage for org.apache.http.ssl SSLContextBuilder build

List of usage examples for org.apache.http.ssl SSLContextBuilder build

Introduction

In this page you can find the example usage for org.apache.http.ssl SSLContextBuilder build.

Prototype

public SSLContext build() throws NoSuchAlgorithmException, KeyManagementException 

Source Link

Usage

From source file:se.curity.examples.http.UnsafeHttpClientSupplier.java

private static HttpClient create() {
    try {//w w  w.jav  a 2  s  .c o m
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(builder.build(),
                NoopHostnameVerifier.INSTANCE);
        return HttpClients.custom().disableAuthCaching().disableAutomaticRetries().disableRedirectHandling()
                .setSSLSocketFactory(sslSocketFactory).build();
    } catch (Exception e) {
        _logger.error("Unable to create Unsafe HTTP client supplier", e);
        throw new RuntimeException("Unable to initialize httpClient", e);
    }
}

From source file:org.mobicents.servlet.restcomm.http.CustomHttpClientBuilder.java

private static HttpClient buildAllowallClient(RequestConfig requestConfig) {
    HttpConnectorList httpConnectorList = UriUtils.getHttpConnectorList();
    HttpClient httpClient = null;//from w ww. j  a  v  a2  s  .c  om
    //Enable SSL only if we have HTTPS connector
    List<HttpConnector> connectors = httpConnectorList.getConnectors();
    Iterator<HttpConnector> iterator = connectors.iterator();
    while (iterator.hasNext()) {
        HttpConnector connector = iterator.next();
        if (connector.isSecure()) {
            SSLConnectionSocketFactory sslsf;
            try {
                SSLContextBuilder builder = new SSLContextBuilder();
                builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
                sslsf = new SSLConnectionSocketFactory(builder.build());
                httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig)
                        .setSSLSocketFactory(sslsf).build();
            } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
                throw new RuntimeException("Error creating HttpClient", e);
            }
            break;
        }
    }
    if (httpClient == null) {
        httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
    }

    return httpClient;
}

From source file:org.apache.metron.elasticsearch.client.ElasticsearchClientFactory.java

/**
 * <p>Setup connection encryption details (SSL) if applicable.
 * If ssl.enabled=true, sets up SSL connection. If enabled, keystore.path is required. User can
 * also optionally set keystore.password and keystore.type.
 * https://www.elastic.co/guide/en/elasticsearch/client/java-rest/5.6/_encrypted_communication.html
 * <p>/* w  ww.  j a  va  2s.co  m*/
 * <p>Other guidance on the HTTP Component library and configuring SSL connections.
 * http://www.robinhowlett.com/blog/2016/01/05/everything-you-ever-wanted-to-know-about-ssl-but-were-afraid-to-ask.
 * <p>
 * <p>JSSE docs - https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html
 * <p>
 * <p>Additional guidance for configuring Elasticsearch for SSL can be found here - https://www.elastic.co/guide/en/x-pack/5.6/ssl-tls.html
 */
private static SSLContext getSSLContext(ElasticsearchClientConfig esClientConfig) {
    if (esClientConfig.isSSLEnabled()) {
        LOG.info("Configuring client for SSL connection.");
        if (!esClientConfig.getKeyStorePath().isPresent()) {
            throw new IllegalStateException("KeyStore path must be provided for SSL connection.");
        }
        Optional<String> optKeyStorePass = esClientConfig.getKeyStorePassword();
        char[] keyStorePass = optKeyStorePass.map(String::toCharArray).orElse(null);
        KeyStore trustStore = getStore(esClientConfig.getKeyStoreType(), esClientConfig.getKeyStorePath().get(),
                keyStorePass);
        try {
            SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null);
            return sslBuilder.build();
        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
            throw new IllegalStateException("Unable to load truststore.", e);
        }
    }
    return null;
}

From source file:org.thingsboard.server.msa.AbstractContainerTest.java

private static HttpComponentsClientHttpRequestFactory getRequestFactoryForSelfSignedCert() throws Exception {
    SSLContextBuilder builder = SSLContexts.custom();
    builder.loadTrustMaterial(null, (TrustStrategy) (chain, authType) -> true);
    SSLContext sslContext = builder.build();
    SSLConnectionSocketFactory sslSelfSigned = new SSLConnectionSocketFactory(sslContext,
            new X509HostnameVerifier() {
                @Override//ww w. j a  v a 2 s .com
                public void verify(String host, SSLSocket ssl) {
                }

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

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

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

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

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
    return new HttpComponentsClientHttpRequestFactory(httpClient);
}

From source file:com.threatconnect.app.playbooks.db.tcapi.ConnectionUtil.java

/**
 * Adds the ability to trust self signed certificates for this HttpClientBuilder
 * //from   ww  w .j a  v a 2  s  . c  o  m
 * @param httpClientBuilder
 * the HttpClientBuilder to apply these settings to
 */
public static void trustSelfSignedCerts(final HttpClientBuilder httpClientBuilder) {
    logger.debug("Trusting self-signed certs.");
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(),
                new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        // allow all
                        return true;
                    }
                });

        httpClientBuilder.setSSLSocketFactory(sslsf);
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
        logger.error("Error adding SSLSocketFactory to HttpClientBuilder", ex);
    }
}

From source file:org.ensembl.gti.seqstore.database.cramstore.EnaCramSubmitter.java

protected static HttpClient getHttpsClient() {
    try {/*from  w  w w. j  a v  a 2  s.c  o  m*/
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
        return HttpClients.custom().setSSLSocketFactory(sslsf).build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.threatconnect.sdk.conn.ConnectionUtil.java

/**
 * Adds the ability to trust self signed certificates for this HttpClientBuilder
 * //from  w  ww.  j  ava 2s .  c om
 * @param httpClientBuilder
 * the HttpClientBuilder to apply these settings to
 */
public static void trustSelfSignedCerts(final HttpClientBuilder httpClientBuilder) {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(),
                new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        // allow all
                        return true;
                    }
                });

        httpClientBuilder.setSSLSocketFactory(sslsf);
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
        logger.error("Error adding SSLSocketFactory to HttpClientBuilder", ex);
    }
}

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

public static void setTrustManagers(TrustManager[] trustManagers) throws Exception {

    SSLContextBuilder sslContextBuilder = SSLContexts.custom();

    SSLContext sslContext = sslContextBuilder.build();

    sslContext.init(null, trustManagers, new SecureRandom());

    _defaultSSLSocketFactory = new SSLConnectionSocketFactory(sslContext,
            SSLConnectionSocketFactory.getDefaultHostnameVerifier());
}

From source file:org.apache.gobblin.service.modules.orchestration.AzkabanAjaxAPIClient.java

private static CloseableHttpClient getHttpClient() throws IOException {
    try {/*from   w w w .ja  v  a 2 s .  c o  m*/
        // Self sign SSL
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, (TrustStrategy) new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());

        // Create client
        return HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultCookieStore(new BasicCookieStore())
                .build();
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        throw new IOException("Issue with creating http client", e);
    }
}

From source file:org.eclipse.rdf4j.http.client.util.HttpClientBuilders.java

/**
 * Return an {@link HttpClientBuilder} that can be used to build an {@link HttpClient} which trusts all
 * certificates (particularly including self-signed certificates).
 * /*from   w  w  w  .j ava2s  . c om*/
 * @return a {@link HttpClientBuilder} for <i>SSL trust all</i>
 */
public static HttpClientBuilder getSSLTrustAllHttpClientBuilder() {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustStrategy() {

            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        });

        HostnameVerifier hostNameVerifier = new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        SSLConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(builder.build(), hostNameVerifier);

        return HttpClients.custom().setSSLSocketFactory(sslSF).useSystemProperties();
    } catch (Exception e) {
        // key management exception, etc.
        throw new RuntimeException(e);
    }
}