Search in sources :

Example 1 with ConnectionSocketFactory

use of org.apache.http.conn.socket.ConnectionSocketFactory in project camel by apache.

the class HttpComponent method createConnectionRegistry.

protected Registry<ConnectionSocketFactory> createConnectionRegistry(HostnameVerifier x509HostnameVerifier, SSLContextParameters sslContextParams) throws GeneralSecurityException, IOException {
    // create the default connection registry to use
    RegistryBuilder<ConnectionSocketFactory> builder = RegistryBuilder.<ConnectionSocketFactory>create();
    builder.register("http", PlainConnectionSocketFactory.getSocketFactory());
    builder.register("http4", PlainConnectionSocketFactory.getSocketFactory());
    if (sslContextParams != null) {
        builder.register("https", new SSLConnectionSocketFactory(sslContextParams.createSSLContext(getCamelContext()), x509HostnameVerifier));
        builder.register("https4", new SSLConnectionSocketFactory(sslContextParams.createSSLContext(getCamelContext()), x509HostnameVerifier));
    } else {
        builder.register("https4", new SSLConnectionSocketFactory(SSLContexts.createDefault(), x509HostnameVerifier));
        builder.register("https", new SSLConnectionSocketFactory(SSLContexts.createDefault(), x509HostnameVerifier));
    }
    return builder.build();
}
Also used : PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory)

Example 2 with ConnectionSocketFactory

use of org.apache.http.conn.socket.ConnectionSocketFactory in project camel by apache.

the class HttpComponent method createConnectionManager.

protected HttpClientConnectionManager createConnectionManager(final Map<String, Object> parameters, final SSLContextParameters sslContextParameters) throws GeneralSecurityException, IOException {
    if (clientConnectionManager != null) {
        return clientConnectionManager;
    }
    final HostnameVerifier resolvedHostnameVerifier = resolveAndRemoveReferenceParameter(parameters, "x509HostnameVerifier", HostnameVerifier.class);
    final HostnameVerifier hostnameVerifier = Optional.ofNullable(resolvedHostnameVerifier).orElse(x509HostnameVerifier);
    // need to check the parameters of maxTotalConnections and connectionsPerRoute
    final int maxTotalConnections = getAndRemoveParameter(parameters, "maxTotalConnections", int.class, 0);
    final int connectionsPerRoute = getAndRemoveParameter(parameters, "connectionsPerRoute", int.class, 0);
    final Registry<ConnectionSocketFactory> connectionRegistry = createConnectionRegistry(hostnameVerifier, sslContextParameters);
    return createConnectionManager(connectionRegistry, maxTotalConnections, connectionsPerRoute);
}
Also used : PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) Endpoint(org.apache.camel.Endpoint) HostnameVerifier(javax.net.ssl.HostnameVerifier) DefaultHostnameVerifier(org.apache.http.conn.ssl.DefaultHostnameVerifier)

Example 3 with ConnectionSocketFactory

use of org.apache.http.conn.socket.ConnectionSocketFactory in project hive by apache.

the class HiveConnection method getHttpClient.

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());
        }
    }
    // 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;
                // 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);
    // 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();
}
Also used : HashMap(java.util.HashMap) SQLException(java.sql.SQLException) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) ServiceUnavailableRetryStrategy(org.apache.http.client.ServiceUnavailableRetryStrategy) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) DefaultHostnameVerifier(org.apache.http.conn.ssl.DefaultHostnameVerifier) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) Savepoint(java.sql.Savepoint) FileInputStream(java.io.FileInputStream) TTransportException(org.apache.thrift.transport.TTransportException) SQLFeatureNotSupportedException(java.sql.SQLFeatureNotSupportedException) SaslException(javax.security.sasl.SaslException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SQLClientInfoException(java.sql.SQLClientInfoException) SQLException(java.sql.SQLException) TException(org.apache.thrift.TException) IOException(java.io.IOException) CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor) Map(java.util.Map) HashMap(java.util.HashMap)

Example 4 with ConnectionSocketFactory

use of org.apache.http.conn.socket.ConnectionSocketFactory in project cas by apereo.

the class SimpleHttpClientFactoryBean method buildHttpClient.

/**
     * Build a HTTP client based on the current properties.
     *
     * @return the built HTTP client
     */
