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: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  ww. j a v a  2 s  .c  o 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:org.springframework.boot.web.servlet.server.AbstractServletWebServerFactoryTests.java

@Test
public void sslWantsClientAuthenticationSucceedsWithoutClientCertificate() throws Exception {
    AbstractServletWebServerFactory factory = getFactory();
    addTestTxtFile(factory);//from ww w  .j a v  a2s.c o m
    factory.setSsl(getSsl(ClientAuth.WANT, "password", "classpath:test.jks"));
    this.webServer = factory.getWebServer();
    this.webServer.start();
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
            new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());
    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
            httpClient);
    assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)).isEqualTo("test");
}

From source file:org.apache.zeppelin.livy.BaseLivyInterpreter.java

private RestTemplate createRestTemplate() {
    String keytabLocation = getProperty("zeppelin.livy.keytab");
    String principal = getProperty("zeppelin.livy.principal");
    boolean isSpnegoEnabled = StringUtils.isNotEmpty(keytabLocation) && StringUtils.isNotEmpty(principal);

    HttpClient httpClient = null;/*from  w w w  . ja  v a  2 s.co  m*/
    if (livyURL.startsWith("https:")) {
        String keystoreFile = getProperty("zeppelin.livy.ssl.trustStore");
        String password = getProperty("zeppelin.livy.ssl.trustStorePassword");
        if (StringUtils.isBlank(keystoreFile)) {
            throw new RuntimeException("No zeppelin.livy.ssl.trustStore specified for livy ssl");
        }
        if (StringUtils.isBlank(password)) {
            throw new RuntimeException("No zeppelin.livy.ssl.trustStorePassword specified " + "for livy ssl");
        }
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(keystoreFile);
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(new FileInputStream(keystoreFile), password.toCharArray());
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore).build();
            SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
            HttpClientBuilder httpClientBuilder = HttpClients.custom().setSSLSocketFactory(csf);
            RequestConfig reqConfig = new RequestConfig() {
                @Override
                public boolean isAuthenticationEnabled() {
                    return true;
                }
            };
            httpClientBuilder.setDefaultRequestConfig(reqConfig);
            Credentials credentials = new Credentials() {
                @Override
                public String getPassword() {
                    return null;
                }

                @Override
                public Principal getUserPrincipal() {
                    return null;
                }
            };
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(AuthScope.ANY, credentials);
            httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
            if (isSpnegoEnabled) {
                Registry<AuthSchemeProvider> authSchemeProviderRegistry = RegistryBuilder
                        .<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
                        .build();
                httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeProviderRegistry);
            }

            httpClient = httpClientBuilder.build();
        } catch (Exception e) {
            throw new RuntimeException("Failed to create SSL HttpClient", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    LOGGER.error("Failed to close keystore file", e);
                }
            }
        }
    }

    RestTemplate restTemplate = null;
    if (isSpnegoEnabled) {
        if (httpClient == null) {
            restTemplate = new KerberosRestTemplate(keytabLocation, principal);
        } else {
            restTemplate = new KerberosRestTemplate(keytabLocation, principal, httpClient);
        }
    } else {
        if (httpClient == null) {
            restTemplate = new RestTemplate();
        } else {
            restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
        }
    }
    restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
    return restTemplate;
}

From source file:org.springframework.boot.web.servlet.server.AbstractServletWebServerFactoryTests.java

@Test
public void sslWithCustomSslStoreProvider() throws Exception {
    AbstractServletWebServerFactory factory = getFactory();
    addTestTxtFile(factory);//w  w  w.  j  a v  a 2 s. co  m
    Ssl ssl = new Ssl();
    ssl.setClientAuth(ClientAuth.NEED);
    ssl.setKeyPassword("password");
    factory.setSsl(ssl);
    SslStoreProvider sslStoreProvider = mock(SslStoreProvider.class);
    given(sslStoreProvider.getKeyStore()).willReturn(loadStore());
    given(sslStoreProvider.getTrustStore()).willReturn(loadStore());
    factory.setSslStoreProvider(sslStoreProvider);
    this.webServer = factory.getWebServer();
    this.webServer.start();
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(new FileInputStream(new File("src/test/resources/test.jks")), "secret".toCharArray());
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
            new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy())
                    .loadKeyMaterial(keyStore, "password".toCharArray()).build());
    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
            httpClient);
    assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)).isEqualTo("test");
    verify(sslStoreProvider).getKeyStore();
    verify(sslStoreProvider).getTrustStore();
}

From source file:org.springframework.boot.web.servlet.server.AbstractServletWebServerFactoryTests.java

