List of usage examples for org.apache.http.conn.ssl SSLContextBuilder SSLContextBuilder
public SSLContextBuilder()
From source file:com.esri.geoevent.test.performance.provision.GeoEventProvisioner.java
private SSLConnectionSocketFactory getSSLSocketFactory() { KeyStore trustStore;/*from ww w. j ava 2 s. c om*/ try { trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); TrustStrategy trustStrategy = new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }; SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(trustStore, trustStrategy); sslContextBuilder.useTLS(); SSLContext sslContext = sslContextBuilder.build(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext); return sslSocketFactory; } catch (GeneralSecurityException | IOException e) { System.err.println("SSL Error : " + e.getMessage()); } return null; }
From source file:org.piwigo.remotesync.api.client.WSClient.java
protected CloseableHttpClient getHttpClient() throws Exception { if (httpClient == null) { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); if (clientConfiguration.getUsesProxy()) { String proxyUrl = clientConfiguration.getProxyUrl(); int proxyPort = clientConfiguration.getProxyPort(); String proxyUsername = clientConfiguration.getProxyUsername(); String proxyPassword = clientConfiguration.getProxyPassword(); if (proxyUsername != null && proxyUsername.length() > 0 && proxyPassword != null && proxyPassword.length() > 0) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(proxyUrl, proxyPort), new UsernamePasswordCredentials(proxyUsername, proxyPassword)); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); }//w w w .ja v a 2s . c o m HttpHost proxy = new HttpHost(proxyUrl, proxyPort); requestConfig = RequestConfig.custom().setProxy(proxy).build(); } if (clientConfiguration.getTrustSSLCertificates()) { SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(null, new TrustSSLCertificatesStrategy()); httpClientBuilder.setSSLSocketFactory(new SSLConnectionSocketFactory(sslContextBuilder.build())); } httpClient = httpClientBuilder.build(); } return httpClient; }
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 .ja va 2 s . c om*/ 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.maven.wagon.providers.http.AbstractHttpClientWagon.java
private static PoolingHttpClientConnectionManager createConnManager() { String sslProtocolsStr = System.getProperty("https.protocols"); String cipherSuitesStr = System.getProperty("https.cipherSuites"); String[] sslProtocols = sslProtocolsStr != null ? sslProtocolsStr.split(" *, *") : null; String[] cipherSuites = cipherSuitesStr != null ? cipherSuitesStr.split(" *, *") : null; SSLConnectionSocketFactory sslConnectionSocketFactory; if (SSL_INSECURE) { try {/*from w ww . ja va 2 s. c om*/ SSLContext sslContext = new SSLContextBuilder().useSSL() .loadTrustMaterial(null, new RelaxedTrustStrategy(IGNORE_SSL_VALIDITY_DATES)).build(); sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, sslProtocols, cipherSuites, SSL_ALLOW_ALL ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER : SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); } catch (Exception ex) { throw new SSLInitializationException(ex.getMessage(), ex); } } else { sslConnectionSocketFactory = new SSLConnectionSocketFactory( HttpsURLConnection.getDefaultSSLSocketFactory(), sslProtocols, cipherSuites, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); } Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", sslConnectionSocketFactory).build(); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry); if (PERSISTENT_POOL) { connManager.setDefaultMaxPerRoute(MAX_CONN_PER_ROUTE); connManager.setMaxTotal(MAX_CONN_TOTAL); } else { connManager.setMaxTotal(1); } return connManager; }
From source file:org.apache.maven.wagon.providers.http.AbstractHttpClientWagonFixed.java
@SuppressWarnings("checkstyle:linelength") private static PoolingHttpClientConnectionManager createConnManager() { String sslProtocolsStr = System.getProperty("https.protocols"); String cipherSuitesStr = System.getProperty("https.cipherSuites"); String[] sslProtocols = sslProtocolsStr != null ? sslProtocolsStr.split(" *, *") : null; String[] cipherSuites = cipherSuitesStr != null ? cipherSuitesStr.split(" *, *") : null; SSLConnectionSocketFactory sslConnectionSocketFactory; if (SSL_INSECURE) { try {/*from w w w . ja va 2 s. c o m*/ SSLContext sslContext = new SSLContextBuilder().useSSL() .loadTrustMaterial(null, new RelaxedTrustStrategy(IGNORE_SSL_VALIDITY_DATES)).build(); sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, sslProtocols, cipherSuites, SSL_ALLOW_ALL ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER : SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); } catch (Exception ex) { throw new SSLInitializationException(ex.getMessage(), ex); } } else { sslConnectionSocketFactory = new SSLConnectionSocketFactory( HttpsURLConnection.getDefaultSSLSocketFactory(), sslProtocols, cipherSuites, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); } Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", sslConnectionSocketFactory).build(); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry); if (persistentPool) { connManager.setDefaultMaxPerRoute(MAX_CONN_PER_ROUTE); connManager.setMaxTotal(MAX_CONN_TOTAL); } else { connManager.setMaxTotal(1); } return connManager; }
From source file:org.kuali.rice.ksb.messaging.serviceconnectors.DefaultHttpClientConfigurer.java
/** * Builds the {@link SSLConnectionSocketFactory} used in the connection manager's socket factory registry. * * <p>Note that if {@link org.kuali.rice.ksb.util.KSBConstants.Config#KSB_ALLOW_SELF_SIGNED_SSL} is set to true * in the project configuration, this connection factory will be configured to accept self signed certs even if * the hostname doesn't match.</p> * * @return the SSLConnectionSocketFactory *///from www . ja v a2s. com protected SSLConnectionSocketFactory buildSslConnectionSocketFactory() { SSLContextBuilder builder = new SSLContextBuilder(); if (ConfigContext.getCurrentContextConfig() .getBooleanProperty(KSBConstants.Config.KSB_ALLOW_SELF_SIGNED_SSL)) { try { // allow self signed certs builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); } catch (NoSuchAlgorithmException e) { throw new RiceRuntimeException(e); } catch (KeyStoreException e) { throw new RiceRuntimeException(e); } } SSLConnectionSocketFactory sslsf = null; try { if (ConfigContext.getCurrentContextConfig() .getBooleanProperty(KSBConstants.Config.KSB_ALLOW_SELF_SIGNED_SSL)) { // allow certs that don't match the hostname sslsf = new SSLConnectionSocketFactory(builder.build(), new AllowAllHostnameVerifier()); } else { sslsf = new SSLConnectionSocketFactory(builder.build()); } } catch (NoSuchAlgorithmException e) { throw new RiceRuntimeException(e); } catch (KeyManagementException e) { throw new RiceRuntimeException(e); } return sslsf; }
From source file:org.esbtools.message.admin.common.EsbMessageAdminServiceImpl.java
private Boolean sendMessageToRestEndPoint(String message, List<String> endpoints) { CloseableHttpClient httpClient;//from ww w.j av a 2s. com try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); for (String restEndPoint : endpoints) { try { HttpPost httpPost = new HttpPost(restEndPoint); httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); httpPost.setEntity(new StringEntity(message.toString())); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) { // status is Success by default return true; } else { // try another host LOG.warn("Message failed to transmit, received HTTP response code:" + httpResponse.getStatusLine().getStatusCode() + " with message:" + httpResponse.getEntity().toString() + " from:" + restEndPoint); } } catch (IOException e) { LOG.error(e.getMessage(), e); } } httpClient.close(); } catch (Exception e) { LOG.error(e.getMessage()); } return false; }
From source file:org.wso2.greg.plugin.Utils.java
/** * Method to initialize the http client. We use only one instance of http client since there can not be concurrent * invocations// w w w. j a v a 2 s.c om * * @return @link{HttpClient} httpClient instance */ public static HttpClient getHttpClient() { HttpClient httpClient = null; try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build()); httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build(); } catch (NoSuchAlgorithmException e) { log.error("Unable to load the trust store", e); } catch (KeyStoreException e) { log.error("Unable to get the key store instance", e); } catch (KeyManagementException e) { log.error("Unable to load trust store material", e); } return httpClient; }
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 {//from ww w. j av a 2 s . c om 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(); } } }