List of usage examples for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory
public SSLConnectionSocketFactory(final SSLContext sslContext)
From source file:com.nridge.connector.common.con_com.crawl.CrawlStart.java
private CloseableHttpClient createHttpClient() throws NSException { Logger appLogger = mAppMgr.getLogger(this, "createHttpClient"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); // http://hc.apache.org/httpcomponents-client-4.3.x/httpclient/examples/org/apache/http/examples/client/ClientCustomSSL.java // http://stackoverflow.com/questions/19517538/ignoring-ssl-certificate-in-apache-httpclient-4-3 CloseableHttpClient httpClient = null; SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); try {/*from w w w. j a v a 2s. c o m*/ // Note: This logic will trust CA and self-signed certificates. sslContextBuilder.loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] aChain, String anAuthType) throws CertificateException { return true; } }); SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory( sslContextBuilder.build()); httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build(); } catch (Exception e) { String msgStr = String.format("HTTP Client Error: %s", e.getMessage()); appLogger.error(msgStr, e); throw new NSException(msgStr); } appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); return httpClient; }
From source file:de.elomagic.maven.http.HTTPMojo.java
@Override public void execute() throws MojoExecutionException, MojoFailureException { try {/*w w w .java 2 s . c o m*/ Executor executor; if (httpsInsecure) { getLog().info("Accepting unsecure HTTPS connections."); try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustAllStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); final Registry<ConnectionSocketFactory> sfr = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslsf).build(); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager( sfr); connectionManager.setDefaultMaxPerRoute(100); connectionManager.setMaxTotal(200); connectionManager.setValidateAfterInactivity(1000); HttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connectionManager) .build(); executor = Executor.newInstance(httpClient); } catch (Exception ex) { throw new Exception("Unable to setup HTTP client for unstrusted connections.", ex); } } else { executor = Executor.newInstance(); } Settings settings = session.getSettings(); if (StringUtils.isNotBlank(serverId)) { Server server = settings.getServer(serverId); if (server == null) { throw new Exception("Server ID \"" + serverId + "\" not found in your Maven settings.xml"); } getLog().debug("ServerId: " + serverId); executor.auth(server.getUsername(), server.getPassword()); } Request request = createRequestMethod(); request.setHeader("Accept", accept); if (httpHeaders != null) { for (Entry<String, String> entry : httpHeaders.entrySet()) { request.addHeader(entry.getKey(), entry.getValue()); } } if (formParams != null) { Form form = Form.form(); for (Entry<String, String> entry : formParams.entrySet()) { form.add(entry.getKey(), entry.getValue()); } } if (fromFile != null) { if (!fromFile.exists()) { throw new MojoExecutionException("From file \"" + fromFile + "\" doesn't exist."); } if (StringUtils.isBlank(contentType)) { contentType = Files.probeContentType(fromFile.toPath()); } getLog().debug("From file: " + fromFile); getLog().debug("Upload file size: " + FileUtils.byteCountToDisplaySize(new Long(fromFile.length()).intValue())); getLog().debug("Content type: " + contentType); if (StringUtils.isBlank(contentType)) { request.body(new FileEntity(fromFile)); } else { request.body(new FileEntity(fromFile, ContentType.create(contentType))); } } getLog().info(method + " " + url); Response response = executor.execute(request); handleResponse(response); } catch (Exception ex) { getLog().error(ex); if (failOnError) { throw new MojoExecutionException(ex.getMessage(), ex); } else { getLog().info("Fail on error is disabled. Continue execution."); } } }
From source file:org.wso2.carbon.customer_portal.tag.cloud.sample.CustomerService.java
private HttpClient getHttpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); // create a post request to addAPI. return HttpClients.custom().setSSLSocketFactory(sslsf).build(); }
From source file:eu.vital.TrustManager.connectors.ppi.PPIManager.java
private String query(String ppi_endpoint, String body, String method) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException { Cookie ck;/*from w w w . j av a 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(); //httpclient = HttpClients.createDefault(); URI uri = null; try { // Prepare to forward the request to the proxy uri = new URI(ppi_endpoint); } catch (URISyntaxException e1) { //log } 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(3000).setConnectTimeout(3000) .setSocketTimeout(3000).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(PPIManager.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) { // e1.printStackTrace(); } httpaction.setConfig(RequestConfig.custom().setConnectionRequestTimeout(7000) .setConnectTimeout(7000).setSocketTimeout(7000).build()); response = httpclient.execute(httpaction); } catch (ClientProtocolException ea) { java.util.logging.Logger.getLogger(PPIManager.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(PPIManager.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(PPIManager.class.getName()).log(Level.SEVERE, null, eaa); return ""; } catch (Exception eaa) { java.util.logging.Logger.getLogger(PPIManager.class.getName()).log(Level.SEVERE, null, eaa); return ""; //return eaa.getMessage(); } } } int statusCode; try { statusCode = response.getStatusLine().getStatusCode(); } catch (Exception eaa) { java.util.logging.Logger.getLogger(PPIManager.class.getName()).log(Level.SEVERE, null, eaa); return ""; } if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_ACCEPTED) { if (statusCode == 503) { java.util.logging.Logger.getLogger(PPIManager.class.getName()).log(Level.SEVERE, null, "PPI 503"); return ""; } else if (statusCode == 502) { java.util.logging.Logger.getLogger(PPIManager.class.getName()).log(Level.SEVERE, null, "PPI 502"); return ""; } else if (statusCode == 401) { java.util.logging.Logger.getLogger(PPIManager.class.getName()).log(Level.SEVERE, null, "PPI 401"); return ""; } else { java.util.logging.Logger.getLogger(PPIManager.class.getName()).log(Level.SEVERE, null, "PPI 500"); return ""; //throw new ServiceUnavailableException(); } } HttpEntity entity; entity = response.getEntity(); String respString = ""; if (entity != null) { try { respString = EntityUtils.toString(entity); response.close(); return respString; } catch (ParseException | IOException e) { java.util.logging.Logger.getLogger(PPIManager.class.getName()).log(Level.SEVERE, null, "PPI 401"); return ""; } } return respString; }
From source file:eu.europa.ec.markt.dss.validation102853.https.CommonDataLoader.java
private RegistryBuilder<ConnectionSocketFactory> setConnectionManagerSchemeHttps( RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistryBuilder) throws DSSException { try {//from w w w . j a v a 2 s .c o m SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); SSLContext.setDefault(sslContext); final SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory( sslContext); return socketFactoryRegistryBuilder.register("https", sslConnectionSocketFactory); } catch (Exception e) { throw new DSSException(e); } }
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 w w w .j a v a2 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:org.wso2.carbon.buzzword.tag.cloud.sample.BuzzwordDAO.java
private HttpClient getHttpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); // create a post request to addAPI. HttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); return httpclient; }
From source file:org.drugis.addis.config.MainConfig.java
@Bean public HttpClient httpClient(RequestConfig requestConfig) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException { KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream(KEYSTORE_PATH), KEYSTORE_PASSWORD.toCharArray()); String ADDIS_LOCAL = System.getenv("ADDIS_LOCAL"); SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadKeyMaterial(keyStore, KEYSTORE_PASSWORD.toCharArray()); if (ADDIS_LOCAL != null) { String TRUSTSTORE_PATH = WebConstants.loadSystemEnv("TRUSTSTORE_PATH"); sslContextBuilder.loadTrustMaterial(new File(TRUSTSTORE_PATH)); }//from ww w . j ava 2 s . c om sslContextBuilder.build(); SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory( sslContextBuilder.build()); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", connectionSocketFactory).register("http", new PlainConnectionSocketFactory()) .build(); HttpClientConnectionManager clientConnectionManager = new PoolingHttpClientConnectionManager(registry); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); return httpClientBuilder.setConnectionManager(clientConnectionManager).setMaxConnTotal(20) .setMaxConnPerRoute(2).setDefaultRequestConfig(requestConfig).build(); }
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 {// w w w.ja va2s. com 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.openhim.mediator.engine.connectors.HTTPConnector.java
private CloseableHttpClient getHttpClient(final MediatorHTTPRequest req) { if (sslContext != null && "https".equalsIgnoreCase(req.getScheme())) { SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext); return HttpClients.custom().setSSLSocketFactory(sslsf).build(); } else {/* w w w . jav a 2 s .c om*/ return HttpClients.createDefault(); } }