List of usage examples for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory
public SSLConnectionSocketFactory(final javax.net.ssl.SSLSocketFactory socketfactory, final X509HostnameVerifier hostnameVerifier)
From source file:org.apache.manifoldcf.crawler.connectors.wiki.WikiConnector.java
protected void getSession() throws ManifoldCFException, ServiceInterruption { if (hasBeenSetup == false) { String emailAddress = params.getParameter(WikiConfig.PARAM_EMAIL); if (emailAddress != null) userAgent = "Mozilla/5.0 (ApacheManifoldCFWikiReader; " + ((emailAddress == null) ? "" : emailAddress) + ")"; else//from w ww.j a v a 2 s .c o m userAgent = null; String protocol = params.getParameter(WikiConfig.PARAM_PROTOCOL); if (protocol == null || protocol.length() == 0) protocol = "http"; String portString = params.getParameter(WikiConfig.PARAM_PORT); if (portString == null || portString.length() == 0) portString = null; String path = params.getParameter(WikiConfig.PARAM_PATH); if (path == null) path = "/w"; baseURL = protocol + "://" + server + ((portString != null) ? ":" + portString : "") + path + "/api.php?format=xml&"; int socketTimeout = 900000; int connectionTimeout = 300000; javax.net.ssl.SSLSocketFactory httpsSocketFactory = KeystoreManagerFactory .getTrustingSecureSocketFactory(); SSLConnectionSocketFactory myFactory = new SSLConnectionSocketFactory( new InterruptibleSocketFactory(httpsSocketFactory, connectionTimeout), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // Set up connection manager connectionManager = new PoolingHttpClientConnectionManager(); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); if (accessUser != null && accessUser.length() > 0 && accessPassword != null) { Credentials credentials = new UsernamePasswordCredentials(accessUser, accessPassword); if (accessRealm != null && accessRealm.length() > 0) credentialsProvider.setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, accessRealm), credentials); else credentialsProvider.setCredentials(AuthScope.ANY, credentials); } RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true) .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true) .setExpectContinueEnabled(true).setConnectTimeout(connectionTimeout) .setConnectionRequestTimeout(socketTimeout); // If there's a proxy, set that too. if (proxyHost != null && proxyHost.length() > 0) { int proxyPortInt; if (proxyPort != null && proxyPort.length() > 0) { try { proxyPortInt = Integer.parseInt(proxyPort); } catch (NumberFormatException e) { throw new ManifoldCFException("Bad number: " + e.getMessage(), e); } } else proxyPortInt = 8080; // Configure proxy authentication if (proxyUsername != null && proxyUsername.length() > 0) { if (proxyPassword == null) proxyPassword = ""; if (proxyDomain == null) proxyDomain = ""; credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPortInt), new NTCredentials(proxyUsername, proxyPassword, currentHost, proxyDomain)); } HttpHost proxy = new HttpHost(proxyHost, proxyPortInt); requestBuilder.setProxy(proxy); } httpClient = HttpClients.custom().setConnectionManager(connectionManager).setMaxConnTotal(1) .disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build()) .setDefaultSocketConfig( SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build()) .setDefaultCredentialsProvider(credentialsProvider).setSSLSocketFactory(myFactory) .setRequestExecutor(new HttpRequestExecutor(socketTimeout)).build(); /* BasicHttpParams params = new BasicHttpParams(); params.setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,true); params.setIntParameter(CoreProtocolPNames.WAIT_FOR_CONTINUE,socketTimeout); params.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY,true); params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK,true); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,socketTimeout); params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,connectionTimeout); params.setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS,true); DefaultHttpClient localHttpClient = new DefaultHttpClient(connectionManager,params); // No retries localHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() { public boolean retryRequest( IOException exception, int executionCount, HttpContext context) { return false; } }); */ loginToAPI(); hasBeenSetup = true; } }
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 w ww . j av a 2s . c o m 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:net.maritimecloud.identityregistry.keycloak.spi.eventprovider.McEventListenerProvider.java
private CloseableHttpClient buildHttpClient() { KeyStore keyStore = null;// w w w .ja v a 2 s .c om KeyStore trustStore = null; FileInputStream instreamKeystore = null; FileInputStream instreamTruststore = null; try { keyStore = KeyStore.getInstance("jks"); instreamKeystore = new FileInputStream(keystorePath); keyStore.load(instreamKeystore, keystorePassword.toCharArray()); if (truststorePath != null && !truststorePath.isEmpty()) { trustStore = KeyStore.getInstance("jks"); instreamTruststore = new FileInputStream(truststorePath); trustStore.load(instreamTruststore, truststorePassword.toCharArray()); } } catch (NoSuchAlgorithmException e) { log.error("Threw exception", e); return null; } catch (CertificateException e) { log.error("Threw exception", e); return null; } catch (IOException e) { log.error("Threw exception", e); return null; } catch (KeyStoreException e) { log.error("Threw exception", e); return null; } finally { try { if (instreamKeystore != null) { instreamKeystore.close(); } if (instreamTruststore != null) { instreamTruststore.close(); } } catch (IOException e) { log.error("Threw exception", e); } } // Trust own CA and all self-signed certs SSLContext sslcontext; try { SSLContextBuilder sslContextBuilder = SSLContexts.custom(); sslContextBuilder.loadKeyMaterial(keyStore, keystorePassword.toCharArray()); // If you have a trust store - should only be needed when the site we contact use self-signed certificates. if (trustStore != null) { sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()); } sslContextBuilder.loadKeyMaterial(keyStore, keystorePassword.toCharArray()); sslcontext = sslContextBuilder.build(); } catch (KeyManagementException e) { log.error("Threw exception", e); return null; } catch (UnrecoverableKeyException e) { log.error("Threw exception", e); return null; } catch (NoSuchAlgorithmException e) { log.error("Threw exception", e); return null; } catch (KeyStoreException e) { log.error("Threw exception", e); return null; } SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new NoopHostnameVerifier()); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); return httpclient; }
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 w w . j a v a 2 s. c om*/ 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(); } }
From source file:com.bosch.iot.things.example.historian.Controller.java
private synchronized CloseableHttpClient getHttpClient() { if (theHttpClient == null) { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); // #### ONLY FOR TEST: Trust ANY certificate (self certified, any chain, ...) try {/* w w w . j a v a2s . co m*/ SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true) .build(); httpClientBuilder.setSSLContext(sslContext); // #### ONLY FOR TEST: Do NOT verify hostname SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslConnectionSocketFactory).build(); PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager( socketFactoryRegistry); httpClientBuilder.setConnectionManager(httpClientConnectionManager); } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException ex) { java.util.logging.Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex); } Properties config = getConfig(); if (config.getProperty("http.proxyHost") != null) { httpClientBuilder.setProxy(new HttpHost(config.getProperty("http.proxyHost"), Integer.parseInt(config.getProperty("http.proxyPort")))); } if (config.getProperty("http.proxyUser") != null) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope(HttpHost.create(getConfig().getProperty("thingsServiceEndpointUrl"))), new UsernamePasswordCredentials(config.getProperty("http.proxyUser"), config.getProperty("http.proxyPwd"))); httpClientBuilder.setDefaultCredentialsProvider(credsProvider); } theHttpClient = httpClientBuilder.build(); } return theHttpClient; }
From source file:com.spotify.docker.client.DefaultDockerClient.java
private Registry<ConnectionSocketFactory> getSchemeRegistry(final Builder builder) { final SSLConnectionSocketFactory https; if (builder.dockerCertificates == null) { https = SSLConnectionSocketFactory.getSocketFactory(); } else {/*from ww w . j a v a 2 s . c om*/ https = new SSLConnectionSocketFactory(builder.dockerCertificates.sslContext(), builder.dockerCertificates.hostnameVerifier()); } final RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder .<ConnectionSocketFactory>create().register("https", https) .register("http", PlainConnectionSocketFactory.getSocketFactory()); if (builder.uri.getScheme().equals(UNIX_SCHEME)) { registryBuilder.register(UNIX_SCHEME, new UnixConnectionSocketFactory(builder.uri)); } return registryBuilder.build(); }
From source file:com.liferay.sync.engine.session.Session.java
private static SSLConnectionSocketFactory _getTrustingSSLSocketFactory() throws Exception { if (_trustingSSLSocketFactory == null) { SSLContextBuilder sslContextBuilder = SSLContexts.custom(); sslContextBuilder.loadTrustMaterial(new TrustStrategy() { @Override//from ww w . j av a 2 s. co m public boolean isTrusted(X509Certificate[] x509Certificates, String authType) { return true; } }); _trustingSSLSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), new NoopHostnameVerifier()); } return _trustingSSLSocketFactory; }
From source file:br.com.intercomex.ws.GnreLoteRecepcao.java
@WebMethod(operationName = "processarSimples") public String processarSimples(@WebParam(name = "gnreDadosMsg") Object TLoteGNRE) { br.gov.pe.gnre.TRetLoteGNRE retorno = null; String recibo = null;//from ww w .j a v a 2s.co m try { loadConfig(); XmlUtil util = new XmlUtil(); //<TConsultaConfigUf xmlns=\"http://www.gnre.pe.gov.br\"><ambiente>1</ambiente><uf>MG</uf><receita>100048</receita></TConsultaConfigUf> //String gnreDadosMsgSTR= util.convertToXml(TLoteGNRE, br.gov.pe.gnre.TLoteGNRE.class); System.out.println("PARAMETRO envio ==== " + TLoteGNRE); String gnreDadosMsgSTR = util.nodeToString((Node) TLoteGNRE); String XML_DATA = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:gnr=\"http://www.gnre.pe.gov.br/webservice/GnreLoteRecepcao\">" + "<soap:Header><gnr:gnreCabecMsg><gnr:versaoDados>1.00</gnr:versaoDados></gnr:gnreCabecMsg></soap:Header>" + "<soap:Body><gnr:gnreDadosMsg>" + gnreDadosMsgSTR + "</gnr:gnreDadosMsg></soap:Body></soap:Envelope>"; System.out.println("PARAMETRO envio ==== " + XML_DATA); HttpPost httpPost = new HttpPost(url); httpPost.setHeader(new BasicHeader("Content-Type", "application/soap+xml;charset=UTF-8")); httpPost.setHeader(new BasicHeader("SOAPAction", action)); StringEntity s = new StringEntity(XML_DATA, "UTF-8"); httpPost.setEntity(s); FileInputStream instream = null; FileInputStream instreamTrust = null; KeyStore keyStore = KeyStore.getInstance("PKCS12"); instream = new FileInputStream(new File(caminhoDoCertificadoDoCliente)); keyStore.load(instream, senhaDoCertificadoDoCliente.toCharArray()); KeyStore trustStore = KeyStore.getInstance("JKS"); instreamTrust = new FileInputStream(new File(arquivoCacertsGeradoParaCadaEstado)); trustStore.load(instreamTrust, senhaDoCertificadoDoCliente.toCharArray()); SSLContextBuilder builder = SSLContexts.custom().loadTrustMaterial(trustStore); builder.loadKeyMaterial(keyStore, senhaDoCertificadoDoCliente.toCharArray()); SSLContext sslcontext = builder.build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); CloseableHttpClient httpclientSLL = HttpClients.custom().setSSLSocketFactory(sslsf).build(); System.out.println("executing request" + httpPost.getRequestLine()); HttpResponse response = httpclientSLL.execute(httpPost); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); String retornoStr = EntityUtils.toString(entity); System.out.println("Response " + retornoStr); retorno = util.getTRetLoteGNRE(retornoStr); recibo = util.getRecibo(retornoStr); System.out.println("ResponseOBJ " + retorno.getAmbiente()); recibo = retorno.getRecibo().getNumero(); } if (entity != null) { entity.consumeContent(); } httpclient.getConnectionManager().shutdown(); } catch (UnsupportedEncodingException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (KeyStoreException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (FileNotFoundException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (CertificateException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (UnrecoverableKeyException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } catch (KeyManagementException ex) { Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex); } return recibo; }
From source file:se.skltp.adapterservices.druglogistics.dosdispensing.RetryComponent.java
private Registry<ConnectionSocketFactory> setupSSLSocketFactory() { try {/*from w w w . ja va2 s.c om*/ KeyStore keystore = loadKeystore(keystorePath, keystorePassword.toCharArray(), keystoreType); char[] keyPassword = keystorePassword.toCharArray(); KeyStore truststore = loadKeystore(truststorePath, truststorePassword.toCharArray(), truststoreType); SSLContext sslContext = SSLContexts.custom().loadKeyMaterial(keystore, keyPassword) .loadTrustMaterial(truststore).build(); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create().register("https", new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)) .build(); return socketFactoryRegistry; } catch (Exception e) { throw new RuntimeException(e); } }