List of usage examples for org.apache.http.conn.ssl SSLContextBuilder loadTrustMaterial
public SSLContextBuilder loadTrustMaterial(final KeyStore truststore, final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException
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// w ww . j a va 2s . 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: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(); // /* w w w . ja 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.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 ww . j a v a 2s.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: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;/* ww 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(); 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: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//ww w . jav a2s. c o 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:org.esbtools.message.admin.common.EsbMessageAdminServiceImpl.java
private Boolean sendMessageToRestEndPoint(String message, List<String> endpoints) { CloseableHttpClient httpClient;// ww w . ja v a2 s. co m 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:com.couchbase.jdbc.core.ProtocolImpl.java
public ProtocolImpl(String url, Properties props) { if (props.containsKey(ConnectionParameters.USER)) { user = props.getProperty(ConnectionParameters.USER); }/*from w w w . j a va 2s.co m*/ if (props.containsKey(ConnectionParameters.PASSWORD)) { password = props.getProperty(ConnectionParameters.PASSWORD); } if (props.containsKey("credentials")) { credentials = props.getProperty("credentials"); } this.url = url; setConnectionTimeout(props.getProperty(ConnectionParameters.CONNECTION_TIMEOUT)); if (props.containsKey(ConnectionParameters.SCAN_CONSISTENCY)) { scanConsistency = props.getProperty(ConnectionParameters.SCAN_CONSISTENCY); } requestConfig = RequestConfig.custom().setConnectionRequestTimeout(0).setConnectTimeout(connectTimeout) .setSocketTimeout(connectTimeout).build(); if (props.containsKey(ConnectionParameters.ENABLE_SSL) && props.getProperty(ConnectionParameters.ENABLE_SSL).equals("true")) { SSLContextBuilder builder = SSLContexts.custom(); try { builder.loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }); SSLContext sslContext = builder.build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() { @Override public void verify(String host, SSLSocket ssl) throws IOException { } @Override public void verify(String host, X509Certificate cert) throws SSLException { } @Override public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException { } @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create().register("https", sslsf).build(); HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry); httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(requestConfig) .build(); ssl = true; } catch (Exception ex) { logger.error("Error creating ssl client", ex); } } else { httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build(); } }
From source file:org.bonitasoft.connectors.rest.RESTConnector.java
/** * Set the request builder based on the request * /*from w w w .j av a 2 s. c o m*/ * @param ssl The request SSL options * @param httpClientBuilder The request builder * @throws Exception */ private void setSSL(final SSL ssl, final HttpClientBuilder httpClientBuilder) throws Exception { if (ssl != null) { final SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); if (ssl.getTrustStore() != null) { final KeyStore trustStore = ssl.getTrustStore().generateKeyStore(); if (ssl.isUseSelfSignedCertificate()) { sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()); } else { sslContextBuilder.loadTrustMaterial(trustStore); } } if (ssl.getKeyStore() != null) { final KeyStore keyStore = ssl.getKeyStore().generateKeyStore(); final String keyStorePassword = ssl.getKeyStore().getPassword(); sslContextBuilder.loadKeyMaterial(keyStore, keyStorePassword.toCharArray()); } sslContextBuilder.setSecureRandom(null); if (ssl.isUseTLS()) { sslContextBuilder.useTLS(); } else { sslContextBuilder.useSSL(); } final SSLVerifier verifier = ssl.getSslVerifier(); X509HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER; switch (verifier) { case BROWSER: hostnameVerifier = SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER; break; case ALLOW: hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; break; case STRICT: hostnameVerifier = SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER; break; default: hostnameVerifier = SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER; break; } final SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( sslContextBuilder.build(), hostnameVerifier); httpClientBuilder.setSSLSocketFactory(socketFactory); } }
From source file:hello.MyPostHTTP.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 = KeyStore.getInstance(service.getTrustStoreType()); try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) { truststore.load(in, service.getTrustStorePassword().toCharArray()); }/*from w ww. j a v a 2s . c om*/ builder = builder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy()); } final String keyFilename = service.getKeyStoreFile(); if (keyFilename != null) { final KeyStore keystore = KeyStore.getInstance(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()); } final SSLContext sslContext = builder.build(); return sslContext; }
From source file:com.kixeye.chassis.transport.HttpTransportTest.java
@Test public void testHttpServiceWithJsonWithHTTPS() throws Exception { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("https.enabled", "true"); properties.put("https.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("https.hostname", "localhost"); properties.put("https.selfSigned", "true"); AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("default", properties)); context.setEnvironment(environment); context.register(PropertySourcesPlaceholderConfigurer.class); context.register(TransportConfiguration.class); context.register(TestRestService.class); try {//from w ww .j ava 2 s . c o m context.refresh(); final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class); SSLContextBuilder builder = SSLContexts.custom(); builder.loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }); SSLContext sslContext = builder.build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() { @Override public void verify(String host, SSLSocket ssl) throws IOException { } @Override public void verify(String host, X509Certificate cert) throws SSLException { } @Override public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException { } @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create().register("https", sslsf).build(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setHttpClient(HttpClients.custom().setConnectionManager(cm).build()); RestTemplate httpClient = new RestTemplate(requestFactory); httpClient.setErrorHandler(new ResponseErrorHandler() { public boolean hasError(ClientHttpResponse response) throws IOException { return response.getRawStatusCode() == HttpStatus.OK.value(); } public void handleError(ClientHttpResponse response) throws IOException { } }); httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR)); httpClient.setMessageConverters(new ArrayList<HttpMessageConverter<?>>( Lists.newArrayList(new SerDeHttpMessageConverter(serDe)))); TestObject response = httpClient.getForObject( new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); response = httpClient.postForObject( new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), new TestObject("more stuff"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); response = httpClient.getForObject( new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); response = httpClient.getForObject( new URI("https://localhost:" + properties.get("https.port") + "/stuff/getFuture"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); response = httpClient.getForObject( new URI("https://localhost:" + properties.get("https.port") + "/stuff/getObservable"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); ResponseEntity<ServiceError> error = httpClient.postForEntity( new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode()); Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code); error = httpClient.getForEntity( new URI("https://localhost:" + properties.get("https.port") + "/stuff/expectedError"), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode()); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description); error = httpClient.getForEntity( new URI("https://localhost:" + properties.get("https.port") + "/stuff/unexpectedError"), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode()); Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code); } finally { context.close(); } }