List of usage examples for org.apache.http.conn.ssl SSLContextBuilder build
public SSLContext build() throws NoSuchAlgorithmException, KeyManagementException
From source file:de.tsystems.mms.apm.performancesignature.viewer.rest.model.CustomJenkinsHttpClient.java
private static HttpClientBuilder createHttpClientBuilder(final boolean verifyCertificate, final CustomProxy customProxy) { HttpClientBuilder httpClientBuilder = HttpClients.custom(); httpClientBuilder.useSystemProperties(); if (!verifyCertificate) { SSLContextBuilder builder = new SSLContextBuilder(); try {//from w ww . j a v a 2s .c o m builder.loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }); httpClientBuilder.setSSLSocketFactory(new SSLConnectionSocketFactory(builder.build())); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { LOGGER.severe(ExceptionUtils.getFullStackTrace(e)); } } if (customProxy != null) { Jenkins jenkins = PerfSigUIUtils.getInstance(); if (customProxy.isUseJenkinsProxy() && jenkins.proxy != null) { final ProxyConfiguration proxyConfiguration = jenkins.proxy; if (StringUtils.isNotBlank(proxyConfiguration.name) && proxyConfiguration.port > 0) { httpClientBuilder.setProxy(new HttpHost(proxyConfiguration.name, proxyConfiguration.port)); if (StringUtils.isNotBlank(proxyConfiguration.getUserName())) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials( proxyConfiguration.getUserName(), proxyConfiguration.getUserName()); credsProvider.setCredentials( new AuthScope(proxyConfiguration.name, proxyConfiguration.port), usernamePasswordCredentials); httpClientBuilder.setDefaultCredentialsProvider(credsProvider); httpClientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy()); } } } else { httpClientBuilder.setProxy(new HttpHost(customProxy.getProxyServer(), customProxy.getProxyPort())); if (StringUtils.isNotBlank(customProxy.getProxyUser()) && StringUtils.isNotBlank(customProxy.getProxyPassword())) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials( customProxy.getProxyUser(), customProxy.getProxyPassword()); credsProvider.setCredentials( new AuthScope(customProxy.getProxyServer(), customProxy.getProxyPort()), usernamePasswordCredentials); httpClientBuilder.setDefaultCredentialsProvider(credsProvider); httpClientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy()); } } } return httpClientBuilder; }
From source file:photosharing.api.ExecutorUtil.java
/** * helper method that returns an HTTPClient executor with credentials * available./*from www . jav a 2s.c o m*/ * * Also enables the test case to connect to ANY SSL Certificate * valid/invalid * * @return {Executor} or Null if there is an issue */ public static Executor getExecutor() { Executor executor = null; /* * if using one of the environments without a trusted CA chain or * you are using Fiddler, you want to set TRUST=TRUE in appconfig.properties */ Configuration config = Configuration.getInstance(null); String sTrust = config.getValue(Configuration.TRUST); boolean trusted = Boolean.parseBoolean(sTrust); if (trusted) { try { HttpClientBuilder builder = HttpClients.custom(); // Setup the SSL Context to Trust Any SSL Certificate SSLContextBuilder sslBuilder = new SSLContextBuilder(); sslBuilder.loadTrustMaterial(null, new TrustStrategy() { /** * override for fiddler proxy */ public boolean isTrusted(X509Certificate[] certs, String host) throws CertificateException { return true; } }); SSLContext sslContext = sslBuilder.build(); builder.setHostnameVerifier(new AllowAllHostnameVerifier()); builder.setSslcontext(sslContext); CloseableHttpClient httpClient = builder.build(); executor = Executor.newInstance(httpClient); } catch (NoSuchAlgorithmException e) { logger.log(Level.SEVERE, "Issue with No Algorithm " + e.toString()); } catch (KeyStoreException e) { logger.log(Level.SEVERE, "Issue with KeyStore " + e.toString()); } catch (KeyManagementException e) { logger.log(Level.SEVERE, "Issue with KeyManagement " + e.toString()); } } return executor; }
From source file:com.ibm.watson.app.common.util.http.HttpClientBuilder.java
public static CloseableHttpClient buildDefaultHttpClient(Credentials cred) { // Use custom cookie store if necessary. CookieStore cookieStore = new BasicCookieStore(); // Use custom credentials provider if necessary. CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); RequestConfig defaultRequestConfig;//w w w .j av a 2 s . c o m //private DefaultHttpClient client; connManager.setMaxTotal(200); connManager.setDefaultMaxPerRoute(50); try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); // Create a registry of custom connection socket factories for supported // protocol schemes. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", new SSLConnectionSocketFactory(builder.build())).build(); } catch (Exception e) { logger.warn(MessageKey.AQWEGA02000W_unable_init_ssl_context.getMessage(), e); } // Create global request configuration defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH) .setExpectContinueEnabled(true) .setTargetPreferredAuthSchemes( Arrays.asList(AuthSchemes.BASIC, AuthSchemes.NTLM, AuthSchemes.DIGEST)) .setAuthenticationEnabled(true).build(); if (cred != null) credentialsProvider.setCredentials(AuthScope.ANY, cred); return HttpClients.custom().setConnectionManager(connManager).setDefaultCookieStore(cookieStore) .setDefaultCredentialsProvider(credentialsProvider).setDefaultRequestConfig(defaultRequestConfig) .build(); }
From source file:org.pepstock.jem.commands.util.HttpUtil.java
/** * It builds a {@link SSLConnectionSocketFactory} if SSL is needed. * //from w w w . j av a 2s . c om * @return the {@link SSLConnectionSocketFactory} for SSL purposes. * @throws KeyManagementException * @throws UnrecoverableKeyException * @throws NoSuchAlgorithmException * @throws KeyStoreException * @see SSLConnectionSocketFactory */ private static SSLConnectionSocketFactory buildSSLConnectionSocketFactory() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException { TrustStrategy ts = new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { // always true to avoid certificate unknown exception return true; } }; SSLContextBuilder builder = SSLContexts.custom(); builder.loadTrustMaterial(null, ts); SSLContext sslContext = builder.build(); return new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); }
From source file:org.apache.cxf.fediz.integrationtests.HTTPTestUtils.java
public static String sendHttpGetForSAMLSSO(String url, String user, String password, int returnCodeIDP, int returnCodeRP, int idpPort) throws Exception { CloseableHttpClient httpClient = null; try {/*from ww w . j av a 2 s . c o m*/ CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope("localhost", idpPort), new UsernamePasswordCredentials(user, password)); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks")); try { trustStore.load(instream, "clientpass".toCharArray()); } finally { try { instream.close(); } catch (Exception ex) { ex.printStackTrace(); } } SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()); sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray()); SSLContext sslContext = sslContextBuilder.build(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setDefaultCredentialsProvider(credsProvider); httpClientBuilder.setSSLSocketFactory(sslSocketFactory); httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy()); httpClient = httpClientBuilder.build(); HttpGet httpget = new HttpGet(url); HttpResponse response = httpClient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: " + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode()); return EntityUtils.toString(entity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources if (httpClient != null) { httpClient.close(); } } }
From source file:org.apache.cxf.fediz.integrationtests.HTTPTestUtils.java
/** * Same as sendHttpGet above, except that we return the HttpClient so that it can * subsequently be re-used (for e.g. logout) *//*from w w w . j a v a2 s. co m*/ public static CloseableHttpClient sendHttpGetForSignIn(String url, String user, String password, int returnCodeIDP, int returnCodeRP, int idpPort) throws Exception { CloseableHttpClient httpClient = null; CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope("localhost", idpPort), new UsernamePasswordCredentials(user, password)); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks")); try { trustStore.load(instream, "clientpass".toCharArray()); } finally { try { instream.close(); } catch (Exception ex) { ex.printStackTrace(); } } SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()); sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray()); SSLContext sslContext = sslContextBuilder.build(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setDefaultCredentialsProvider(credsProvider); httpClientBuilder.setSSLSocketFactory(sslSocketFactory); httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy()); httpClient = httpClientBuilder.build(); HttpGet httpget = new HttpGet(url); HttpResponse response = httpClient.execute(httpget); HttpEntity entity = response.getEntity(); Assert.assertTrue("IDP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: " + returnCodeIDP + "]", returnCodeIDP == response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() != 200) { return null; } // Redirect to a POST is not supported without user interaction // http://www.ietf.org/rfc/rfc2616.txt // If the 301 status code is received in response to a request other // than GET or HEAD, the user agent MUST NOT automatically redirect the // request unless it can be confirmed by the user, since this might // change the conditions under which the request was issued. Source source = new Source(EntityUtils.toString(entity)); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); FormFields formFields = source.getFormFields(); List<Element> forms = source.getAllElements(HTMLElementName.FORM); Assert.assertEquals("Only one form expected but got " + forms.size(), 1, forms.size()); String postUrl = forms.get(0).getAttributeValue("action"); Assert.assertNotNull("Form field 'wa' not found", formFields.get("wa")); Assert.assertNotNull("Form field 'wresult' not found", formFields.get("wresult")); for (FormField formField : formFields) { if (formField.getUserValueCount() != 0) { nvps.add(new BasicNameValuePair(formField.getName(), formField.getValues().get(0))); } } HttpPost httppost = new HttpPost(postUrl); httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); response = httpClient.execute(httppost); entity = response.getEntity(); Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: " + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode()); String responseStr = EntityUtils.toString(entity); Assert.assertTrue("Principal not " + user, responseStr.indexOf("userPrincipal=" + user) > 0); return httpClient; }
From source file:org.apache.cxf.fediz.integrationtests.HTTPTestUtils.java
public static String sendHttpGet(String url, String user, String password, int returnCodeIDP, int returnCodeRP, int idpPort) throws Exception { CloseableHttpClient httpClient = null; try {//from ww w . j a v a2s . co m CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope("localhost", idpPort), new UsernamePasswordCredentials(user, password)); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks")); try { trustStore.load(instream, "clientpass".toCharArray()); } finally { try { instream.close(); } catch (Exception ex) { ex.printStackTrace(); } } SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()); sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray()); SSLContext sslContext = sslContextBuilder.build(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setDefaultCredentialsProvider(credsProvider); httpClientBuilder.setSSLSocketFactory(sslSocketFactory); httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy()); httpClient = httpClientBuilder.build(); HttpGet httpget = new HttpGet(url); HttpResponse response = httpClient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } Assert.assertTrue("IDP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: " + returnCodeIDP + "]", returnCodeIDP == response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() != 200) { return null; } // Redirect to a POST is not supported without user interaction // http://www.ietf.org/rfc/rfc2616.txt // If the 301 status code is received in response to a request other // than GET or HEAD, the user agent MUST NOT automatically redirect the // request unless it can be confirmed by the user, since this might // change the conditions under which the request was issued. Source source = new Source(EntityUtils.toString(entity)); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); FormFields formFields = source.getFormFields(); List<Element> forms = source.getAllElements(HTMLElementName.FORM); Assert.assertEquals("Only one form expected but got " + forms.size(), 1, forms.size()); String postUrl = forms.get(0).getAttributeValue("action"); Assert.assertNotNull("Form field 'wa' not found", formFields.get("wa")); Assert.assertNotNull("Form field 'wresult' not found", formFields.get("wresult")); for (FormField formField : formFields) { if (formField.getUserValueCount() != 0) { nvps.add(new BasicNameValuePair(formField.getName(), formField.getValues().get(0))); } } HttpPost httppost = new HttpPost(postUrl); httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); response = httpClient.execute(httppost); entity = response.getEntity(); System.out.println(response.getStatusLine()); Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: " + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } return EntityUtils.toString(entity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources if (httpClient != null) { httpClient.close(); } } }
From source file:org.apache.cxf.fediz.integrationtests.KerberosTest.java
public static String sendHttpGet(String url, String ticket, int returnCodeIDP, int returnCodeRP, int idpPort) throws Exception { CloseableHttpClient httpClient = null; try {/* www . j a v a 2 s. c o m*/ KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks")); try { trustStore.load(instream, "clientpass".toCharArray()); } finally { try { instream.close(); } catch (Exception ex) { ex.printStackTrace(); } } SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()); sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray()); SSLContext sslContext = sslContextBuilder.build(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setSSLSocketFactory(sslSocketFactory); httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy()); httpClient = httpClientBuilder.build(); HttpGet httpget = new HttpGet(url); httpget.addHeader("Authorization", "Negotiate " + ticket); HttpResponse response = httpClient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } Assert.assertTrue("IDP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: " + returnCodeIDP + "]", returnCodeIDP == response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() != 200) { return null; } // Redirect to a POST is not supported without user interaction // http://www.ietf.org/rfc/rfc2616.txt // If the 301 status code is received in response to a request other // than GET or HEAD, the user agent MUST NOT automatically redirect the // request unless it can be confirmed by the user, since this might // change the conditions under which the request was issued. Source source = new Source(EntityUtils.toString(entity)); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); FormFields formFields = source.getFormFields(); List<Element> forms = source.getAllElements(HTMLElementName.FORM); Assert.assertEquals("Only one form expected but got " + forms.size(), 1, forms.size()); String postUrl = forms.get(0).getAttributeValue("action"); Assert.assertNotNull("Form field 'wa' not found", formFields.get("wa")); Assert.assertNotNull("Form field 'wresult' not found", formFields.get("wresult")); for (FormField formField : formFields) { if (formField.getUserValueCount() != 0) { nvps.add(new BasicNameValuePair(formField.getName(), formField.getValues().get(0))); } } HttpPost httppost = new HttpPost(postUrl); httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); response = httpClient.execute(httppost); entity = response.getEntity(); System.out.println(response.getStatusLine()); Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: " + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } return EntityUtils.toString(entity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources if (httpClient != null) { httpClient.close(); } } }
From source file:com.vmware.vim25.ws.ApacheTrustSelfSigned.java
public static SSLConnectionSocketFactory trust() { SSLContextBuilder builder = new SSLContextBuilder(); log.trace("Set SSL Context Builder to trust self signed certs."); try {// w w w . j a v a2s.co m builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); log.trace("Added Self Signed Strategy to builder."); } catch (NoSuchAlgorithmException e) { log.error("NoSuchAlgorithm caught trying to add SelfSignedStrategy.", e); return null; } catch (KeyStoreException e) { log.error("KeyStoreException caught trying to add TrustSelfSignedStrategy.", e); return null; } SSLConnectionSocketFactory sslConnectionSocketFactory; try { sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build(), new AllowAllHostnameVerifier()); log.trace("Added SSLConnectionSocketFactory to builder."); } catch (NoSuchAlgorithmException e) { log.error("Error trying to trust self signed certs.", e); return null; } catch (KeyManagementException e) { log.error("Error trying to trust self signed certs.", e); return null; } log.trace("Created self signed trust."); return sslConnectionSocketFactory; }
From source file:com.toastcoders.vcumeter.ws.util.ApacheTrustSelfSignedSSL.java
/** * Method that intentionally break SSL by accepting any self signed SSL * certs. This is how the default VMware certs are signed. * * @return//from w ww .ja v a 2 s .c om */ public static SSLConnectionSocketFactory trust() { SSLContextBuilder builder = new SSLContextBuilder(); log.trace("Set SSL Context Builder to trust self signed certs."); try { builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); log.trace("Added Self Signed Strategy to builder."); } catch (NoSuchAlgorithmException e) { log.error("NoSuchAlgorithm caught trying to add SelfSignedStrategy.", e); return null; } catch (KeyStoreException e) { log.error("KeyStoreException caught trying to add TrustSelfSignedStrategy.", e); return null; } SSLConnectionSocketFactory sslConnectionSocketFactory; try { sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build(), new AllowAllHostnameVerifier()); log.trace("Added SSLConnectionSocketFactory to builder."); } catch (NoSuchAlgorithmException e) { log.error("Error trying to trust self signed certs.", e); return null; } catch (KeyManagementException e) { log.error("Error trying to trust self signed certs.", e); return null; } log.trace("Created self signed trust."); return sslConnectionSocketFactory; }