private CloseableHttpClient buildHttpClient() {
    try {
        final ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
        final LayeredConnectionSocketFactory sslsf = this.sslSocketFactory;
        final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", plainsf).register("https", sslsf).build();
        final PoolingHttpClientConnectionManager connMgmr = new PoolingHttpClientConnectionManager(registry);
        connMgmr.setMaxTotal(this.maxPooledConnections);
        connMgmr.setDefaultMaxPerRoute(this.maxConnectionsPerRoute);
        connMgmr.setValidateAfterInactivity(DEFAULT_TIMEOUT);
        final HttpHost httpHost = new HttpHost(InetAddress.getLocalHost());
        final HttpRoute httpRoute = new HttpRoute(httpHost);
        connMgmr.setMaxPerRoute(httpRoute, MAX_CONNECTIONS_PER_ROUTE);
        final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(this.readTimeout).setConnectTimeout(Long.valueOf(this.connectionTimeout).intValue()).setConnectionRequestTimeout(Long.valueOf(this.connectionTimeout).intValue()).setCircularRedirectsAllowed(this.circularRedirectsAllowed).setRedirectsEnabled(this.redirectsEnabled).setAuthenticationEnabled(this.authenticationEnabled).build();
        final HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connMgmr).setDefaultRequestConfig(requestConfig).setSSLSocketFactory(sslsf).setSSLHostnameVerifier(this.hostnameVerifier).setRedirectStrategy(this.redirectionStrategy).setDefaultCredentialsProvider(this.credentialsProvider).setDefaultCookieStore(this.cookieStore).setConnectionReuseStrategy(this.connectionReuseStrategy).setConnectionBackoffStrategy(this.connectionBackoffStrategy).setServiceUnavailableRetryStrategy(this.serviceUnavailableRetryStrategy).setProxyAuthenticationStrategy(this.proxyAuthenticationStrategy).setDefaultHeaders(this.defaultHeaders).useSystemProperties();
        return builder.build();
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw Throwables.propagate(e);
    }
}
Also used : HttpRoute(org.apache.http.conn.routing.HttpRoute) RequestConfig(org.apache.http.client.config.RequestConfig) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) LayeredConnectionSocketFactory(org.apache.http.conn.socket.LayeredConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) LayeredConnectionSocketFactory(org.apache.http.conn.socket.LayeredConnectionSocketFactory) HttpHost(org.apache.http.HttpHost) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager)

Example 5 with ConnectionSocketFactory

use of org.apache.http.conn.socket.ConnectionSocketFactory in project dropwizard by dropwizard.

the class HttpClientBuilderTest method canUseACustomHostnameVerifierWhenTlsConfigurationNotSpecified.

