Example usage for org.apache.http.conn.ssl SSLContexts custom

List of usage examples for org.apache.http.conn.ssl SSLContexts custom

Introduction

In this page you can find the example usage for org.apache.http.conn.ssl SSLContexts custom.

Prototype

public static SSLContextBuilder custom() 

Source Link

Document

Creates custom SSL context.

Usage

From source file:org.openscore.content.httpclient.build.conn.SSLConnectionSocketFactoryBuilderTest.java

@Test
public void buildWithTrustAllRoots() throws Exception {
    builder = new SSLConnectionSocketFactoryBuilder();
    builder.setTrustAllRoots("true");
    mockStatic(SSLContexts.class);

    when(SSLContexts.custom()).thenReturn(sslContextBuilderMock);

    when(sslContextBuilderMock.useTLS()).thenReturn(null);
    when(sslContextBuilderMock.useSSL()).thenReturn(null);
    when(sslContextBuilderMock.loadTrustMaterial(isA(KeyStore.class), isA(TrustStrategy.class)))
            .thenReturn(null);//from w  w w  .ja va 2 s  .co  m

    when(sslContextBuilderMock.build()).thenReturn(sslCtxMock);

    whenNew(SSLConnectionSocketFactory.class).withParameterTypes(SSLContext.class, X509HostnameVerifier.class)
            .withArguments(isA(SSLContext.class), isA(X509HostnameVerifier.class)).thenReturn(sslsfMock);

    SSLConnectionSocketFactory sslsf = builder.build();
    assertNotNull(sslsf);
    assertEquals(sslsfMock, sslsf);
}

From source file:net.ymate.platform.module.wechat.support.HttpClientHelper.java

private CloseableHttpClient __doBuildHttpClient() throws KeyManagementException, NoSuchAlgorithmException {
    HttpClientBuilder _builder = HttpClientBuilder.create()
            .setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(__connectionTimeout)
                    .setSocketTimeout(__connectionTimeout).setConnectionRequestTimeout(__connectionTimeout)
                    .build());//from w  ww.jav  a 2s .c o m
    if (__socketFactory == null) {
        __socketFactory = new SSLConnectionSocketFactory(SSLContexts.custom().useSSL().build(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    }
    return _builder.setSSLSocketFactory(__socketFactory).build();
}

From source file:net.shibboleth.idp.cas.authn.PkixProxyAuthenticator.java

/**
 * Creates a new instance.//  ww  w  .j  a  v a  2s  .  c  o  m
 *
 * @param x509TrustEngine X.509 trust engine used to validate the TLS certificate presented by the proxy
 *                        callback endpoint.
 */
public PkixProxyAuthenticator(@Nonnull TrustEngine<X509Credential> x509TrustEngine) {
    Constraint.isNotNull(x509TrustEngine, "Trust engine cannot be null");
    try {
        SSLContext sslContext = SSLContexts.custom().useTLS()
                .loadTrustMaterial(null, new TrustEngineTrustStrategy(x509TrustEngine)).build();
        socketFactory = new SSLConnectionSocketFactory(sslContext,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (Exception e) {
        throw new RuntimeException("SSL initialization error", e);
    }
}

From source file:majordodo.client.http.Client.java

private void createClient() {

    try {//  w  w  w  .  j a  v  a2  s. c o  m
        SSLContext sslContext;
        SSLConnectionSocketFactory sslsf;
        if (configuration.isDisableHttpsVerification()) {
            sslContext = SSLContext.getInstance("SSL");
            TrustManager mytm[] = { new MyTrustManager() };
            sslContext.init(null, mytm, null);
            sslsf = new SSLConnectionSocketFactory(sslContext,
                    SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        } else {
            sslContext = SSLContexts.custom().build();
            sslsf = new SSLConnectionSocketFactory(sslContext,
                    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        }

        Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", new PlainConnectionSocketFactory()).register("https", sslsf).build();

        poolManager = new PoolingHttpClientConnectionManager(r);

        if (configuration.getMaxConnTotal() > 0) {
            poolManager.setMaxTotal(configuration.getMaxConnTotal());
        }
        if (configuration.getMaxConnPerRoute() > 0) {
            poolManager.setDefaultMaxPerRoute(configuration.getMaxConnPerRoute());
        }

        poolManager.setDefaultSocketConfig(SocketConfig.custom().setSoKeepAlive(true).setSoReuseAddress(true)
                .setTcpNoDelay(false).setSoTimeout(configuration.getSotimeout()).build());

        ConnectionKeepAliveStrategy myStrategy = (HttpResponse response, HttpContext context) -> configuration
                .getKeepAlive();

        httpclient = HttpClients.custom().setConnectionManager(poolManager)
                .setConnectionReuseStrategy(DefaultConnectionReuseStrategy.INSTANCE)
                .setKeepAliveStrategy(myStrategy).build();
    } catch (NoSuchAlgorithmException | KeyManagementException ex) {
        throw new RuntimeException(ex);
    }

}

From source file:io.pivotal.strepsirrhini.chaoslemur.infrastructure.StandardDirectorUtils.java

private static String getBoshDirectorUaaToken(String host, String directorName, String password)
        throws GeneralSecurityException {

    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS()
            .build();// w w  w  . j a  v a2 s  .  c  o  m

    SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext,
            new AllowAllHostnameVerifier());

    HttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling()
            .setSSLSocketFactory(connectionFactory).build();
    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));

    MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
    String base64Passowrd = encodePassword(directorName, password);
    headers.add("Authorization", "Basic " + base64Passowrd);
    headers.add("Content-Type", "application/x-www-form-urlencoded");

    String postArgs = "grant_type=client_credentials";

    HttpEntity<String> requestEntity = new HttpEntity<String>(postArgs, headers);
    String uri = "https://" + host + ":8443/oauth/token";
    UaaToken response = restTemplate.postForObject(uri, requestEntity, UaaToken.class);

    log.info("Uaa token:" + response);
    return response.getAccess_token();
}

From source file:io.cloudslang.content.httpclient.build.conn.SSLConnectionSocketFactoryBuilderTest.java

@Test
public void buildWithTrustAllRoots() throws Exception {
    builder = new SSLConnectionSocketFactoryBuilder();
    builder.setTrustAllRoots("true");
    builder.setKeystore(System.getProperty("java.home") + "/lib/security/cacerts");
    builder.setKeystorePassword("changeit");
    mockStatic(SSLContexts.class);

    when(SSLContexts.custom()).thenReturn(sslContextBuilderMock);

    when(sslContextBuilderMock.useTLS()).thenReturn(null);
    when(sslContextBuilderMock.useSSL()).thenReturn(null);
    when(sslContextBuilderMock.loadTrustMaterial(isA(KeyStore.class), isA(TrustStrategy.class)))
            .thenReturn(null);/*from w  ww.j a  va2  s .  c  o  m*/

    when(sslContextBuilderMock.build()).thenReturn(sslCtxMock);

    prepareSSLConnectionSocketFactory();

    SSLConnectionSocketFactory sslsf = builder.build();
    assertNotNull(sslsf);
    assertEquals(sslsfMock, sslsf);
}

From source file:com.meltmedia.cadmium.cli.AbstractAuthorizedOnly.java

/**
 * Sets the Commons HttpComponents to accept all SSL Certificates.
 * /*from   w w  w. j a va 2  s .  c om*/
 * @throws Exception
 * @return An instance of HttpClient that will accept all.
 */
protected static HttpClient httpClient() throws Exception {
    return HttpClients.custom().setHostnameVerifier(new AllowAllHostnameVerifier())
            .setSslcontext(SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s)
                        throws CertificateException {
                    return true;
                }
            }).build()).build();
}

