List of usage examples for org.apache.http.ssl SSLContextBuilder build
public SSLContext build() throws NoSuchAlgorithmException, KeyManagementException
From source file:com.networknt.client.Client.java
private SSLContext sslContext() throws ClientException, IOException, NoSuchAlgorithmException, KeyManagementException { SSLContext sslContext = null; Map<String, Object> tlsMap = (Map) config.get(TLS); if (tlsMap != null) { SSLContextBuilder builder = SSLContexts.custom(); // load trust store, this is the server public key certificate // first check if javax.net.ssl.trustStore system properties is set. It is only necessary if the server // certificate doesn't have the entire chain. Boolean loadTrustStore = (Boolean) tlsMap.get(LOAD_TRUST_STORE); if (loadTrustStore != null && loadTrustStore == true) { String trustStoreName = System.getProperty(TRUST_STORE_PROPERTY); String trustStorePass = System.getProperty(TRUST_STORE_PASSWORD_PROPERTY); if (trustStoreName != null && trustStorePass != null) { logger.info("Loading trust store from system property at " + Encode.forJava(trustStoreName)); } else { trustStoreName = (String) tlsMap.get(TRUST_STORE); trustStorePass = (String) tlsMap.get(TRUST_PASS); logger.info("Loading trust store from config at " + Encode.forJava(trustStoreName)); }//from ww w.java 2s . com KeyStore trustStore = null; if (trustStoreName != null && trustStorePass != null) { InputStream trustStream = Config.getInstance().getInputStreamFromFile(trustStoreName); if (trustStream != null) { try { trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(trustStream, trustStorePass.toCharArray()); builder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()); } catch (CertificateException ce) { logger.error("CertificateException: Unable to load trust store.", ce); throw new ClientException("CertificateException: Unable to load trust store.", ce); } catch (KeyStoreException kse) { logger.error("KeyStoreException: Unable to load trust store.", kse); throw new ClientException("KeyStoreException: Unable to load trust store.", kse); } finally { trustStream.close(); } } } } // load key store for client certificate if two way ssl is used. Boolean loadKeyStore = (Boolean) tlsMap.get(LOAD_KEY_STORE); if (loadKeyStore != null && loadKeyStore == true) { String keyStoreName = (String) tlsMap.get(KEY_STORE); String keyStorePass = (String) tlsMap.get(KEY_PASS); KeyStore keyStore = null; if (keyStoreName != null && keyStorePass != null) { InputStream keyStream = Config.getInstance().getInputStreamFromFile(keyStoreName); if (keyStream != null) { try { keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(keyStream, keyStorePass.toCharArray()); builder.loadKeyMaterial(keyStore, keyStorePass.toCharArray()); } catch (CertificateException ce) { logger.error("CertificateException: Unable to load key store.", ce); throw new ClientException("CertificateException: Unable to load key store.", ce); } catch (KeyStoreException kse) { logger.error("KeyStoreException: Unable to load key store.", kse); throw new ClientException("KeyStoreException: Unable to load key store.", kse); } catch (UnrecoverableKeyException uke) { logger.error("UnrecoverableKeyException: Unable to load key store.", uke); throw new ClientException("UnrecoverableKeyException: Unable to load key store.", uke); } finally { keyStream.close(); } } } } sslContext = builder.build(); } return sslContext; }
From source file:org.apache.gobblin.elasticsearch.writer.ElasticsearchRestWriter.java
private static RestClient buildRestClient(List<InetSocketTransportAddress> hosts, int threadCount, boolean sslEnabled, String keyStoreType, String keyStoreFilePassword, String identityFilepath, String trustStoreType, String trustStoreFilePassword, String cacertsFilepath) throws Exception { HttpHost[] httpHosts = new HttpHost[hosts.size()]; String scheme = sslEnabled ? "https" : "http"; for (int h = 0; h < httpHosts.length; h++) { InetSocketTransportAddress host = hosts.get(h); httpHosts[h] = new HttpHost(host.getAddress(), host.getPort(), scheme); }//from ww w. j a v a2 s.co m RestClientBuilder builder = RestClient.builder(httpHosts); if (sslEnabled) { log.info("ssl configuration: trustStoreType = {}, cacertsFilePath = {}", trustStoreType, cacertsFilepath); KeyStore truststore = KeyStore.getInstance(trustStoreType); FileInputStream trustInputStream = new FileInputStream(cacertsFilepath); try { truststore.load(trustInputStream, trustStoreFilePassword.toCharArray()); } finally { trustInputStream.close(); } SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(truststore, null); log.info("ssl key configuration: keyStoreType = {}, keyFilePath = {}", keyStoreType, identityFilepath); KeyStore keystore = KeyStore.getInstance(keyStoreType); FileInputStream keyInputStream = new FileInputStream(identityFilepath); try { keystore.load(keyInputStream, keyStoreFilePassword.toCharArray()); } finally { keyInputStream.close(); } sslBuilder.loadKeyMaterial(keystore, keyStoreFilePassword.toCharArray()); final SSLContext sslContext = sslBuilder.build(); builder = builder.setHttpClientConfigCallback(httpAsyncClientBuilder -> httpAsyncClientBuilder // Set ssl context .setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()) // Configure number of threads for clients .setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(threadCount).build())); } else { builder = builder.setHttpClientConfigCallback(httpAsyncClientBuilder -> httpAsyncClientBuilder // Configure number of threads for clients .setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(threadCount).build())); } // Configure timeouts builder.setRequestConfigCallback( requestConfigBuilder -> requestConfigBuilder.setConnectionRequestTimeout(0)); // Important, otherwise the client has spurious timeouts return builder.build(); }
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.// w ww .ja va 2 s . c o 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.hadoop.yarn.server.resourcemanager.security.TestHopsworksRMAppSecurityActions.java
private Pair<String, String[]> loginAndGetJWT() throws Exception { CloseableHttpClient client = null;//from w w w.j a va 2 s.co m try { SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { return true; } }); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), NoopHostnameVerifier.INSTANCE); client = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build(); URL loginURL = new URL(new URL(HOPSWORKS_ENDPOINT), HOPSWORKS_LOGIN_PATH); HttpUriRequest login = RequestBuilder.post().setUri(loginURL.toURI()) .addParameter("email", HOPSWORKS_USER).addParameter("password", HOPSWORKS_PASSWORD).build(); CloseableHttpResponse response = client.execute(login); Assert.assertNotNull(response); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); Header[] authHeaders = response.getHeaders(HttpHeaders.AUTHORIZATION); String masterJWT = null; for (Header h : authHeaders) { Matcher matcher = HopsworksRMAppSecurityActions.JWT_PATTERN.matcher(h.getValue()); if (matcher.matches()) { masterJWT = matcher.group(1); } } JsonParser jsonParser = new JsonParser(); JsonObject json = jsonParser.parse(EntityUtils.toString(response.getEntity())).getAsJsonObject(); JsonArray array = json.getAsJsonArray("renewTokens"); String[] renewTokens = new String[array.size()]; boolean renewalTokensFound = false; for (int i = 0; i < renewTokens.length; i++) { renewTokens[i] = array.get(i).getAsString(); renewalTokensFound = true; } if (masterJWT != null && renewalTokensFound) { return new Pair<>(masterJWT, renewTokens); } throw new IOException("Could not get JWT from Hopsworks"); } finally { if (client != null) { client.close(); } } }
From source file:org.apache.syncope.installer.utilities.HttpUtils.java
private static CloseableHttpClient createHttpsClient() { CloseableHttpClient chc = null;/*from www. j a va 2 s. com*/ try { final SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); chc = HttpClients.custom().setSSLSocketFactory( new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE)).build(); } catch (Exception ex) { // ignore } return chc; }
From source file:org.finra.herd.dao.helper.HttpClientHelper.java
/** * Creates a new HTTP client./*from ww w . ja v a 2 s . co m*/ * * @param trustSelfSignedCertificate specifies whether to trust a self-signed certificate * @param disableHostnameVerification specifies whether to turn off hostname verification * * @return the HTTP client * @throws KeyStoreException if a key store exception occurs * @throws NoSuchAlgorithmException if a no such algorithm exception occurs * @throws KeyManagementException if key management exception */ public CloseableHttpClient createHttpClient(Boolean trustSelfSignedCertificate, Boolean disableHostnameVerification) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { // Create an HTTP client builder. HttpClientBuilder httpClientBuilder = HttpClients.custom(); // Create an SSL context builder. SSLContextBuilder sslContextBuilder = SSLContexts.custom(); // If specified, setup a trust strategy that allows all certificates. if (BooleanUtils.isTrue(trustSelfSignedCertificate)) { sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); } // If specified, turn hostname verification off. HostnameVerifier hostnameVerifier = BooleanUtils.isTrue(disableHostnameVerification) ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER : SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER; // Create and assign an SSL connection socket factory. SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory( sslContextBuilder.build(), hostnameVerifier); httpClientBuilder.setSSLSocketFactory(sslConnectionSocketFactory); // Build and return an HTTP client. return httpClientBuilder.build(); }
From source file:org.flowable.http.bpmn.impl.HttpActivityBehaviorImpl.java
public HttpActivityBehaviorImpl() { HttpClientConfig config = CommandContextUtil.getProcessEngineConfiguration().getHttpClientConfig(); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); // https settings if (config.isDisableCertVerify()) { try {//from w ww. j av a 2 s . c om SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); httpClientBuilder.setSSLSocketFactory( new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } })); } catch (Exception e) { LOGGER.error("Could not configure HTTP client SSL self signed strategy", e); } } // request retry settings int retryCount = 0; if (config.getRequestRetryLimit() > 0) { retryCount = config.getRequestRetryLimit(); } httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(retryCount, false)); this.httpActivityExecutor = new HttpActivityExecutor(httpClientBuilder, new ProcessErrorPropagator()); }
From source file:org.flowable.http.cmmn.impl.CmmnHttpActivityBehaviorImpl.java
public CmmnHttpActivityBehaviorImpl() { org.flowable.cmmn.engine.HttpClientConfig config = CommandContextUtil.getCmmnEngineConfiguration() .getHttpClientConfig();/*from w ww . j a va 2 s . c o m*/ HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); // https settings if (config.isDisableCertVerify()) { try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); httpClientBuilder.setSSLSocketFactory( new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } })); } catch (Exception e) { LOGGER.error("Could not configure HTTP client SSL self signed strategy", e); } } // request retry settings int retryCount = 0; if (config.getRequestRetryLimit() > 0) { retryCount = config.getRequestRetryLimit(); } httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(retryCount, false)); this.httpActivityExecutor = new HttpActivityExecutor(httpClientBuilder, new NopErrorPropagator()); }
From source file:org.flowable.http.impl.HttpActivityBehaviorImpl.java
public HttpActivityBehaviorImpl() { HttpClientConfig config = CommandContextUtil.getProcessEngineConfiguration().getHttpClientConfig(); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); // https settings if (config.isDisableCertVerify()) { try {/* ww w . jav a2 s . c o m*/ SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); httpClientBuilder.setSSLSocketFactory( new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() { public boolean verify(String s, SSLSession sslSession) { return true; } })); } catch (Exception e) { LOGGER.error("Could not configure HTTP client SSL self signed strategy", e); } } // request retry settings int retryCount = 0; if (config.getRequestRetryLimit() > 0) { retryCount = config.getRequestRetryLimit(); } httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(retryCount, false)); // Build http client client = httpClientBuilder.build(); LOGGER.info("HTTP client is initialized"); // Shutdown hook to close the http client Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { if (client != null) { try { client.close(); LOGGER.info("HTTP client is closed"); } catch (Throwable e) { LOGGER.error("Could not close http client", e); } } } }); }