List of usage examples for org.apache.http.impl.conn BasicHttpClientConnectionManager BasicHttpClientConnectionManager
public BasicHttpClientConnectionManager(final Lookup<ConnectionSocketFactory> socketFactoryRegistry)
From source file:org.apache.ambari.view.hive.client.Connection.java
private CloseableHttpClient getHttpClient(Boolean useSsl) throws SQLException { boolean isCookieEnabled = authParams.get(Utils.HiveAuthenticationParams.COOKIE_AUTH) == null || (!Utils.HiveAuthenticationParams.COOKIE_AUTH_FALSE .equalsIgnoreCase(authParams.get(Utils.HiveAuthenticationParams.COOKIE_AUTH))); String cookieName = authParams.get(Utils.HiveAuthenticationParams.COOKIE_NAME) == null ? Utils.HiveAuthenticationParams.DEFAULT_COOKIE_NAMES_HS2 : authParams.get(Utils.HiveAuthenticationParams.COOKIE_NAME); CookieStore cookieStore = isCookieEnabled ? new BasicCookieStore() : null; HttpClientBuilder httpClientBuilder; // Request interceptor for any request pre-processing logic HttpRequestInterceptor requestInterceptor; Map<String, String> additionalHttpHeaders = new HashMap<String, String>(); // Retrieve the additional HttpHeaders for (Map.Entry<String, String> entry : authParams.entrySet()) { String key = entry.getKey(); if (key.startsWith(Utils.HiveAuthenticationParams.HTTP_HEADER_PREFIX)) { additionalHttpHeaders.put(key.substring(Utils.HiveAuthenticationParams.HTTP_HEADER_PREFIX.length()), entry.getValue());//from ww w.ja va2 s. c o m } } // Configure http client for kerberos/password based authentication if (isKerberosAuthMode()) { /** * Add an interceptor which sets the appropriate header in the request. * It does the kerberos authentication and get the final service ticket, * for sending to the server before every request. * In https mode, the entire information is encrypted */ Boolean assumeSubject = Utils.HiveAuthenticationParams.AUTH_KERBEROS_AUTH_TYPE_FROM_SUBJECT .equals(authParams.get(Utils.HiveAuthenticationParams.AUTH_KERBEROS_AUTH_TYPE)); requestInterceptor = new HttpKerberosRequestInterceptor( authParams.get(Utils.HiveAuthenticationParams.AUTH_PRINCIPAL), host, getServerHttpUrl(useSsl), assumeSubject, cookieStore, cookieName, useSsl, additionalHttpHeaders); } else { /** * Add an interceptor to pass username/password in the header. * In https mode, the entire information is encrypted */ requestInterceptor = new HttpBasicAuthInterceptor( getAuthParamDefault(Utils.HiveAuthenticationParams.AUTH_USER, getUsername()), getPassword(), cookieStore, cookieName, useSsl, additionalHttpHeaders); } // Configure http client for cookie based authentication if (isCookieEnabled) { // Create a http client with a retry mechanism when the server returns a status code of 401. httpClientBuilder = HttpClients.custom() .setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() { @Override public boolean retryRequest(final HttpResponse response, final int executionCount, final HttpContext context) { int statusCode = response.getStatusLine().getStatusCode(); boolean ret = statusCode == 401 && executionCount <= 1; // Set the context attribute to true which will be interpreted by the request interceptor if (ret) { context.setAttribute(Utils.HIVE_SERVER2_RETRY_KEY, Utils.HIVE_SERVER2_RETRY_TRUE); } return ret; } @Override public long getRetryInterval() { // Immediate retry return 0; } }); } else { httpClientBuilder = HttpClientBuilder.create(); } // Add the request interceptor to the client builder httpClientBuilder.addInterceptorFirst(requestInterceptor); // Configure http client for SSL if (useSsl) { String useTwoWaySSL = authParams.get(Utils.HiveAuthenticationParams.USE_TWO_WAY_SSL); String sslTrustStorePath = authParams.get(Utils.HiveAuthenticationParams.SSL_TRUST_STORE); String sslTrustStorePassword = authParams.get(Utils.HiveAuthenticationParams.SSL_TRUST_STORE_PASSWORD); KeyStore sslTrustStore; SSLSocketFactory socketFactory; /** * The code within the try block throws: * 1. SSLInitializationException * 2. KeyStoreException * 3. IOException * 4. NoSuchAlgorithmException * 5. CertificateException * 6. KeyManagementException * 7. UnrecoverableKeyException * We don't want the client to retry on any of these, hence we catch all * and throw a SQLException. */ try { if (useTwoWaySSL != null && useTwoWaySSL.equalsIgnoreCase(Utils.HiveAuthenticationParams.TRUE)) { socketFactory = getTwoWaySSLSocketFactory(); } else if (sslTrustStorePath == null || sslTrustStorePath.isEmpty()) { // Create a default socket factory based on standard JSSE trust material socketFactory = SSLSocketFactory.getSocketFactory(); } else { // Pick trust store config from the given path sslTrustStore = KeyStore.getInstance(Utils.HiveAuthenticationParams.SSL_TRUST_STORE_TYPE); try (FileInputStream fis = new FileInputStream(sslTrustStorePath)) { sslTrustStore.load(fis, sslTrustStorePassword.toCharArray()); } socketFactory = new SSLSocketFactory(sslTrustStore); } socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", socketFactory).build(); httpClientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry)); } catch (Exception e) { String msg = "Could not create an https connection to " + getServerHttpUrl(useSsl) + ". " + e.getMessage(); throw new SQLException(msg, " 08S01", e); } } return httpClientBuilder.build(); }
From source file:com.xebialabs.overthere.winrm.WinRmClient.java
private HttpClientConnectionManager getHttpClientConnectionManager() { final Lookup<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create().register("http", new PlainConnectionSocketFactory() { @Override//from ww w . j a v a 2s . co m public Socket createSocket(HttpContext context) throws IOException { return socketFactory.createSocket(); } }).register("https", new SSLConnectionSocketFactory(SSLContexts.createDefault(), SSLConnectionSocketFactory.getDefaultHostnameVerifier()) { @Override public Socket createSocket(HttpContext context) throws IOException { return socketFactory.createSocket(); } }).build(); return new BasicHttpClientConnectionManager(socketFactoryRegistry); }
From source file:com.tremolosecurity.unison.openshiftv3.OpenShiftTarget.java
public HttpCon createClient() throws Exception { ArrayList<Header> defheaders = new ArrayList<Header>(); defheaders.add(new BasicHeader("X-Csrf-Token", "1")); BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager( cfgMgr.getHttpClientSocketRegistry()); RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setRedirectsEnabled(false) .build();/* w w w . ja v a 2s .c o m*/ CloseableHttpClient http = HttpClients.custom().setConnectionManager(bhcm).setDefaultHeaders(defheaders) .setDefaultRequestConfig(rc).build(); HttpCon con = new HttpCon(); con.setBcm(bhcm); con.setHttp(http); return con; }
From source file:com.tremolosecurity.unison.openstack.KeystoneProvisioningTarget.java
public HttpCon createClient() throws Exception { ArrayList<Header> defheaders = new ArrayList<Header>(); BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager( cfgMgr.getHttpClientSocketRegistry()); RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setRedirectsEnabled(false) .build();/* w w w . java 2 s.c om*/ CloseableHttpClient http = HttpClients.custom().setConnectionManager(bhcm).setDefaultHeaders(defheaders) .setDefaultRequestConfig(rc).build(); HttpCon con = new HttpCon(); con.setBcm(bhcm); con.setHttp(http); return con; }
From source file:org.apache.hive.jdbc.HiveConnection.java
private CloseableHttpClient getHttpClient(Boolean useSsl) throws SQLException { boolean isCookieEnabled = sessConfMap.get(JdbcConnectionParams.COOKIE_AUTH) == null || (!JdbcConnectionParams.COOKIE_AUTH_FALSE .equalsIgnoreCase(sessConfMap.get(JdbcConnectionParams.COOKIE_AUTH))); String cookieName = sessConfMap.get(JdbcConnectionParams.COOKIE_NAME) == null ? JdbcConnectionParams.DEFAULT_COOKIE_NAMES_HS2 : sessConfMap.get(JdbcConnectionParams.COOKIE_NAME); CookieStore cookieStore = isCookieEnabled ? new BasicCookieStore() : null; HttpClientBuilder httpClientBuilder; // Request interceptor for any request pre-processing logic HttpRequestInterceptor requestInterceptor; Map<String, String> additionalHttpHeaders = new HashMap<String, String>(); // Retrieve the additional HttpHeaders for (Map.Entry<String, String> entry : sessConfMap.entrySet()) { String key = entry.getKey(); if (key.startsWith(JdbcConnectionParams.HTTP_HEADER_PREFIX)) { additionalHttpHeaders.put(key.substring(JdbcConnectionParams.HTTP_HEADER_PREFIX.length()), entry.getValue());/*from www . ja va 2s . co m*/ } } // Configure http client for kerberos/password based authentication if (isKerberosAuthMode()) { /** * Add an interceptor which sets the appropriate header in the request. * It does the kerberos authentication and get the final service ticket, * for sending to the server before every request. * In https mode, the entire information is encrypted */ requestInterceptor = new HttpKerberosRequestInterceptor( sessConfMap.get(JdbcConnectionParams.AUTH_PRINCIPAL), host, getServerHttpUrl(useSsl), assumeSubject, cookieStore, cookieName, useSsl, additionalHttpHeaders); } else { // Check for delegation token, if present add it in the header String tokenStr = getClientDelegationToken(sessConfMap); if (tokenStr != null) { requestInterceptor = new HttpTokenAuthInterceptor(tokenStr, cookieStore, cookieName, useSsl, additionalHttpHeaders); } else { /** * Add an interceptor to pass username/password in the header. * In https mode, the entire information is encrypted */ requestInterceptor = new HttpBasicAuthInterceptor(getUserName(), getPassword(), cookieStore, cookieName, useSsl, additionalHttpHeaders); } } // Configure http client for cookie based authentication if (isCookieEnabled) { // Create a http client with a retry mechanism when the server returns a status code of 401. httpClientBuilder = HttpClients.custom() .setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() { @Override public boolean retryRequest(final HttpResponse response, final int executionCount, final HttpContext context) { int statusCode = response.getStatusLine().getStatusCode(); boolean ret = statusCode == 401 && executionCount <= 1; // Set the context attribute to true which will be interpreted by the request // interceptor if (ret) { context.setAttribute(Utils.HIVE_SERVER2_RETRY_KEY, Utils.HIVE_SERVER2_RETRY_TRUE); } return ret; } @Override public long getRetryInterval() { // Immediate retry return 0; } }); } else { httpClientBuilder = HttpClientBuilder.create(); } // In case the server's idletimeout is set to a lower value, it might close it's side of // connection. However we retry one more time on NoHttpResponseException httpClientBuilder.setRetryHandler(new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount > 1) { LOG.info("Retry attempts to connect to server exceeded."); return false; } if (exception instanceof org.apache.http.NoHttpResponseException) { LOG.info("Could not connect to the server. Retrying one more time."); return true; } return false; } }); // Add the request interceptor to the client builder httpClientBuilder.addInterceptorFirst(requestInterceptor); // Add an interceptor to add in an XSRF header httpClientBuilder.addInterceptorLast(new XsrfHttpRequestInterceptor()); // Configure http client for SSL if (useSsl) { String useTwoWaySSL = sessConfMap.get(JdbcConnectionParams.USE_TWO_WAY_SSL); String sslTrustStorePath = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE); String sslTrustStorePassword = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE_PASSWORD); KeyStore sslTrustStore; SSLConnectionSocketFactory socketFactory; SSLContext sslContext; /** * The code within the try block throws: SSLInitializationException, KeyStoreException, * IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException & * UnrecoverableKeyException. We don't want the client to retry on any of these, * hence we catch all and throw a SQLException. */ try { if (useTwoWaySSL != null && useTwoWaySSL.equalsIgnoreCase(JdbcConnectionParams.TRUE)) { socketFactory = getTwoWaySSLSocketFactory(); } else if (sslTrustStorePath == null || sslTrustStorePath.isEmpty()) { // Create a default socket factory based on standard JSSE trust material socketFactory = SSLConnectionSocketFactory.getSocketFactory(); } else { // Pick trust store config from the given path sslTrustStore = KeyStore.getInstance(JdbcConnectionParams.SSL_TRUST_STORE_TYPE); try (FileInputStream fis = new FileInputStream(sslTrustStorePath)) { sslTrustStore.load(fis, sslTrustStorePassword.toCharArray()); } sslContext = SSLContexts.custom().loadTrustMaterial(sslTrustStore, null).build(); socketFactory = new SSLConnectionSocketFactory(sslContext, new DefaultHostnameVerifier(null)); } final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", socketFactory).build(); httpClientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry)); } catch (Exception e) { String msg = "Could not create an https connection to " + jdbcUriString + ". " + e.getMessage(); throw new SQLException(msg, " 08S01", e); } } return httpClientBuilder.build(); }
From source file:org.opennms.core.web.HttpClientWrapper.java
protected void configureSSLContext(final HttpClientBuilder builder) { final RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder .<ConnectionSocketFactory>create(); for (final Map.Entry<String, SSLContext> entry : m_sslContext.entrySet()) { final SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(entry.getValue(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); registryBuilder.register(entry.getKey(), sslConnectionFactory); }// ww w . ja v a 2 s . c o m if (!m_sslContext.containsKey("http")) { registryBuilder.register("http", PlainConnectionSocketFactory.INSTANCE); } if (!m_sslContext.containsKey("https")) { registryBuilder.register("https", SSLConnectionSocketFactory.getSystemSocketFactory()); } final HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registryBuilder.build()); builder.setConnectionManager(ccm); }
From source file:org.ovirt.engine.core.uutils.net.HttpClientBuilder.java
public CloseableHttpClient build() throws IOException, GeneralSecurityException { // Prepare the default configuration for all requests: RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(connectTimeout != null ? connectTimeout : 0) .setSocketTimeout(readTimeout != null ? readTimeout : 0).build(); // Configure the trust manager: TrustManager[] trustManager = null; if (verifyChain) { if (trustStore != null) { try (InputStream is = new FileInputStream(trustStore)) { KeyStore ks = KeyStore.getInstance(trustStoreType); ks.load(is, StringUtils.isEmpty(trustStorePassword) ? null : trustStorePassword.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance(trustManagerAlgorithm); tmf.init(ks);// ww w . j a v a 2s . c o m trustManager = tmf.getTrustManagers(); } } } else { trustManager = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[] {}; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; } // Create the SSL context: SSLContext sslContext = SSLContext.getInstance(tlsProtocol); sslContext.init(null, trustManager, null); // Create the SSL host name verifier: HostnameVerifier sslHostnameVerifier = null; if (!verifyHost) { sslHostnameVerifier = (hostname, session) -> true; } // Create the socket factory for HTTP: ConnectionSocketFactory httpSocketFactory = new PlainConnectionSocketFactory(); // Create the socket factory for HTTPS: ConnectionSocketFactory httpsSocketFactory = new SSLConnectionSocketFactory(sslContext, sslHostnameVerifier); // Create the socket factory registry: Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", httpSocketFactory).register("https", httpsSocketFactory).build(); // Create the connection manager: HttpClientConnectionManager connectionManager; if (poolSize != null) { PoolingHttpClientConnectionManager poolManager = new PoolingHttpClientConnectionManager( socketFactoryRegistry); poolManager.setDefaultMaxPerRoute(poolSize); poolManager.setMaxTotal(poolSize); connectionManager = poolManager; } else { connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry); } // Create the client: return org.apache.http.impl.client.HttpClientBuilder.create().setDefaultRequestConfig(requestConfig) .setSSLHostnameVerifier(sslHostnameVerifier).setConnectionManager(connectionManager).build(); }