From source file:com.github.kpavlov.ssl.DynamicSSLSocketFactory.java

private SSLSocketFactory createSSLSocketFactory(String host) {
    try {/*from   w  ww. j  av  a  2  s  .c o  m*/
        final KeyStore keyStore = keyStoreProvider.getKeyStore(host);
        final KeyStore trustStore = keyStoreProvider.getTrustStore(host);
        final char[] keyPassword = keyPasswordProvider.getPassword(host);

        final SSLContextBuilder contextBuilder = SSLContexts.custom();
        if (keyStore != null) {
            contextBuilder.loadKeyMaterial(keyStore, keyPassword);
        }
        if (trustStore != null) {
            contextBuilder.loadTrustMaterial(trustStore);
        }

        SSLContext sslContext = contextBuilder.useTLS().build();

        return sslContext.getSocketFactory();
    } catch (Exception e) {
        LOGGER.error("Unable to create SSLContext", e);
    }

    return null;
}

From source file:com.spectralogic.ds3client.NetworkClientImpl.java

private static CloseableHttpClient createDefaultClient(final ConnectionDetails connectionDetails) {
    final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setDefaultMaxPerRoute(MAX_CONNECTION_PER_ROUTE);
    connectionManager.setMaxTotal(MAX_CONNECTION_TOTAL);

    if (connectionDetails.isHttps() && !connectionDetails.isCertificateVerification()) {
        try {//from  w  w w  . jav  a2 s  . co  m

            final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(final X509Certificate[] chain, final String authType)
                        throws CertificateException {
                    return true;
                }
            }).useTLS().build();

            final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                    new AllowAllHostnameVerifier());
            return HttpClients.custom().setConnectionManager(connectionManager).setSSLSocketFactory(sslsf)
                    .build();

        } catch (final NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
            throw new SSLSetupException(e);
        }
    } else {
        return HttpClients.custom().setConnectionManager(connectionManager).build();
    }
}

From source file:org.ops4j.pax.web.itest.base.client.HttpComponentsWrapper.java

private CloseableHttpClient createHttpClient() throws KeyStoreException, IOException, NoSuchAlgorithmException,
        CertificateException, KeyManagementException {
    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    SSLConnectionSocketFactory sslsf = null;
    try {// w  w  w . j  a v  a 2  s  .co  m
        FileInputStream instream = new FileInputStream(new File(keyStore));
        try {
            trustStore.load(instream, "password".toCharArray());
        } finally {
            // CHECKSTYLE:OFF
            try {
                instream.close();
            } catch (Exception ignore) {
            }
            // CHECKSTYLE:ON
        }

        SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore).build();
        sslsf = new SSLConnectionSocketFactory(sslContext, (X509HostnameVerifier) hostnameVerifier);
    } catch (FileNotFoundException e) {
        LOG.error("Error preparing SSL for testing. Https will not be available.", e);
    }

    PlainConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();

    RegistryBuilder<ConnectionSocketFactory> rb = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", plainsf);
    if (sslsf != null) {
        rb.register("https", sslsf);
    }

    Registry<ConnectionSocketFactory> registry = rb.build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);

    return HttpClients.custom().setConnectionManager(cm).build();

}