@Test
public void canUseACustomHostnameVerifierWhenTlsConfigurationNotSpecified() throws Exception {
    final HostnameVerifier customVerifier = (s, sslSession) -> false;
    final Registry<ConnectionSocketFactory> configuredRegistry;
    configuredRegistry = builder.using(customVerifier).createConfiguredRegistry();
    assertThat(configuredRegistry).isNotNull();
    final SSLConnectionSocketFactory socketFactory = (SSLConnectionSocketFactory) configuredRegistry.lookup("https");
    assertThat(socketFactory).isNotNull();
    final Field hostnameVerifierField = FieldUtils.getField(SSLConnectionSocketFactory.class, "hostnameVerifier", true);
    assertThat(hostnameVerifierField.get(socketFactory)).isSameAs(customVerifier);
}
Also used : ProtocolException(org.apache.http.ProtocolException) SocketAddress(java.net.SocketAddress) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) SocketConfig(org.apache.http.config.SocketConfig) TlsConfiguration(io.dropwizard.client.ssl.TlsConfiguration) RequestConfig(org.apache.http.client.config.RequestConfig) Header(org.apache.http.Header) ProxySelector(java.net.ProxySelector) NoConnectionReuseStrategy(org.apache.http.impl.NoConnectionReuseStrategy) Registry(org.apache.http.config.Registry) Proxy(java.net.Proxy) SystemDefaultDnsResolver(org.apache.http.impl.conn.SystemDefaultDnsResolver) After(org.junit.After) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) InstrumentedHttpRequestExecutor(com.codahale.metrics.httpclient.InstrumentedHttpRequestExecutor) HttpRoutePlanner(org.apache.http.conn.routing.HttpRoutePlanner) URI(java.net.URI) HostnameVerifier(javax.net.ssl.HostnameVerifier) HttpHeaders(org.apache.http.HttpHeaders) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) InstrumentedHttpClientConnectionManager(com.codahale.metrics.httpclient.InstrumentedHttpClientConnectionManager) LifecycleEnvironment(io.dropwizard.lifecycle.setup.LifecycleEnvironment) HeaderIterator(org.apache.http.HeaderIterator) HttpClientMetricNameStrategies(com.codahale.metrics.httpclient.HttpClientMetricNameStrategies) DefaultConnectionKeepAliveStrategy(org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy) DefaultConnectionReuseStrategy(org.apache.http.impl.DefaultConnectionReuseStrategy) InetSocketAddress(java.net.InetSocketAddress) HttpRequest(org.apache.http.HttpRequest) List(java.util.List) HttpGet(org.apache.http.client.methods.HttpGet) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) Managed(io.dropwizard.lifecycle.Managed) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) Optional(java.util.Optional) CredentialsProvider(org.apache.http.client.CredentialsProvider) Mockito.mock(org.mockito.Mockito.mock) MockitoAnnotations.initMocks(org.mockito.MockitoAnnotations.initMocks) DefaultRoutePlanner(org.apache.http.impl.conn.DefaultRoutePlanner) RegistryBuilder(org.apache.http.config.RegistryBuilder) BasicListHeaderIterator(org.apache.http.message.BasicListHeaderIterator) DnsResolver(org.apache.http.conn.DnsResolver) CookieSpecs(org.apache.http.client.config.CookieSpecs) HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpRoute(org.apache.http.conn.routing.HttpRoute) Mockito.spy(org.mockito.Mockito.spy) Duration(io.dropwizard.util.Duration) ProxyConfiguration(io.dropwizard.client.proxy.ProxyConfiguration) ArgumentCaptor(org.mockito.ArgumentCaptor) ImmutableList(com.google.common.collect.ImmutableList) Credentials(org.apache.http.auth.Credentials) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) FieldUtils(org.apache.commons.lang3.reflect.FieldUtils) SystemDefaultRoutePlanner(org.apache.http.impl.conn.SystemDefaultRoutePlanner) HttpRequestRetryHandler(org.apache.http.client.HttpRequestRetryHandler) HTTP(org.apache.http.protocol.HTTP) Before(org.junit.Before) Environment(io.dropwizard.setup.Environment) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) MetricRegistry(com.codahale.metrics.MetricRegistry) AuthConfiguration(io.dropwizard.client.proxy.AuthConfiguration) IOException(java.io.IOException) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) HttpProcessor(org.apache.http.protocol.HttpProcessor) Field(java.lang.reflect.Field) Mockito.validateMockitoUsage(org.mockito.Mockito.validateMockitoUsage) Mockito.verify(org.mockito.Mockito.verify) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) RedirectStrategy(org.apache.http.client.RedirectStrategy) AuthScope(org.apache.http.auth.AuthScope) HttpContext(org.apache.http.protocol.HttpContext) BasicHeader(org.apache.http.message.BasicHeader) HttpResponse(org.apache.http.HttpResponse) HttpHost(org.apache.http.HttpHost) Field(java.lang.reflect.Field) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) HostnameVerifier(javax.net.ssl.HostnameVerifier) Test(org.junit.Test)

Aggregations

ConnectionSocketFactory (org.apache.http.conn.socket.ConnectionSocketFactory)30 SSLConnectionSocketFactory (org.apache.http.conn.ssl.SSLConnectionSocketFactory)28 PlainConnectionSocketFactory (org.apache.http.conn.socket.PlainConnectionSocketFactory)21 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)19 SSLContext (javax.net.ssl.SSLContext)15 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)10 IOException (java.io.IOException)8 HostnameVerifier (javax.net.ssl.HostnameVerifier)8 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)7 URI (java.net.URI)6 HttpResponse (org.apache.http.HttpResponse)6 RequestConfig (org.apache.http.client.config.RequestConfig)6 HttpGet (org.apache.http.client.methods.HttpGet)6 Test (org.junit.Test)6 X509Certificate (java.security.cert.X509Certificate)5 BasicHttpClientConnectionManager (org.apache.http.impl.conn.BasicHttpClientConnectionManager)5 Field (java.lang.reflect.Field)4 CertificateException (java.security.cert.CertificateException)4 HashMap (java.util.HashMap)4 SSLContextBuilder (org.apache.http.conn.ssl.SSLContextBuilder)4