List of usage examples for org.apache.http.conn.ssl SSLContexts custom
public static SSLContextBuilder custom()
From source file:nl.armatiek.xslweb.configuration.WebApp.java
public CloseableHttpClient getHttpClient() { if (httpClient == null) { PoolingHttpClientConnectionManager cm; if (Context.getInstance().getTrustAllCerts()) { try { SSLContextBuilder scb = SSLContexts.custom(); scb.loadTrustMaterial(null, new TrustStrategy() { @Override// w ww . j a v a 2s. co m public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }); SSLContext sslContext = scb.build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create().register("https", sslsf) .register("http", new PlainConnectionSocketFactory()).build(); cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry); } catch (Exception e) { logger.warn("Could not set HttpClient to trust all SSL certificates", e); cm = new PoolingHttpClientConnectionManager(); } } else { cm = new PoolingHttpClientConnectionManager(); } cm.setMaxTotal(200); cm.setDefaultMaxPerRoute(20); HttpHost localhost = new HttpHost("localhost", 80); cm.setMaxPerRoute(new HttpRoute(localhost), 50); HttpClientBuilder builder = HttpClients.custom().setConnectionManager(cm); builder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault())); builder.setDefaultCookieStore(new BasicCookieStore()); httpClient = builder.build(); } return httpClient; }
From source file:com.petalmd.armor.AbstractUnitTest.java
protected final HeaderAwareJestHttpClient getJestClient(final String serverUri, final String username, final String password) throws Exception {// http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html final CredentialsProvider credsProvider = new BasicCredentialsProvider(); final HttpClientConfig clientConfig1 = new HttpClientConfig.Builder(serverUri).multiThreaded(true).build(); // Construct a new Jest client according to configuration via factory final HeaderAwareJestClientFactory factory1 = new HeaderAwareJestClientFactory(); factory1.setHttpClientConfig(clientConfig1); final HeaderAwareJestHttpClient c = factory1.getObject(); final HttpClientBuilder hcb = HttpClients.custom(); if (username != null) { credsProvider.setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(username, password)); }/*from w w w.j av a2s. co m*/ if (useSpnego) { //SPNEGO/Kerberos setup log.debug("SPNEGO activated"); final AuthSchemeProvider nsf = new SPNegoSchemeFactory(true, false);// new NegotiateSchemeProvider(); final Credentials jaasCreds = new JaasCredentials(); credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.SPNEGO), jaasCreds); credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.NTLM), new NTCredentials("Guest", "Guest", "Guest", "Guest")); final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, nsf).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).build(); hcb.setDefaultAuthSchemeRegistry(authSchemeRegistry); } hcb.setDefaultCredentialsProvider(credsProvider); if (serverUri.startsWith("https")) { log.debug("Configure Jest with SSL"); final KeyStore myTrustStore = KeyStore.getInstance("JKS"); myTrustStore.load(new FileInputStream(SecurityUtil.getAbsoluteFilePathFromClassPath("ArmorTS.jks")), "changeit".toCharArray()); final KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream(SecurityUtil.getAbsoluteFilePathFromClassPath("ArmorKS.jks")), "changeit".toCharArray()); final SSLContext sslContext = SSLContexts.custom().useTLS() .loadKeyMaterial(keyStore, "changeit".toCharArray()).loadTrustMaterial(myTrustStore).build(); String[] protocols = null; if (enableSSLv3Only) { protocols = new String[] { "SSLv3" }; } else { protocols = SecurityUtil.ENABLED_SSL_PROTOCOLS; } final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, protocols, SecurityUtil.ENABLED_SSL_CIPHERS, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); hcb.setSSLSocketFactory(sslsf); } hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build()); final CloseableHttpClient httpClient = hcb.build(); c.setHttpClient(httpClient); return c; }
From source file:com.gemstone.gemfire.rest.internal.web.controllers.RestAPIsWithSSLDUnitTest.java
private CloseableHttpClient getSSLBasedHTTPClient(String algo) throws Exception { File jks = findTrustedJKS();// ww w . ja va2 s.com KeyStore clientKeys = KeyStore.getInstance("JKS"); clientKeys.load(new FileInputStream(jks.getCanonicalPath()), "password".toCharArray()); // this is needed SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(clientKeys, new TrustSelfSignedStrategy()) .loadKeyMaterial(clientKeys, "password".toCharArray()).build(); // Host checking is disabled here , as tests might run on multiple hosts and // host entries can not be assumed SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); return httpclient; }
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 w w. ja v a 2s . co 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:io.fabric8.elasticsearch.ElasticsearchIntegrationTest.java
protected final CloseableHttpClient getHttpClient() throws Exception { final HttpClientBuilder hcb = HttpClients.custom(); if (enableHttpClientSSL) { log.debug("Configure HTTP client with SSL"); final KeyStore myTrustStore = KeyStore.getInstance("JKS"); myTrustStore.load(new FileInputStream(truststore), password.toCharArray()); final KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream(keystore), password.toCharArray()); final SSLContextBuilder sslContextbBuilder = SSLContexts.custom().useTLS(); if (trustHttpServerCertificate) { sslContextbBuilder.loadTrustMaterial(myTrustStore); }//from ww w. j ava 2 s .co m if (sendHttpClientCertificate) { sslContextbBuilder.loadKeyMaterial(keyStore, "changeit".toCharArray()); } final SSLContext sslContext = sslContextbBuilder.build(); String[] protocols = null; if (enableHttpClientSSLv3Only) { protocols = new String[] { "SSLv3" }; } else { protocols = new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" }; } final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, protocols, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); hcb.setSSLSocketFactory(sslsf); } hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build()); return hcb.build(); }
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 ww w. j av a 2s . com 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:com.rockagen.commons.http.HttpConn.java
/** * Handler main/*from ww w. ja va 2 s . c o m*/ * * @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:net.geoprism.dashboard.DashboardMap.java
/** * Makes a getMap request to geoserver and returns the response as a ByteArrayOutputStream * //from w w w . ja v a 2 s . c o m * @throws NoSuchAlgorithmException * * @requestURL = geoserver getMap() or getLegendGraphic() request url */ private byte[] requestGeoserverImage(String requestURL) { InputStream inStream = null; ByteArrayOutputStream outStream = null; CloseableHttpResponse response = null; CloseableHttpClient client = null; try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); // StorePath and StorePass must be set for the systems keystore trustStore.load(new FileInputStream(GeoserverProperties.getGeoserverKeystorePath()), GeoserverProperties.getGeoserverKeystorePass().toCharArray()); SSLContext sslcontext = SSLContexts.custom() .loadKeyMaterial(trustStore, GeoserverProperties.getGeoserverKeystorePass().toCharArray()) .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build(); // // TODO: socket factory load once ever // SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); client = HttpClients.custom() // Allow all hostnames regardless of what is specified in the certificate .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER) // Use the provided SSL socket factory .setSSLSocketFactory(factory) // Set a default cookie store which will be used in all of the requests .setDefaultCookieStore(new BasicCookieStore()).build(); HttpGet method = new HttpGet(requestURL); response = client.execute(method); inStream = response.getEntity().getContent(); outStream = new ByteArrayOutputStream(); // Copy the input stream to the output stream IOUtils.copy(inStream, outStream); } catch (MalformedURLException e) { String error = "The URL is not formated correctly."; throw new ProgrammingErrorException(error, e); } catch (IOException e) { String error = "Could not make the request to the map server."; throw new ProgrammingErrorException(error, e); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnrecoverableKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (inStream != null) { try { inStream.close(); } catch (IOException e) { String error = "Could not close stream."; throw new ProgrammingErrorException(error, e); } } if (outStream != null) { try { outStream.close(); } catch (IOException e) { String error = "Could not close stream."; throw new ProgrammingErrorException(error, e); } } if (response != null) { try { response.close(); } catch (IOException e) { String error = "Could not close stream."; throw new ProgrammingErrorException(error, e); } } if (client != null) { try { client.close(); } catch (IOException e) { String error = "Could not close stream."; throw new ProgrammingErrorException(error, e); } } } return outStream.toByteArray(); }
From source file:com.enioka.jqm.api.HibernateClient.java
private InputStream getFile(String url) { EntityManager em = getEm();//from w w w . j av a 2 s. c om File file = null; FileOutputStream fos = null; CloseableHttpClient cl = null; CloseableHttpResponse rs = null; String nameHint = null; File destDir = new File(System.getProperty("java.io.tmpdir")); if (!destDir.isDirectory() && !destDir.mkdir()) { throw new JqmClientException("could not create temp directory " + destDir.getAbsolutePath()); } jqmlogger.trace("File will be copied into " + destDir); try { file = new File(destDir + "/" + UUID.randomUUID().toString()); CredentialsProvider credsProvider = null; if (SimpleApiSecurity.getId(em).usr != null) { credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials( SimpleApiSecurity.getId(em).usr, SimpleApiSecurity.getId(em).pass)); } SSLContext ctx = null; if (getFileProtocol(em).equals("https://")) { try { if (p.containsKey("com.enioka.jqm.ws.truststoreFile")) { KeyStore trust = null; InputStream trustIs = null; try { trust = KeyStore .getInstance(this.p.getProperty("com.enioka.jqm.ws.truststoreType", "JKS")); } catch (KeyStoreException e) { throw new JqmInvalidRequestException("Specified trust store type [" + this.p.getProperty("com.enioka.jqm.ws.truststoreType", "JKS") + "] is invalid", e); } try { trustIs = new FileInputStream(this.p.getProperty("com.enioka.jqm.ws.truststoreFile")); } catch (FileNotFoundException e) { throw new JqmInvalidRequestException("Trust store file [" + this.p.getProperty("com.enioka.jqm.ws.truststoreFile") + "] cannot be found", e); } String trustp = this.p.getProperty("com.enioka.jqm.ws.truststorePass", null); try { trust.load(trustIs, (trustp == null ? null : trustp.toCharArray())); } catch (Exception e) { throw new JqmInvalidRequestException("Could not load the trust store file", e); } finally { try { trustIs.close(); } catch (IOException e) { // Nothing to do. } } ctx = SSLContexts.custom().loadTrustMaterial(trust).build(); } else { ctx = SSLContexts.createSystemDefault(); } } catch (Exception e) { // Cannot happen - not trust store is actually loaded! jqmlogger.error( "An supposedly impossible error has happened. Downloading files through the API may not work.", e); } } cl = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).setSslcontext(ctx).build(); // Run HTTP request HttpUriRequest rq = new HttpGet(url.toString()); rs = cl.execute(rq); if (rs.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new JqmClientException( "Could not retrieve file from JQM node. The file may have been purged, or the node may be unreachable. HTTP code was: " + rs.getStatusLine().getStatusCode()); } // There may be a filename hint inside the response Header[] hs = rs.getHeaders("Content-Disposition"); if (hs.length == 1) { Header h = hs[0]; if (h.getValue().contains("filename=")) { nameHint = h.getValue().split("=")[1]; } } // Save the file to a temp local file fos = new FileOutputStream(file); rs.getEntity().writeTo(fos); jqmlogger.trace("File was downloaded to " + file.getAbsolutePath()); } catch (IOException e) { throw new JqmClientException( "Could not create a webserver-local copy of the file. The remote node may be down.", e); } finally { closeQuietly(em); closeQuietly(fos); closeQuietly(rs); closeQuietly(cl); } SelfDestructFileStream res = null; try { res = new SelfDestructFileStream(file); } catch (IOException e) { throw new JqmClientException("File seems not to be present where it should have been downloaded", e); } res.nameHint = nameHint; return res; }
From source file:org.apache.nifi.processors.standard.PostHTTP.java
private SSLContext createSSLContext(final SSLContextService service) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException { SSLContextBuilder builder = SSLContexts.custom(); final String trustFilename = service.getTrustStoreFile(); if (trustFilename != null) { final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType()); try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) { truststore.load(in, service.getTrustStorePassword().toCharArray()); }/*from ww w . java 2 s.co m*/ builder = builder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy()); } final String keyFilename = service.getKeyStoreFile(); if (keyFilename != null) { final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType()); try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) { keystore.load(in, service.getKeyStorePassword().toCharArray()); } builder = builder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray()); } builder = builder.useProtocol(service.getSslAlgorithm()); final SSLContext sslContext = builder.build(); return sslContext; }