List of usage examples for org.apache.http.conn.ssl SSLContextBuilder build
public SSLContext build() throws NoSuchAlgorithmException, KeyManagementException
From source file:org.apache.solr.util.SSLTestConfig.java
/** * Builds a new SSLContext for jetty servers which have been configured based on the settings of * this object.//from ww w.j a va2 s .c om * * NOTE: Uses a completely insecure {@link SecureRandom} instance to prevent tests from blocking * due to lack of entropy, also explicitly allows the use of self-signed * certificates (since that's what is almost always used during testing). * almost always used during testing). */ public SSLContext buildServerSSLContext() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException { assert isSSLMode(); SSLContextBuilder builder = SSLContexts.custom(); builder.setSecureRandom(NotSecurePsuedoRandom.INSTANCE); builder.loadKeyMaterial(buildKeyStore(keyStore, getKeyStorePassword()), getKeyStorePassword().toCharArray()); if (isClientAuthMode()) { builder.loadTrustMaterial(buildKeyStore(trustStore, getTrustStorePassword()), new TrustSelfSignedStrategy()).build(); } return builder.build(); }
From source file:com.activiti.service.activiti.ActivitiClientService.java
public CloseableHttpClient getHttpClient(String userName, String password) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password)); SSLConnectionSocketFactory sslsf = null; try {// w w w .j av a 2 s . c o m SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); sslsf = new SSLConnectionSocketFactory(builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (Exception e) { log.warn("Could not configure HTTP client to use SSL", e); } HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); if (sslsf != null) { httpClientBuilder.setSSLSocketFactory(sslsf); } return httpClientBuilder.build(); }
From source file:org.metaeffekt.dcc.controller.execution.RemoteExecutor.java
private CloseableHttpClient instantiateHttpClientWithTimeout() throws IOException, GeneralSecurityException { final KeyStore keyStore = loadKeyStore(sslConfiguration.getKeyStoreLocation(), sslConfiguration.getKeyStorePassword()); final KeyStore trustStore = loadKeyStore(sslConfiguration.getTrustStoreLocation(), sslConfiguration.getTrustStorePassword()); final SSLContextBuilder sslContextBuilder = SSLContexts.custom(); sslContextBuilder.loadKeyMaterial(keyStore, sslConfiguration.getKeyStorePassword()); sslContextBuilder.loadTrustMaterial(trustStore); final HttpClientBuilder builder = HttpClientBuilder.create(); builder.setSslcontext(sslContextBuilder.build()); builder.setHostnameVerifier(new AllowAllHostnameVerifier()); final CloseableHttpClient client = builder.build(); return client; }
From source file:eu.vital.TrustManager.connectors.dms.DMSManager.java
private String queryDMS(String dms_endpoint, String body) throws UnsupportedEncodingException, IOException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException { // SSLContextBuilder builder = new SSLContextBuilder(); // builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); // SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( // builder.build(),SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // CloseableHttpClient httpclient = HttpClients.custom() // //.setSSLSocketFactory(sslsf) // .setHostnameVerifier(new AllowAllHostnameVerifier()) // .setRedirectStrategy(new LaxRedirectStrategy()).build(); // //from w w w . j a v a 2s. c o m SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf) .setRedirectStrategy(new LaxRedirectStrategy()).build(); String url = this.dms_URL + "/" + dms_endpoint; HttpPost post = new HttpPost(url); post.addHeader("Content-Type", "application/json"); post.addHeader("Content-Type", cookie.substring(17)); RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5000) .setConnectTimeout(5000).setSocketTimeout(5000).build(); post.setConfig(requestConfig); // HttpEntity entity = new StringEntity(body, StandardCharsets.UTF_8); post.setEntity(entity); CloseableHttpResponse clientresponse = httpclient.execute(post); if (clientresponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK && clientresponse.getStatusLine().getStatusCode() != HttpStatus.SC_ACCEPTED) { return null; } String sdata; sdata = EntityUtils.toString(clientresponse.getEntity(), StandardCharsets.UTF_8); return sdata; // }
From source file:com.floragunn.searchguard.AbstractUnitTest.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(getAbsoluteFilePathFromClassPath("truststore.jks")), "changeit".toCharArray()); final KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream(getAbsoluteFilePathFromClassPath(keystore)), "changeit".toCharArray()); final SSLContextBuilder sslContextbBuilder = SSLContexts.custom().useTLS(); if (trustHTTPServerCertificate) { sslContextbBuilder.loadTrustMaterial(myTrustStore); }/*ww w.ja va2 s.c o 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:eu.vital.TrustManager.connectors.dms.DMSManager.java
private String query(String dms_endpoint, String body, String method) throws SocketTimeoutException, ConnectException, IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException { Cookie ck;//from www .j a va 2 s . c o m //String internalToken; CloseableHttpClient httpclient; HttpRequestBase httpaction; //boolean wasEmpty; //int code; SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); URI uri = null; try { // Prepare to forward the request to the proxy uri = new URI(dms_URL + "/" + dms_endpoint); } catch (URISyntaxException e1) { java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, e1); } if (method.equals("GET")) { httpaction = new HttpGet(uri); } else { httpaction = new HttpPost(uri); } // Get token or authenticate if null or invalid //internalToken = client.getToken(); ck = new Cookie("vitalAccessToken", cookie.substring(17)); httpaction.setHeader("Cookie", ck.toString()); httpaction.setConfig(RequestConfig.custom().setConnectionRequestTimeout(5000).setConnectTimeout(5000) .setSocketTimeout(5000).build()); httpaction.setHeader("Content-Type", javax.ws.rs.core.MediaType.APPLICATION_JSON); StringEntity strEntity = new StringEntity(body, StandardCharsets.UTF_8); if (method.equals("POST")) { ((HttpPost) httpaction).setEntity(strEntity); } // Execute and get the response. CloseableHttpResponse response = null; try { response = httpclient.execute(httpaction); } catch (ClientProtocolException e) { java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, e); } catch (IOException e) { try { // Try again with a higher timeout try { Thread.sleep(1000); // do not retry immediately } catch (InterruptedException e1) { java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, e1); return ""; } httpaction.setConfig(RequestConfig.custom().setConnectionRequestTimeout(7000) .setConnectTimeout(7000).setSocketTimeout(7000).build()); response = httpclient.execute(httpaction); } catch (ClientProtocolException ea) { java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, ea); return ""; } catch (IOException ea) { try { // Try again with a higher timeout try { Thread.sleep(1000); // do not retry immediately } catch (InterruptedException e1) { java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, e1); return ""; } httpaction.setConfig(RequestConfig.custom().setConnectionRequestTimeout(12000) .setConnectTimeout(12000).setSocketTimeout(12000).build()); response = httpclient.execute(httpaction); } catch (ClientProtocolException eaa) { java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, eaa); return ""; } catch (SocketTimeoutException eaa) { java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, eaa); return ""; } catch (ConnectException eaa) { java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, eaa); return ""; } catch (ConnectTimeoutException eaa) { java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, eaa); return ""; } } } int statusCode = response.getStatusLine().getStatusCode(); String respString = ""; HttpEntity entity = null; if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_ACCEPTED) { entity = response.getEntity(); } else { if (statusCode == 503) { java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, "httpStatusCode 503"); return ""; } else if (statusCode == 502) { java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, "httpStatusCode 502"); return ""; } else if (statusCode == 401) { java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, "httpStatusCode 401"); return ""; } else { java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, "PPI 500"); return ""; //throw new ServiceUnavailableException(); } } if (entity != null) { try { respString = EntityUtils.toString(entity); response.close(); } catch (ParseException | IOException e) { java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, "PPI 401"); return ""; } } return respString; }
From source file:de.tudarmstadt.ukp.shibhttpclient.ShibHttpClient.java
/** * Create a new client (with an explicit proxy and possibly transparent authentication) * /*w w w . j av a 2 s. c o m*/ * @param aIdpUrl * the URL of the IdP. Should probably be something ending in "/SAML2/SOAP/ECP" * @param aUsername * the user name to log into the IdP. * @param aPassword * the password to log in to the IdP. * @param aProxy * if not {@code null}, use this proxy instead of the default system proxy (if any) * @param anyCert * if {@code true}, accept any certificate from any remote host. Otherwise, * certificates need to be installed in the JRE. * @param transparentAuth * if {@code true} (default), add a HttpRequestPostProcessor to transparently * authenticate. Otherwise, you must handle the authentication process yourself. */ public ShibHttpClient(String aIdpUrl, String aUsername, String aPassword, HttpHost aProxy, boolean anyCert, boolean transparentAuth) { setIdpUrl(aIdpUrl); setUsername(aUsername); setPassword(aPassword); // Use a pooling connection manager, because we'll have to do a call out to the IdP // while still being in a connection with the SP PoolingHttpClientConnectionManager connMgr; if (anyCert) { try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create().register("http", new PlainConnectionSocketFactory()) .register("https", new SSLConnectionSocketFactory(builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)) .build(); connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry); } catch (GeneralSecurityException e) { // There shouldn't be any of these exceptions, because we do not use an actual // keystore throw new IllegalStateException(e); } } else { connMgr = new PoolingHttpClientConnectionManager(); } connMgr.setMaxTotal(10); connMgr.setDefaultMaxPerRoute(5); // The client needs to remember the auth cookie cookieStore = new BasicCookieStore(); RequestConfig globalRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY) .build(); // Let's throw all common client elements into one builder object HttpClientBuilder customClient = HttpClients.custom().setConnectionManager(connMgr) // The client needs to remember the auth cookie .setDefaultRequestConfig(globalRequestConfig).setDefaultCookieStore(cookieStore) // Add the ECP/PAOS headers - needs to be added first so the cookie we get from // the authentication can be handled by the RequestAddCookies interceptor later .addInterceptorFirst(new HttpRequestPreprocessor()); // Automatically log into IdP if transparent Shibboleth authentication handling is requested (default) if (transparentAuth) { customClient = customClient.addInterceptorFirst(new HttpRequestPostprocessor()); } // Build the client with/without proxy settings if (aProxy == null) { // use the proxy settings of the JVM, if specified client = customClient.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault())) .build(); } else { // use the explicit proxy client = customClient.setProxy(aProxy).build(); } parserPool = new BasicParserPool(); parserPool.setNamespaceAware(true); }
From source file:eu.vital.TrustManager.connectors.dms.DMSManager.java
private String query2(String DMS_endpoint, String postObject) throws NoSuchAlgorithmException, KeyStoreException, IOException, KeyManagementException { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustStrategy() { @Override/*from w ww .j av a2 s . c o m*/ public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }); SSLConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); CloseableHttpClient httpClient = HttpClients.custom().setRedirectStrategy(new LaxRedirectStrategy()) .setSSLSocketFactory(sslSF).build(); HttpPost postRequest = new HttpPost(dms_URL + "/" + DMS_endpoint); postRequest.addHeader("Content-Type", "application/json"); postRequest.addHeader("vitalAccessToken", cookie.substring(17)); HttpEntity entityPost = new StringEntity(postObject, StandardCharsets.UTF_8); postRequest.setEntity(entityPost); CloseableHttpResponse response = httpClient.execute(postRequest); try { //(CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(postRequest)) //System.out.println(response.getStatusLine()); HttpEntity entity = response.getEntity(); if (entity == null) return null; return EntityUtils.toString(entity); //EntityUtils.consume(entity); } catch (IOException | ParseException e) { //logger.error(e.toString()); //throw new ConnectionErrorException("Error in connection with DMSManager"); } return null; }
From source file:org.apache.solr.util.SSLTestConfig.java
/** * Builds a new SSLContext for HTTP <b>clients</b> to use when communicating with servers which have * been configured based on the settings of this object. * * NOTE: Uses a completely insecure {@link SecureRandom} instance to prevent tests from blocking * due to lack of entropy, also explicitly allows the use of self-signed * certificates (since that's what is almost always used during testing). *//*from www .j a v a 2 s .com*/ public SSLContext buildClientSSLContext() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException { assert isSSLMode(); SSLContextBuilder builder = SSLContexts.custom(); builder.setSecureRandom(NotSecurePsuedoRandom.INSTANCE); // NOTE: KeyStore & TrustStore are swapped because they are from configured from server perspective... // we are a client - our keystore contains the keys the server trusts, and vice versa builder.loadTrustMaterial(buildKeyStore(keyStore, getKeyStorePassword()), new TrustSelfSignedStrategy()) .build(); if (isClientAuthMode()) { builder.loadKeyMaterial(buildKeyStore(trustStore, getTrustStorePassword()), getTrustStorePassword().toCharArray()); } return builder.build(); }
From source file:com.dnanexus.DXHTTPRequest.java
/** * Construct the DXHTTPRequest using the given DXEnvironment. *//*w w w.ja va2 s . c o m*/ public DXHTTPRequest(DXEnvironment env) { this.securityContext = env.getSecurityContextJson(); this.apiserver = env.getApiserverPath(); this.disableRetry = env.isRetryDisabled(); SSLContextBuilder builder = new SSLContextBuilder(); try { builder.loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } SSLConnectionSocketFactory sslSF = null; try { sslSF = new SSLConnectionSocketFactory(builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } HttpClientBuilder httpClientBuilder = HttpClients.custom().useSystemProperties(); String proxyHost = System.getProperty("http.proxyHost"); String proxyPort = System.getProperty("http.proxyPort"); String proxyHostS = System.getProperty("https.proxyHost"); String proxyPortS = System.getProperty("https.proxyPort"); if ((proxyHost == null || proxyPort == null) && (proxyHostS == null || proxyPortS == null)) { this.httpclient = HttpClientBuilder.create().setUserAgent(USER_AGENT).build(); } else { HttpHost proxy = null; if (proxyHostS != null && proxyPortS != null) { proxy = new HttpHost(proxyHostS, Integer.parseInt(proxyPortS)); } else { proxy = new HttpHost(proxyHost, Integer.parseInt(proxyPort)); } httpClientBuilder.setProxy(proxy); HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); httpClientBuilder.setRoutePlanner(routePlanner).setSSLSocketFactory(sslSF); httpclient = httpClientBuilder.setUserAgent(USER_AGENT).build(); } }