protected void testRestrictedSSLProtocolsAndCipherSuites(String[] protocols, String[] ciphers)
        throws Exception {
    AbstractServletWebServerFactory factory = getFactory();
    factory.setSsl(getSsl(null, "password", "src/test/resources/test.jks", null, protocols, ciphers));
    this.webServer = factory
            .getWebServer(new ServletRegistrationBean<>(new ExampleServlet(true, false), "/hello"));
    this.webServer.start();

    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
            new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());

    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
            httpClient);//from  ww w. j a v  a2s .  com

    assertThat(getResponse(getLocalUrl("https", "/hello"), requestFactory)).contains("scheme=https");
}

From source file:org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfigurationTests.java

private void assertContent(String scheme, String url, int port, Object expected) throws Exception {

    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
            new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());
    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
            httpClient);// w  w  w  . ja v a2s .c om
    ClientHttpRequest request = requestFactory.createRequest(new URI(scheme + "://localhost:" + port + url),
            HttpMethod.GET);
    try {
        ClientHttpResponse response = request.execute();
        if (HttpStatus.NOT_FOUND.equals(response.getStatusCode())) {
            throw new FileNotFoundException();
        }
        try {
            String actual = StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8"));
            if (expected instanceof Matcher) {
                assertThat(actual).is(Matched.by((Matcher<?>) expected));
            } else {
                assertThat(actual).isEqualTo(expected);
            }
        } finally {
            response.close();
        }
    } catch (Exception ex) {
        if (expected == null) {
            if (SocketException.class.isInstance(ex) || FileNotFoundException.class.isInstance(ex)) {
                return;
            }
        }
        throw ex;
    }
}

From source file:com.rockagen.commons.http.HttpConn.java

/**
 * Handler main/*from w w w .j  a  va  2 s.  com*/
 *
 * @param targetHost target {@link HttpHost}
 * @param proxyHost proxy {@link HttpHost}
 * @param httpRequestMethod HttpGet or HttpPost...
 * @param encoding encoding
 * @param upc {@link UsernamePasswordCredentials}
 * @param keystore keystore stream
 * @param password keystore password
 * @return result String
 * @throws IOException  if an I/O error occurs
 */
protected static String execute(HttpHost targetHost, HttpHost proxyHost, HttpRequest httpRequestMethod,
        String encoding, UsernamePasswordCredentials upc, InputStream keystore, char[] password)
        throws IOException {

    HttpClientBuilder hcb = HttpClients.custom();
    hcb.setDefaultRequestConfig(getRequestConfig());
    if (proxyHost != null) {
        hcb.setProxy(proxyHost);
    }
    if (keystore != null) {

        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(keystore, password);
            SSLContext sslcontext = SSLContexts.custom()
                    .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
            SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(sslcontext);
            hcb.setSSLSocketFactory(ssf);
        } catch (KeyStoreException e) {
            log.error("{}", e.getMessage(), e);
        } catch (CertificateException e) {
            log.error("{}", e.getMessage(), e);
        } catch (NoSuchAlgorithmException e) {
            log.error("{}", e.getMessage(), e);
        } catch (KeyManagementException e) {
            log.error("{}", e.getMessage(), e);
        } finally {
            keystore.close();
        }

    }

    if (upc != null) {
        CredentialsProvider cp = new BasicCredentialsProvider();

        AuthScope as = new AuthScope(targetHost);

        cp.setCredentials(as, upc);
        hcb.setDefaultCredentialsProvider(cp);
    }

    CloseableHttpClient chc = hcb.build();
    try {
        CloseableHttpResponse response = chc.execute(targetHost, httpRequestMethod);
        return getResponse(response, encoding);
    } finally {
        chc.close();
    }

}

From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java

