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

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

Introduction

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

Prototype

public SSLContextBuilder() 

Source Link

Usage

From source file:sample.jetty.ssl.SampleJettySslApplicationTests.java

@Test
public void testHome() throws Exception {
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
            new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());

    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();

    TestRestTemplate testRestTemplate = new TestRestTemplate();
    ((HttpComponentsClientHttpRequestFactory) testRestTemplate.getRequestFactory()).setHttpClient(httpClient);
    ResponseEntity<String> entity = testRestTemplate.getForEntity("https://localhost:" + this.port,
            String.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
    assertEquals("Hello World", entity.getBody());
}

From source file:org.wso2.mdm.qsg.utils.HTTPInvoker.java

private static HttpClient createHttpClient()
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    HttpClientBuilder b = HttpClientBuilder.create();

    // setup a Trust Strategy that allows all certificates.
    ////from w  w w . jav a 2 s.  c o m
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();
    b.setSSLContext(sslContext);
    //b.setSSLHostnameVerifier(new NoopHostnameVerifier());

    // don't check Hostnames, either.
    //      -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken
    HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    // here's the special part:
    //      -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
    //      -- and create a Registry, to register it.
    //
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();

    // now, we create connection-manager using our Registry.
    //      -- allows multi-threaded use
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    b.setConnectionManager(connMgr);

    // finally, build the HttpClient;
    //      -- done!
    CloseableHttpClient client = b.build();
    return client;
}

From source file:org.springframework.cloud.contract.wiremock.WireMockRestTemplateConfiguration.java

@Bean
@ConditionalOnClass(SSLContextBuilder.class)
public RestTemplateCustomizer restTemplateCustomizer() {
    return new RestTemplateCustomizer() {
        @Override/*from w w  w.  j  av  a2  s  .com*/
        public void customize(RestTemplate restTemplate) {
            HttpComponentsClientHttpRequestFactory factory = (HttpComponentsClientHttpRequestFactory) restTemplate
                    .getRequestFactory();
            factory.setHttpClient(createSslHttpClient());
        }

        private HttpClient createSslHttpClient() {
            try {
                SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
                        new SSLContextBuilder().loadTrustMaterial(null, TrustSelfSignedStrategy.INSTANCE)
                                .build(),
                        NoopHostnameVerifier.INSTANCE);
                return HttpClients.custom().setSSLSocketFactory(socketFactory).build();
            } catch (Exception ex) {
                throw new IllegalStateException("Unable to create SSL HttpClient", ex);
            }
        }
    };
}

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

private static HttpClient buildAllowallClient(RequestConfig requestConfig) {
    HttpConnectorList httpConnectorList = UriUtils.getHttpConnectorList();
    HttpClient httpClient = null;/* w  w  w .ja v  a2  s .co  m*/
    //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.camel.component.etcd.EtcdEndpoint.java

@Override
protected void doStart() throws Exception {
    if ((configuration.getTrustSelfsigned() == true) || (configuration.getCaFile() != null)
            || (configuration.getKeyFile() != null)) {
        // Need to create a custom httpclient since we need to change the SSL information.
        SSLContextBuilder builder = new SSLContextBuilder();
        if (configuration.getTrustSelfsigned() == true) {
            // Don't need to look at the CA file since we are going to trust anyhow.
            final TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
                @Override//from w  w  w  .  ja v a  2 s  .c o m
                public boolean isTrusted(X509Certificate[] certificate, String authType) {
                    return true;
                }
            };
            builder.loadTrustMaterial(acceptingTrustStrategy);
        } else {
            if (configuration.getCaFile() != null) {
                builder.loadTrustMaterial(new File(configuration.getCaFile()));
            }
        }
        // Now check if there are any private keys.
        if (configuration.getKeyFile() != null) {
            builder.loadKeyMaterial(new File(configuration.getKeyFile()), null, null);
        }
        //SSLSocketFactory socketfactory = SSLSocketFactory(builder.build());
        final CloseableHttpAsyncClient httpClient = HttpAsyncClients.custom().setSSLContext(builder.build())
                .build();
        etcdClient = new EtcdClient(configuration.makeURI());
    } else {
        etcdClient = new EtcdClient(configuration.makeURI());
    }
}

From source file:com.adobe.ags.curly.ConnectionManager.java

private void createNewConnectionManager() {
    try {//from  w  ww. j  a v  a2 s  .  com
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(new TrustSelfSignedStrategy());

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(),
                NoopHostnameVerifier.INSTANCE);
        Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", new PlainConnectionSocketFactory()).register("https", sslsf).build();
        connectionManager = new PoolingHttpClientConnectionManager(r);
        connectionManager.setValidateAfterInactivity(500);
        sharedContext = ThreadLocal.withInitial(HttpClientContext::new);
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
        Logger.getLogger(ConnectionManager.class.getName()).log(Level.SEVERE, null, ex);
    }

}

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

/**
 * Adds the ability to trust self signed certificates for this HttpClientBuilder
 * //from   w  w  w. ja  v  a2s  . 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.springframework.http.server.reactive.ServerHttpsRequestIntegrationTests.java

@Before
public void setup() throws Exception {
    this.server.setHandler(new CheckRequestHandler());
    this.server.afterPropertiesSet();
    this.server.start();

    // Set dynamically chosen port
    this.port = this.server.getPort();

    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(builder.build(),
            NoopHostnameVerifier.INSTANCE);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
            httpclient);/*from www .  ja  va2s .  com*/
    this.restTemplate = new RestTemplate(requestFactory);
}

From source file:io.openvidu.test.e2e.utils.CustomHttpClient.java

public CustomHttpClient(String openviduUrl, String openviduSecret) {
    this.openviduUrl = openviduUrl.replaceFirst("/*$", "");
    this.headerAuth = "Basic "
            + Base64.getEncoder().encodeToString(("OPENVIDUAPP:" + openviduSecret).getBytes());

    SSLContext sslContext = null;
    try {/*w w  w. ja va  2  s  . co m*/
        sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy() {
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        }).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        Assert.fail("Error building custom HttpClient: " + e.getMessage());
    }
    HttpClient unsafeHttpClient = HttpClients.custom().setSSLContext(sslContext)
            .setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
    Unirest.setHttpClient(unsafeHttpClient);
}

From source file:com.questdb.test.tools.HttpTestUtils.java

private static HttpClientBuilder createHttpClient_AcceptsUntrustedCerts() throws Exception {
    HttpClientBuilder b = HttpClientBuilder.create();

    // setup a Trust Strategy that allows all certificates.
    ////  w  w  w. ja  v  a  2 s.c o m
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();

    b.setSSLContext(sslContext);

    // here's the special part:
    //      -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
    //      -- and create a Registry, to register it.
    //
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
            new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();

    // now, we create connection-manager using our Registry.
    //      -- allows multi-threaded use
    b.setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryRegistry));

    return b;
}