List of usage examples for org.apache.http.ssl SSLContexts custom
public static SSLContextBuilder custom()
From source file:com.wudaosoft.net.httpclient.Request.java
protected void init() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException { Args.notNull(hostConfig, "Host config"); SSLConnectionSocketFactory sslConnectionSocketFactory = null; if (sslcontext == null) { if (hostConfig.getCA() != null) { // Trust root CA and all self-signed certs SSLContext sslcontext1 = SSLContexts.custom().loadTrustMaterial(hostConfig.getCA(), hostConfig.getCAPassword(), TrustSelfSignedStrategy.INSTANCE).build(); // Allow TLSv1 protocol only sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext1, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); } else {/*from w w w . j a v a 2 s . c om*/ if (isTrustAll) { SSLContext sslcontext1 = SSLContext.getInstance("TLS"); TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException { } } }; sslcontext1.init(null, trustAllCerts, null); sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext1, NoopHostnameVerifier.INSTANCE); } else { sslConnectionSocketFactory = SSLConnectionSocketFactory.getSocketFactory(); } } } else { sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); } if (keepAliveStrategy == null) { keepAliveStrategy = new ConnectionKeepAliveStrategy() { public long getKeepAliveDuration(HttpResponse response, HttpContext context) { // Honor 'keep-alive' header HeaderElementIterator it = new BasicHeaderElementIterator( response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { try { return Long.parseLong(value) * 1000; } catch (NumberFormatException ignore) { } } } // HttpHost target = (HttpHost) // context.getAttribute(HttpClientContext.HTTP_TARGET_HOST); // if // ("xxxxx".equalsIgnoreCase(target.getHostName())) // { // // Keep alive for 5 seconds only // return 3 * 1000; // } else { // // otherwise keep alive for 30 seconds // return 30 * 1000; // } return 30 * 1000; } }; } if (retryHandler == null) { retryHandler = new HttpRequestRetryHandler() { public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= 3) { // Do not retry if over max retry count return false; } if (exception instanceof InterruptedIOException) { // Timeout return false; } if (exception instanceof UnknownHostException) { // Unknown host return false; } if (exception instanceof ConnectTimeoutException) { // Connection refused return false; } if (exception instanceof SSLException) { // SSL handshake exception return false; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); boolean idempotent = !(request instanceof HttpEntityEnclosingRequest); if (idempotent) { // Retry if the request is considered idempotent return true; } return false; } }; } connManager = new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslConnectionSocketFactory).build()); if (hostConfig.getHost() != null) { connManager.setMaxTotal(hostConfig.getPoolSize() + 60); connManager.setMaxPerRoute( new HttpRoute(hostConfig.getHost(), null, !HttpHost.DEFAULT_SCHEME_NAME.equals(hostConfig.getHost().getSchemeName())), hostConfig.getPoolSize()); connManager.setDefaultMaxPerRoute(20); } else { connManager.setMaxTotal(hostConfig.getPoolSize()); int hostCount = hostConfig.getHostCount() == 0 ? 10 : hostConfig.getHostCount(); connManager.setDefaultMaxPerRoute(hostConfig.getPoolSize() / hostCount); } // connManager.setValidateAfterInactivity(2000); // Create socket configuration SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).setSoKeepAlive(isKeepAlive).build(); connManager.setDefaultSocketConfig(socketConfig); // Create connection configuration ConnectionConfig connectionConfig = ConnectionConfig.custom() .setMalformedInputAction(CodingErrorAction.IGNORE) .setUnmappableInputAction(CodingErrorAction.IGNORE) .setCharset(hostConfig.getCharset() == null ? Consts.UTF_8 : hostConfig.getCharset()).build(); connManager.setDefaultConnectionConfig(connectionConfig); new IdleConnectionMonitorThread(connManager).start(); if (requestInterceptor == null) { requestInterceptor = new SortHeadersInterceptor(hostConfig); } if (!hostConfig.isMulticlient()) { defaultHttpContext = HttpClientContext.create(); httpClient = create(); } }
From source file:com.cisco.oss.foundation.http.netlifx.apache.ApacheNetflixHttpClient.java
protected void configureClient() { clientConfig = new DefaultClientConfigImpl(); clientConfig.loadProperties(getApiName()); setLoadBalancer(loadBalancer);/*from w w w . j a v a 2 s .c o m*/ // clientConfig.set(CommonClientConfigKey.NIWSServerListClassName, DiscoveryEnabledNIWSServerList.class.getName()); // clientConfig.set(IClientConfigKey.Keys.DeploymentContextBasedVipAddresses, metadata.getServiceName()); // clientConfig.set(CommonClientConfigKey.NFLoadBalancerRuleClassName, RoundRobinRule.class.getName()); // clientConfig.set(CommonClientConfigKey.NFLoadBalancerPingClassName, NIWSDiscoveryPing.class.getName()); // clientConfig.set(CommonClientConfigKey.VipAddressResolverClassName, SimpleVipAddressResolver.class.getName()); if (DiscoveryManager.getInstance().getDiscoveryClient() == null && startEurekaClient) { EurekaInstanceConfig eurekaInstanceConfig = new MyDataCenterInstanceConfig(getApiName()); EurekaClientConfig eurekaClientConfig = new DefaultEurekaClientConfig(getApiName() + "."); DiscoveryManager.getInstance().initComponent(eurekaInstanceConfig, eurekaClientConfig); } loadBalancer.initWithNiwsConfig(clientConfig); // if (HystrixPlugins.getInstance().getMetricsPublisher() == null) { // HystrixPlugins.getInstance().registerMetricsPublisher(HystrixMetricsPublisherDefault.getInstance()); // } RequestConfig.Builder requestBuilder = RequestConfig.custom(); requestBuilder = requestBuilder.setConnectTimeout(metadata.getConnectTimeout()); requestBuilder = requestBuilder.setSocketTimeout(metadata.getReadTimeout()); requestBuilder = requestBuilder.setStaleConnectionCheckEnabled(metadata.isStaleConnectionCheckEnabled()); RequestConfig requestConfig = requestBuilder.build(); boolean addSslSupport = StringUtils.isNotEmpty(metadata.getKeyStorePath()) && StringUtils.isNotEmpty(metadata.getKeyStorePassword()); boolean addTrustSupport = StringUtils.isNotEmpty(metadata.getTrustStorePath()) && StringUtils.isNotEmpty(metadata.getTrustStorePassword()); autoCloseable = metadata.isAutoCloseable(); autoEncodeUri = metadata.isAutoEncodeUri(); followRedirects = metadata.isFollowRedirects(); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); SSLContext sslContext = null; try { String keystoreType = "JKS"; if (addSslSupport && addTrustSupport) { KeyStore keyStore = KeyStore.getInstance(keystoreType); keyStore.load(new FileInputStream(metadata.getKeyStorePath()), metadata.getKeyStorePassword().toCharArray()); KeyStore trustStore = KeyStore.getInstance(keystoreType); trustStore.load(new FileInputStream(metadata.getTrustStorePath()), metadata.getTrustStorePassword().toCharArray()); sslContext = SSLContexts.custom().useProtocol("TLS") .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray()) .loadTrustMaterial(trustStore, null).build(); } else if (addSslSupport) { TrustManagerFactory tmf = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore keyStore = KeyStore.getInstance(keystoreType); keyStore.load(new FileInputStream(metadata.getKeyStorePath()), metadata.getKeyStorePassword().toCharArray()); tmf.init(keyStore); sslContext = SSLContexts.custom().useProtocol("SSL") .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray()).build(); sslContext.init(null, tmf.getTrustManagers(), null); SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); httpClientBuilder.setSSLSocketFactory(sf); } else if (addTrustSupport) { KeyStore trustStore = KeyStore.getInstance(keystoreType); trustStore.load(new FileInputStream(metadata.getTrustStorePath()), metadata.getTrustStorePassword().toCharArray()); sslContext = SSLContexts.custom().useProtocol("TLS").loadTrustMaterial(trustStore, null).build(); } if (addSslSupport | addTrustSupport) { SSLContext.setDefault(sslContext); httpClientBuilder.setSslcontext(sslContext); } } catch (Exception e) { LOGGER.error("can't set TLS Support. Error is: {}", e, e); } httpClientBuilder.setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress()) .setMaxConnTotal(metadata.getMaxConnectionsTotal()).setDefaultRequestConfig(requestConfig) .evictExpiredConnections().evictIdleConnections(metadata.getIdleTimeout(), TimeUnit.MILLISECONDS) .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout())); HttpAsyncClientBuilder httpAsyncClientBuilder = HttpAsyncClients.custom(); httpAsyncClientBuilder.setDefaultRequestConfig(requestConfig) .setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress()) .setMaxConnTotal(metadata.getMaxConnectionsTotal()) .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout())) .setSSLContext(sslContext); if (metadata.isDisableCookies()) { httpClientBuilder.disableCookieManagement(); httpAsyncClientBuilder.disableCookieManagement(); } if (hostnameVerifier != null) { httpClientBuilder.setSSLHostnameVerifier(hostnameVerifier); httpAsyncClientBuilder.setSSLHostnameVerifier(hostnameVerifier); } if (!followRedirects) { httpClientBuilder.disableRedirectHandling(); } httpClient = httpClientBuilder.build(); httpAsyncClient = httpAsyncClientBuilder.build(); httpAsyncClient.start(); }
From source file:org.gtri.fhir.api.vistaex.resource.impl.VistaExResourceImpl.java
/** * Creates and configures a {@link SSLConnectionSocketFactory} to use in the application * @return//from ww w.j a va2s. c om */ private SSLConnectionSocketFactory createSSLConnectionSocketFactory() { File trustStore = getFileInClassPath("gtVistaExTrustStore"); SSLContext sslcontext = null; SSLConnectionSocketFactory sslsf = null; try { //TODO: At some point configure to use trust store sslcontext = SSLContexts.custom() //.loadTrustMaterial(trustStore, "gtvistaex".toCharArray(),new TrustSelfSignedStrategy()) .loadTrustMaterial(new TrustAllStrategy()).build(); //TODO: Fix to use non-deprecated code // Allow TLSv1 protocol only sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (Exception e) { e.printStackTrace(); } return sslsf; }
From source file:org.apache.geode.rest.internal.web.controllers.RestAPIsWithSSLDUnitTest.java
private CloseableHttpClient getSSLBasedHTTPClient(Properties properties) throws Exception { KeyStore clientKeys = KeyStore.getInstance("JKS"); File keystoreJKSForPath = findKeyStoreJKS(properties); clientKeys.load(new FileInputStream(keystoreJKSForPath), "password".toCharArray()); KeyStore clientTrust = KeyStore.getInstance("JKS"); File trustStoreJKSForPath = findTrustStoreJKSForPath(properties); clientTrust.load(new FileInputStream(trustStoreJKSForPath), "password".toCharArray()); // this is needed SSLContextBuilder custom = SSLContexts.custom(); SSLContextBuilder sslContextBuilder = custom.loadTrustMaterial(clientTrust, new TrustSelfSignedStrategy()); SSLContext sslcontext = sslContextBuilder .loadKeyMaterial(clientKeys, "password".toCharArray(), (aliases, socket) -> { if (aliases.size() == 1) { return aliases.keySet().stream().findFirst().get(); }/*from w w w . j ava 2s .co m*/ if (!StringUtils.isEmpty(properties.getProperty(INVALID_CLIENT_ALIAS))) { return properties.getProperty(INVALID_CLIENT_ALIAS); } else { return properties.getProperty(SSL_WEB_ALIAS); } }).build(); // Host checking is disabled here , as tests might run on multiple hosts and // host entries can not be assumed SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build(); }
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 w ww . j ava2 s .co m*/ 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:com.hpe.elderberry.TaxiiConnection.java
public RestTemplate getRestTemplate() { if (restTemplate == null) { HttpClientBuilder builder = custom(); if (useProxy) { if ("".equals(proxyHost)) { proxyHost = System.getProperty(discoveryUrl.getScheme() + ".proxyHost"); }/*from www . jav a 2 s .c om*/ if (proxyPort == 0) { proxyPort = Integer.parseInt(System.getProperty(discoveryUrl.getScheme() + ".proxyPort", "0")); } if ("".equals(proxyHost) || proxyHost == null || proxyPort == 0) { log.warn("proxy requested, but not setup, not using a proxy"); } else { log.info("using " + discoveryUrl.getScheme() + " proxy: " + proxyHost + ":" + proxyPort); HttpHost proxy = new HttpHost(proxyHost, proxyPort); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); builder.setRoutePlanner(routePlanner); } } if (getTrustStore() != null || getKeyStore() != null) { SSLContext sslContext; try { sslContext = SSLContexts.custom() .loadTrustMaterial(getTrustStore(), new TrustSelfSignedStrategy()) .loadKeyMaterial(getKeyStore(), keyPassword).build(); } catch (Exception e) { log.error("unable to create SSL context, " + e.getMessage(), e); throw new RuntimeException(e); } SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext); builder.setSSLSocketFactory(sslsf); } if (!"".equals(username)) { restTemplate = new RestTemplate( new PreemptiveAuthHttpRequestFactor(username, password, builder.build())); } else { restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(builder.build())); } if (marshaller == null) { marshaller = new Jaxb2Marshaller(); marshaller.setPackagesToScan("org.mitre"); try { marshaller.afterPropertiesSet(); } catch (Exception e) { log.error("unable to create Jaxb2 Marshaller: " + e.getMessage(), e); throw new RuntimeException(e); } } MarshallingHttpMessageConverter converter = new MarshallingHttpMessageConverter(marshaller); converter.setSupportedMediaTypes(singletonList(APPLICATION_XML)); //noinspection unchecked restTemplate.setMessageConverters(Collections.<HttpMessageConverter<?>>singletonList(converter)); } return restTemplate; }
From source file:com.liferay.petra.json.web.service.client.BaseJSONWebServiceClientImpl.java
protected SSLIOSessionStrategy getSSLIOSessionStrategy() { SSLContextBuilder sslContextBuilder = SSLContexts.custom(); SSLContext sslContext = null; try {/*from ww w .ja va 2s . co m*/ sslContextBuilder.loadTrustMaterial(_keyStore, new TrustSelfSignedStrategy()); sslContext = sslContextBuilder.build(); sslContext.init(null, new TrustManager[] { new X509TrustManagerImpl() }, null); } catch (Exception e) { throw new RuntimeException(e); } return new SSLIOSessionStrategy(sslContext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); }
From source file:be.fedict.dcat.datagovbe.Drupal.java
/** * Drupal REST Service.//from w w w. j a v a 2 s .c o m * * @param url service endpoint * @param langs languages * @param store */ public Drupal(URL url, String[] langs, Storage store) { this.url = url; this.langs = langs; this.store = store; this.host = new HttpHost(url.getHost(), -1, url.getProtocol()); Executor e = null; try { /* Self signed certificates are OK */ SSLContext ctx = SSLContexts.custom().loadTrustMaterial(new TrustSelfSignedStrategy()).build(); /* Allow redirect on POST */ CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new LaxRedirectStrategy()) .setSSLContext(ctx).build(); e = Executor.newInstance(client); } catch (NoSuchAlgorithmException ex) { logger.error("Algo error", ex); } catch (KeyStoreException | KeyManagementException ex) { logger.error("Store exception", ex); } this.exec = e; }
From source file:com.github.parisoft.resty.client.Client.java
private HttpClient newHttpClient() throws IOException { final SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(timeout).build(); final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout) .setConnectTimeout(timeout).setSocketTimeout(timeout).setCookieSpec(CookieSpecs.DEFAULT).build(); final SSLContext sslContext; final HostnameVerifier hostnameVerifier; if (bypassSSL) { hostnameVerifier = NoopHostnameVerifier.INSTANCE; try {/* w ww.j a v a 2s. com*/ sslContext = SSLContexts.custom().loadTrustMaterial(new BypassTrustStrategy()) .useProtocol(SSLConnectionSocketFactory.TLS).build(); } catch (Exception e) { throw new IOException("Cannot create bypassed SSL context", e); } } else { sslContext = SSLContexts.createSystemDefault(); hostnameVerifier = null; } final HttpRequestRetryHandler retryHandler = new RequestRetryHandler(retries); final HttpClientConnectionManager connectionManager = getConnectionManager(); return HttpClientBuilder.create().setConnectionManager(connectionManager).setConnectionManagerShared(true) .setRetryHandler(retryHandler).setDefaultSocketConfig(socketConfig) .setDefaultRequestConfig(requestConfig).setSSLContext(sslContext) .setSSLHostnameVerifier(hostnameVerifier).build(); }