private void setUpSSL() throws InvalidArgumentException {

    if (cryptoPrimitives == null) {
        try {/* w w  w.  jav  a  2s.c  o  m*/
            cryptoPrimitives = new CryptoPrimitives();
            cryptoPrimitives.init();
        } catch (Exception e) {
            throw new InvalidArgumentException(e);
        }
    }

    if (isSSL && null == registry) {
        if (!properties.containsKey("pemBytes") && !properties.containsKey("pemFile")) {

            logger.warn("SSL with no CA certficates in either pemBytes or pemFile");

        }
        try {

            if (properties.containsKey("pemBytes")) {
                byte[] permbytes = (byte[]) properties.get("pemBytes");

                try (BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(permbytes))) {
                    cryptoPrimitives.addCACertificatesToTrustStore(bis);
                }

            }

            if (properties.containsKey("pemFile")) {
                String pemFile = properties.getProperty("pemFile");
                if (pemFile != null) {
                    String[] pems = pemFile.split("[ \t]*,[ \t]*");

                    for (String pem : pems) {
                        if (null != pem && !pem.isEmpty()) {
                            try {
                                try (BufferedInputStream bis = new BufferedInputStream(
                                        new ByteArrayInputStream(Files.readAllBytes(Paths.get(pem))))) {
                                    cryptoPrimitives.addCACertificatesToTrustStore(bis);
                                }
                            } catch (IOException e) {
                                throw new InvalidArgumentException(
                                        format("Unable to add CA certificate, can't open certificate file %s",
                                                new File(pem).getAbsolutePath()));
                            }
                        }
                    }
                }
            }

            SSLContext sslContext = SSLContexts.custom()
                    .loadTrustMaterial(cryptoPrimitives.getTrustStore(), null).build();

            ConnectionSocketFactory sf;
            if (null != properties && "true".equals(properties.getProperty("allowAllHostNames"))) {
                AllHostsSSLSocketFactory msf = new AllHostsSSLSocketFactory(cryptoPrimitives.getTrustStore());
                msf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                sf = msf;
            } else {
                sf = new SSLConnectionSocketFactory(sslContext);
            }

            registry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sf)
                    .register("http", new PlainConnectionSocketFactory()).build();

        } catch (Exception e) {
            logger.error(e);
            throw new InvalidArgumentException(e);
        }
    }

}

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

/**
 * Create a {@link CloseableHttpClient} used to communicate with Azkaban server.
 * Derived class can configure different http client by overriding this method.
 *
 * @return A closeable http client./*from w  w  w  .  j a v  a  2s. co m*/
 */
protected CloseableHttpClient getClient() throws AzkabanClientException {
    try {
        // SSLSocketFactory using custom TrustStrategy that ignores warnings about untrusted certificates
        // Self sign SSL
        SSLContextBuilder sslcb = new SSLContextBuilder();
        sslcb.loadTrustMaterial(null, (TrustStrategy) new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcb.build());

        HttpClientBuilder builder = HttpClientBuilder.create();
        RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(10000)
                .setConnectTimeout(10000).setConnectionRequestTimeout(10000).build();

        builder.disableCookieManagement().useSystemProperties().setDefaultRequestConfig(requestConfig)
                .setConnectionManager(new BasicHttpClientConnectionManager()).setSSLSocketFactory(sslsf);

        return builder.build();
    } catch (Exception e) {
        throw new AzkabanClientException("HttpClient cannot be created", e);
    }
}

From source file:org.apache.hive.jdbc.HiveConnection.java

SSLConnectionSocketFactory getTwoWaySSLSocketFactory() throws SQLException {
    SSLConnectionSocketFactory socketFactory = null;

    try {/*  w  w w.j a  v a2  s. co m*/
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
                JdbcConnectionParams.SUNX509_ALGORITHM_STRING, JdbcConnectionParams.SUNJSSE_ALGORITHM_STRING);
        String keyStorePath = sessConfMap.get(JdbcConnectionParams.SSL_KEY_STORE);
        String keyStorePassword = sessConfMap.get(JdbcConnectionParams.SSL_KEY_STORE_PASSWORD);
        KeyStore sslKeyStore = KeyStore.getInstance(JdbcConnectionParams.SSL_KEY_STORE_TYPE);

        if (keyStorePath == null || keyStorePath.isEmpty()) {
            throw new IllegalArgumentException(JdbcConnectionParams.SSL_KEY_STORE
                    + " Not configured for 2 way SSL connection, keyStorePath param is empty");
        }
        try (FileInputStream fis = new FileInputStream(keyStorePath)) {
            sslKeyStore.load(fis, keyStorePassword.toCharArray());
        }
        keyManagerFactory.init(sslKeyStore, keyStorePassword.toCharArray());

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(JdbcConnectionParams.SUNX509_ALGORITHM_STRING);
        String trustStorePath = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE);
        String trustStorePassword = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE_PASSWORD);
        KeyStore sslTrustStore = KeyStore.getInstance(JdbcConnectionParams.SSL_TRUST_STORE_TYPE);

        if (trustStorePath == null || trustStorePath.isEmpty()) {
            throw new IllegalArgumentException(
                    JdbcConnectionParams.SSL_TRUST_STORE + " Not configured for 2 way SSL connection");
        }
        try (FileInputStream fis = new FileInputStream(trustStorePath)) {
            sslTrustStore.load(fis, trustStorePassword.toCharArray());
        }
        trustManagerFactory.init(sslTrustStore);
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
                new SecureRandom());
        socketFactory = new SSLConnectionSocketFactory(context);
    } catch (Exception e) {
        throw new SQLException("Error while initializing 2 way ssl socket factory ", e);
    }
    return socketFactory;
}