List of usage examples for org.apache.http.impl.client HttpClientBuilder setSSLSocketFactory
public final HttpClientBuilder setSSLSocketFactory(final LayeredConnectionSocketFactory sslSocketFactory)
From source file:com.floragunn.searchguard.httpclient.HttpClient.java
private final CloseableHttpClient createHTTPClient() throws NoSuchAlgorithmException, KeyStoreException, CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException, KeyManagementException { // basic auth // pki auth//from ww w.java 2 s . c o m // kerberos auth final org.apache.http.impl.client.HttpClientBuilder hcb = HttpClients.custom(); if (ssl) { final SSLContextBuilder sslContextbBuilder = SSLContexts.custom().useTLS(); if (log.isTraceEnabled()) { log.trace("Configure HTTP client with SSL"); } if (trustStore != null) { final KeyStore myTrustStore = KeyStore .getInstance(trustStore.getName().endsWith("jks") ? "JKS" : "PKCS12"); myTrustStore.load(new FileInputStream(trustStore), truststorePassword == null || truststorePassword.isEmpty() ? null : truststorePassword.toCharArray()); sslContextbBuilder.loadTrustMaterial(myTrustStore); } if (keystore != null) { final KeyStore keyStore = KeyStore .getInstance(keystore.getName().endsWith("jks") ? "JKS" : "PKCS12"); keyStore.load(new FileInputStream(keystore), keystorePassword == null || keystorePassword.isEmpty() ? null : keystorePassword.toCharArray()); sslContextbBuilder.loadKeyMaterial(keyStore, keystorePassword == null || keystorePassword.isEmpty() ? null : keystorePassword.toCharArray()); } final SSLContext sslContext = sslContextbBuilder.build(); final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1.1", "TLSv1.2" }, null, verifyHostnames ? SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER : SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); hcb.setSSLSocketFactory(sslsf); } /*if (keytab != null) { //System.setProperty("java.security.auth.login.config", "login.conf"); //System.setProperty("java.security.krb5.conf", "krb5.conf"); final CredentialsProvider credsProvider = new BasicCredentialsProvider(); //SPNEGO/Kerberos setup log.debug("SPNEGO activated"); final AuthSchemeProvider nsf = new LoginSPNegoSchemeFactory(true); final Credentials jaasCreds = new JaasCredentials(); credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.SPNEGO), jaasCreds); credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.NTLM), new NTCredentials("Guest", "Guest", "Guest", "Guest")); final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create() .register(AuthSchemes.SPNEGO, nsf).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).build(); hcb.setDefaultAuthSchemeRegistry(authSchemeRegistry); hcb.setDefaultCredentialsProvider(credsProvider); }*/ if (basicCredentials != null) { hcb.setDefaultHeaders( Lists.newArrayList(new BasicHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicCredentials))); } return hcb.build(); }
From source file:com.cisco.oss.foundation.http.netlifx.apache.ApacheNetflixHttpClient.java
protected void configureClient() { clientConfig = new DefaultClientConfigImpl(); clientConfig.loadProperties(getApiName()); setLoadBalancer(loadBalancer);//from w w w .j a v a2 s .c om // clientConfig.set(CommonClientConfigKey.NIWSServerListClassName, DiscoveryEnabledNIWSServerList.class.getName()); // clientConfig.set(IClientConfigKey.Keys.DeploymentContextBasedVipAddresses, metadata.getServiceName()); // clientConfig.set(CommonClientConfigKey.NFLoadBalancerRuleClassName, RoundRobinRule.class.getName()); // clientConfig.set(CommonClientConfigKey.NFLoadBalancerPingClassName, NIWSDiscoveryPing.class.getName()); // clientConfig.set(CommonClientConfigKey.VipAddressResolverClassName, SimpleVipAddressResolver.class.getName()); if (DiscoveryManager.getInstance().getDiscoveryClient() == null && startEurekaClient) { EurekaInstanceConfig eurekaInstanceConfig = new MyDataCenterInstanceConfig(getApiName()); EurekaClientConfig eurekaClientConfig = new DefaultEurekaClientConfig(getApiName() + "."); DiscoveryManager.getInstance().initComponent(eurekaInstanceConfig, eurekaClientConfig); } loadBalancer.initWithNiwsConfig(clientConfig); // if (HystrixPlugins.getInstance().getMetricsPublisher() == null) { // HystrixPlugins.getInstance().registerMetricsPublisher(HystrixMetricsPublisherDefault.getInstance()); // } RequestConfig.Builder requestBuilder = RequestConfig.custom(); requestBuilder = requestBuilder.setConnectTimeout(metadata.getConnectTimeout()); requestBuilder = requestBuilder.setSocketTimeout(metadata.getReadTimeout()); requestBuilder = requestBuilder.setStaleConnectionCheckEnabled(metadata.isStaleConnectionCheckEnabled()); RequestConfig requestConfig = requestBuilder.build(); boolean addSslSupport = StringUtils.isNotEmpty(metadata.getKeyStorePath()) && StringUtils.isNotEmpty(metadata.getKeyStorePassword()); boolean addTrustSupport = StringUtils.isNotEmpty(metadata.getTrustStorePath()) && StringUtils.isNotEmpty(metadata.getTrustStorePassword()); autoCloseable = metadata.isAutoCloseable(); autoEncodeUri = metadata.isAutoEncodeUri(); followRedirects = metadata.isFollowRedirects(); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); SSLContext sslContext = null; try { String keystoreType = "JKS"; if (addSslSupport && addTrustSupport) { KeyStore keyStore = KeyStore.getInstance(keystoreType); keyStore.load(new FileInputStream(metadata.getKeyStorePath()), metadata.getKeyStorePassword().toCharArray()); KeyStore trustStore = KeyStore.getInstance(keystoreType); trustStore.load(new FileInputStream(metadata.getTrustStorePath()), metadata.getTrustStorePassword().toCharArray()); sslContext = SSLContexts.custom().useProtocol("TLS") .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray()) .loadTrustMaterial(trustStore, null).build(); } else if (addSslSupport) { TrustManagerFactory tmf = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore keyStore = KeyStore.getInstance(keystoreType); keyStore.load(new FileInputStream(metadata.getKeyStorePath()), metadata.getKeyStorePassword().toCharArray()); tmf.init(keyStore); sslContext = SSLContexts.custom().useProtocol("SSL") .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray()).build(); sslContext.init(null, tmf.getTrustManagers(), null); SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); httpClientBuilder.setSSLSocketFactory(sf); } else if (addTrustSupport) { KeyStore trustStore = KeyStore.getInstance(keystoreType); trustStore.load(new FileInputStream(metadata.getTrustStorePath()), metadata.getTrustStorePassword().toCharArray()); sslContext = SSLContexts.custom().useProtocol("TLS").loadTrustMaterial(trustStore, null).build(); } if (addSslSupport | addTrustSupport) { SSLContext.setDefault(sslContext); httpClientBuilder.setSslcontext(sslContext); } } catch (Exception e) { LOGGER.error("can't set TLS Support. Error is: {}", e, e); } httpClientBuilder.setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress()) .setMaxConnTotal(metadata.getMaxConnectionsTotal()).setDefaultRequestConfig(requestConfig) .evictExpiredConnections().evictIdleConnections(metadata.getIdleTimeout(), TimeUnit.MILLISECONDS) .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout())); HttpAsyncClientBuilder httpAsyncClientBuilder = HttpAsyncClients.custom(); httpAsyncClientBuilder.setDefaultRequestConfig(requestConfig) .setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress()) .setMaxConnTotal(metadata.getMaxConnectionsTotal()) .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout())) .setSSLContext(sslContext); if (metadata.isDisableCookies()) { httpClientBuilder.disableCookieManagement(); httpAsyncClientBuilder.disableCookieManagement(); } if (hostnameVerifier != null) { httpClientBuilder.setSSLHostnameVerifier(hostnameVerifier); httpAsyncClientBuilder.setSSLHostnameVerifier(hostnameVerifier); } if (!followRedirects) { httpClientBuilder.disableRedirectHandling(); } httpClient = httpClientBuilder.build(); httpAsyncClient = httpAsyncClientBuilder.build(); httpAsyncClient.start(); }
From source file:org.bonitasoft.connectors.rest.RESTConnector.java
/** * Set the request builder based on the request * //from w w w .java2 s. co 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:com.petalmd.armor.AbstractUnitTest.java
protected final HeaderAwareJestHttpClient getJestClient(final String serverUri, final String username, final String password) throws Exception {// http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html final CredentialsProvider credsProvider = new BasicCredentialsProvider(); final HttpClientConfig clientConfig1 = new HttpClientConfig.Builder(serverUri).multiThreaded(true).build(); // Construct a new Jest client according to configuration via factory final HeaderAwareJestClientFactory factory1 = new HeaderAwareJestClientFactory(); factory1.setHttpClientConfig(clientConfig1); final HeaderAwareJestHttpClient c = factory1.getObject(); final HttpClientBuilder hcb = HttpClients.custom(); if (username != null) { credsProvider.setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(username, password)); }//from w ww .j a va2s.c o m if (useSpnego) { //SPNEGO/Kerberos setup log.debug("SPNEGO activated"); final AuthSchemeProvider nsf = new SPNegoSchemeFactory(true, false);// new NegotiateSchemeProvider(); final Credentials jaasCreds = new JaasCredentials(); credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.SPNEGO), jaasCreds); credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.NTLM), new NTCredentials("Guest", "Guest", "Guest", "Guest")); final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, nsf).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).build(); hcb.setDefaultAuthSchemeRegistry(authSchemeRegistry); } hcb.setDefaultCredentialsProvider(credsProvider); if (serverUri.startsWith("https")) { log.debug("Configure Jest with SSL"); final KeyStore myTrustStore = KeyStore.getInstance("JKS"); myTrustStore.load(new FileInputStream(SecurityUtil.getAbsoluteFilePathFromClassPath("ArmorTS.jks")), "changeit".toCharArray()); final KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream(SecurityUtil.getAbsoluteFilePathFromClassPath("ArmorKS.jks")), "changeit".toCharArray()); final SSLContext sslContext = SSLContexts.custom().useTLS() .loadKeyMaterial(keyStore, "changeit".toCharArray()).loadTrustMaterial(myTrustStore).build(); String[] protocols = null; if (enableSSLv3Only) { protocols = new String[] { "SSLv3" }; } else { protocols = SecurityUtil.ENABLED_SSL_PROTOCOLS; } final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, protocols, SecurityUtil.ENABLED_SSL_CIPHERS, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); hcb.setSSLSocketFactory(sslsf); } hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build()); final CloseableHttpClient httpClient = hcb.build(); c.setHttpClient(httpClient); return c; }
From source file:lucee.runtime.tag.Http.java
private void ssl(HttpClientBuilder builder) throws PageException { try {// w ww. j av a2 s. c om // SSLContext sslcontext = SSLContexts.createSystemDefault(); SSLContext sslcontext = SSLContext.getInstance("TLSv1.2"); if (!StringUtil.isEmpty(this.clientCert)) { if (this.clientCertPassword == null) this.clientCertPassword = ""; File ksFile = new File(this.clientCert); KeyStore clientStore = KeyStore.getInstance("PKCS12"); clientStore.load(new FileInputStream(ksFile), this.clientCertPassword.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(clientStore, this.clientCertPassword.toCharArray()); sslcontext.init(kmf.getKeyManagers(), null, new java.security.SecureRandom()); } else { sslcontext.init(null, null, new java.security.SecureRandom()); } final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactoryImpl(sslcontext, new DefaultHostnameVerifierImpl()); builder.setSSLSocketFactory(sslsf); Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslsf) .build(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager( new DefaultHttpClientConnectionOperatorImpl(reg), null, -1, TimeUnit.MILLISECONDS); // TODO review -1 setting builder.setConnectionManager(cm); } catch (Exception e) { throw Caster.toPageException(e); } }
From source file:org.apache.manifoldcf.crawler.connectors.sharepoint.SharePointRepository.java
/** Set up a session */ protected void getSession() throws ManifoldCFException { if (proxy == null) { String serverVersion = params.getParameter(SharePointConfig.PARAM_SERVERVERSION); if (serverVersion == null) serverVersion = "4.0"; supportsItemSecurity = !serverVersion.equals("2.0"); dspStsWorks = serverVersion.equals("2.0") || serverVersion.equals("3.0"); attachmentsSupported = !serverVersion.equals("2.0"); String authorityType = params.getParameter(SharePointConfig.PARAM_AUTHORITYTYPE); if (authorityType == null) authorityType = "ActiveDirectory"; activeDirectoryAuthority = authorityType.equals("ActiveDirectory"); serverProtocol = params.getParameter(SharePointConfig.PARAM_SERVERPROTOCOL); if (serverProtocol == null) serverProtocol = "http"; try {/*from w w w . java 2 s .co m*/ String serverPort = params.getParameter(SharePointConfig.PARAM_SERVERPORT); if (serverPort == null || serverPort.length() == 0) { if (serverProtocol.equals("https")) this.serverPort = 443; else this.serverPort = 80; } else this.serverPort = Integer.parseInt(serverPort); } catch (NumberFormatException e) { throw new ManifoldCFException(e.getMessage(), e); } serverLocation = params.getParameter(SharePointConfig.PARAM_SERVERLOCATION); if (serverLocation == null) serverLocation = ""; if (serverLocation.endsWith("/")) serverLocation = serverLocation.substring(0, serverLocation.length() - 1); if (serverLocation.length() > 0 && !serverLocation.startsWith("/")) serverLocation = "/" + serverLocation; encodedServerLocation = serverLocation; serverLocation = decodePath(serverLocation); userName = params.getParameter(SharePointConfig.PARAM_SERVERUSERNAME); password = params.getObfuscatedParameter(SharePointConfig.PARAM_SERVERPASSWORD); int index = userName.indexOf("\\"); if (index != -1) { strippedUserName = userName.substring(index + 1); ntlmDomain = userName.substring(0, index); } else { strippedUserName = null; ntlmDomain = null; } String proxyHost = params.getParameter(SharePointConfig.PARAM_PROXYHOST); String proxyPortString = params.getParameter(SharePointConfig.PARAM_PROXYPORT); int proxyPort = 8080; if (proxyPortString != null && proxyPortString.length() > 0) { try { proxyPort = Integer.parseInt(proxyPortString); } catch (NumberFormatException e) { throw new ManifoldCFException(e.getMessage(), e); } } String proxyUsername = params.getParameter(SharePointConfig.PARAM_PROXYUSER); String proxyPassword = params.getParameter(SharePointConfig.PARAM_PROXYPASSWORD); String proxyDomain = params.getParameter(SharePointConfig.PARAM_PROXYDOMAIN); serverUrl = serverProtocol + "://" + serverName; if (serverProtocol.equals("https")) { if (serverPort != 443) serverUrl += ":" + Integer.toString(serverPort); } else { if (serverPort != 80) serverUrl += ":" + Integer.toString(serverPort); } fileBaseUrl = serverUrl + encodedServerLocation; // Set up ssl if indicated keystoreData = params.getParameter(SharePointConfig.PARAM_SERVERKEYSTORE); int connectionTimeout = 60000; int socketTimeout = 900000; connectionManager = new PoolingHttpClientConnectionManager(); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); SSLConnectionSocketFactory myFactory = null; if (keystoreData != null) { keystoreManager = KeystoreManagerFactory.make("", keystoreData); myFactory = new SSLConnectionSocketFactory(keystoreManager.getSecureSocketFactory(), new BrowserCompatHostnameVerifier()); } if (strippedUserName != null) { credentialsProvider.setCredentials(new AuthScope(serverName, serverPort), new NTCredentials(strippedUserName, password, currentHost, ntlmDomain)); } RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true) .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true) .setExpectContinueEnabled(false).setConnectTimeout(connectionTimeout) .setConnectionRequestTimeout(socketTimeout); // If there's a proxy, set that too. if (proxyHost != null && proxyHost.length() > 0) { // Configure proxy authentication if (proxyUsername != null && proxyUsername.length() > 0) { if (proxyPassword == null) proxyPassword = ""; if (proxyDomain == null) proxyDomain = ""; credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUsername, proxyPassword, currentHost, proxyDomain)); } HttpHost proxy = new HttpHost(proxyHost, proxyPort); requestBuilder.setProxy(proxy); } HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connectionManager) .setMaxConnTotal(1).disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build()) .setDefaultSocketConfig( SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build()) .setDefaultCredentialsProvider(credentialsProvider); if (myFactory != null) builder.setSSLSocketFactory(myFactory); builder.setRequestExecutor(new HttpRequestExecutor(socketTimeout)) .setRedirectStrategy(new DefaultRedirectStrategy()); httpClient = builder.build(); proxy = new SPSProxyHelper(serverUrl, encodedServerLocation, serverLocation, userName, password, org.apache.manifoldcf.connectorcommon.common.CommonsHTTPSender.class, "client-config.wsdd", httpClient); } sessionTimeout = System.currentTimeMillis() + sessionExpirationInterval; }
From source file:org.apache.manifoldcf.crawler.connectors.livelink.LivelinkConnector.java
protected void getSession() throws ManifoldCFException, ServiceInterruption { getSessionParameters();/*ww w . j a v a 2 s . c o m*/ if (hasConnected == false) { int socketTimeout = 900000; int connectionTimeout = 300000; // Set up connection manager connectionManager = new PoolingHttpClientConnectionManager(); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); // Set up ingest ssl if indicated SSLConnectionSocketFactory myFactory = null; if (ingestKeystoreManager != null) { myFactory = new SSLConnectionSocketFactory( new InterruptibleSocketFactory(ingestKeystoreManager.getSecureSocketFactory(), connectionTimeout), new BrowserCompatHostnameVerifier()); } // Set up authentication to use if (ingestNtlmDomain != null) { credentialsProvider.setCredentials(AuthScope.ANY, new NTCredentials(ingestNtlmUsername, ingestNtlmPassword, currentHost, ingestNtlmDomain)); } HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connectionManager) .setMaxConnTotal(1).disableAutomaticRetries() .setDefaultRequestConfig(RequestConfig.custom().setCircularRedirectsAllowed(true) .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true) .setExpectContinueEnabled(true).setConnectTimeout(connectionTimeout) .setConnectionRequestTimeout(socketTimeout).build()) .setDefaultSocketConfig( SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build()) .setDefaultCredentialsProvider(credentialsProvider) .setRequestExecutor(new HttpRequestExecutor(socketTimeout)) .setRedirectStrategy(new DefaultRedirectStrategy()); if (myFactory != null) builder.setSSLSocketFactory(myFactory); httpClient = builder.build(); // System.out.println("Connection server object = "+llServer.toString()); // Establish the actual connection int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { GetSessionThread t = new GetSessionThread(); try { t.start(); t.finishUp(); hasConnected = true; break; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: " + e.getMessage(), e, ManifoldCFException.INTERRUPTED); } catch (RuntimeException e2) { sanityRetryCount = handleLivelinkRuntimeException(e2, sanityRetryCount, true); } } } expirationTime = System.currentTimeMillis() + expirationInterval; }
From source file:org.finra.herd.dao.helper.HttpClientHelper.java
/** * Creates a new HTTP client./*from ww w . ja v a 2s . c o m*/ * * @param trustSelfSignedCertificate specifies whether to trust a self-signed certificate * @param disableHostnameVerification specifies whether to turn off hostname verification * * @return the HTTP client * @throws KeyStoreException if a key store exception occurs * @throws NoSuchAlgorithmException if a no such algorithm exception occurs * @throws KeyManagementException if key management exception */ public CloseableHttpClient createHttpClient(Boolean trustSelfSignedCertificate, Boolean disableHostnameVerification) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { // Create an HTTP client builder. HttpClientBuilder httpClientBuilder = HttpClients.custom(); // Create an SSL context builder. SSLContextBuilder sslContextBuilder = SSLContexts.custom(); // If specified, setup a trust strategy that allows all certificates. if (BooleanUtils.isTrue(trustSelfSignedCertificate)) { sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); } // If specified, turn hostname verification off. HostnameVerifier hostnameVerifier = BooleanUtils.isTrue(disableHostnameVerification) ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER : SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER; // Create and assign an SSL connection socket factory. SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory( sslContextBuilder.build(), hostnameVerifier); httpClientBuilder.setSSLSocketFactory(sslConnectionSocketFactory); // Build and return an HTTP client. return httpClientBuilder.build(); }
From source file:org.flowable.app.service.editor.AppDefinitionPublishService.java
protected void deployZipArtifact(String artifactName, byte[] zipArtifact, String deploymentKey, String deploymentName) {// w w w. j ava 2s . co m String deployApiUrl = environment.getRequiredProperty("deployment.api.url"); String basicAuthUser = environment.getRequiredProperty("idm.admin.user"); String basicAuthPassword = environment.getRequiredProperty("idm.admin.password"); if (deployApiUrl.endsWith("/") == false) { deployApiUrl = deployApiUrl.concat("/"); } deployApiUrl = deployApiUrl .concat(String.format("repository/deployments?deploymentKey=%s&deploymentName=%s", encode(deploymentKey), encode(deploymentName))); HttpPost httpPost = new HttpPost(deployApiUrl); httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String( Base64.encodeBase64((basicAuthUser + ":" + basicAuthPassword).getBytes(Charset.forName("UTF-8"))))); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); entityBuilder.addBinaryBody("artifact", zipArtifact, ContentType.DEFAULT_BINARY, artifactName); HttpEntity entity = entityBuilder.build(); httpPost.setEntity(entity); HttpClientBuilder clientBuilder = HttpClientBuilder.create(); SSLConnectionSocketFactory sslsf = null; try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); sslsf = new SSLConnectionSocketFactory(builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); clientBuilder.setSSLSocketFactory(sslsf); } catch (Exception e) { logger.error("Could not configure SSL for http client", e); throw new InternalServerErrorException("Could not configure SSL for http client", e); } CloseableHttpClient client = clientBuilder.build(); try { HttpResponse response = client.execute(httpPost); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) { return; } else { logger.error("Invalid deploy result code: {}", response.getStatusLine()); throw new InternalServerErrorException("Invalid deploy result code: " + response.getStatusLine()); } } catch (IOException ioe) { logger.error("Error calling deploy endpoint", ioe); throw new InternalServerErrorException("Error calling deploy endpoint: " + ioe.getMessage()); } finally { if (client != null) { try { client.close(); } catch (IOException e) { logger.warn("Exception while closing http client", e); } } } }
From source file:org.flowable.http.bpmn.impl.HttpActivityBehaviorImpl.java
public HttpActivityBehaviorImpl() { HttpClientConfig config = CommandContextUtil.getProcessEngineConfiguration().getHttpClientConfig(); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); // https settings if (config.isDisableCertVerify()) { try {/*from w ww . java2 s.c om*/ SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); httpClientBuilder.setSSLSocketFactory( new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } })); } catch (Exception e) { LOGGER.error("Could not configure HTTP client SSL self signed strategy", e); } } // request retry settings int retryCount = 0; if (config.getRequestRetryLimit() > 0) { retryCount = config.getRequestRetryLimit(); } httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(retryCount, false)); this.httpActivityExecutor = new HttpActivityExecutor(httpClientBuilder, new ProcessErrorPropagator()); }