Search in sources :

Example 6 with ConnectionSocketFactory

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

the class HttpClientBuilderTest method canUseACustomHostnameVerifierWhenTlsConfigurationSpecified.

@Test
public void canUseACustomHostnameVerifierWhenTlsConfigurationSpecified() throws Exception {
    final TlsConfiguration tlsConfiguration = new TlsConfiguration();
    tlsConfiguration.setVerifyHostname(true);
    configuration.setTlsConfiguration(tlsConfiguration);
    final HostnameVerifier customVerifier = (s, sslSession) -> false;
    final Registry<ConnectionSocketFactory> configuredRegistry;
    configuredRegistry = builder.using(configuration).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) TlsConfiguration(io.dropwizard.client.ssl.TlsConfiguration) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) HostnameVerifier(javax.net.ssl.HostnameVerifier) Test(org.junit.Test)

Example 7 with ConnectionSocketFactory

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

the class HttpClientWrapper method configureSSLContext.

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);
    }
    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);
}
Also used : SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLContext(javax.net.ssl.SSLContext) HttpClientConnectionManager(org.apache.http.conn.HttpClientConnectionManager) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) Map(java.util.Map) HashMap(java.util.HashMap) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager)

Example 8 with ConnectionSocketFactory

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

the class TestJSONOverHttps method callProcOverJSON.

private String callProcOverJSON(String varString, final int expectedCode) throws Exception {
    URI uri = URI.create("https://localhost:" + m_port + "/api/1.0/");
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

        @Override
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();
    SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sf).build();
    // allows multi-threaded use
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    HttpClientBuilder b = HttpClientBuilder.create();
    b.setSslcontext(sslContext);
    b.setConnectionManager(connMgr);
    try (CloseableHttpClient httpclient = b.build()) {
        HttpPost post = new HttpPost(uri);
        // play nice by using HTTP 1.1 continue requests where the client sends the request headers first
        // to the server to see if the server is willing to accept it. This allows us to test large requests
        // without incurring server socket connection terminations
        RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setExpectContinueEnabled(true).build();
        post.setProtocolVersion(HttpVersion.HTTP_1_1);
        post.setConfig(rc);
        post.setEntity(new StringEntity(varString, utf8ApplicationFormUrlEncoded));
        ResponseHandler<String> rh = new ResponseHandler<String>() {

            @Override
            public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                assertEquals(expectedCode, status);
                if ((status >= 200 && status < 300) || status == 400) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                }
                return null;
            }
        };
        return httpclient.execute(post, rh);
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) ResponseHandler(org.apache.http.client.ResponseHandler) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) SSLContext(javax.net.ssl.SSLContext) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) URI(java.net.URI) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) StringEntity(org.apache.http.entity.StringEntity) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) SSLContextBuilder(org.apache.http.conn.ssl.SSLContextBuilder)

Example 9 with ConnectionSocketFactory

use of org.apache.http.conn.socket.ConnectionSocketFactory in project calcite-avatica by apache.

the class AvaticaCommonsHttpClientImpl method initializeClient.

private void initializeClient() {
    SSLConnectionSocketFactory sslFactory = null;
    if (null != truststore && null != truststorePassword) {
        try {
            SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(truststore, truststorePassword.toCharArray()).build();
            sslFactory = new SSLConnectionSocketFactory(sslcontext);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    } else {
        LOG.debug("Not configuring HTTPS because of missing truststore/password");
    }
    RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
    registryBuilder.register("http", PlainConnectionSocketFactory.getSocketFactory());
    // Only register the SSL factory when provided
    if (null != sslFactory) {
        registryBuilder.register("https", sslFactory);
    }
    pool = new PoolingHttpClientConnectionManager(registryBuilder.build());
    // Increase max total connection to 100
    final String maxCnxns = System.getProperty(MAX_POOLED_CONNECTIONS_KEY, MAX_POOLED_CONNECTIONS_DEFAULT);
    pool.setMaxTotal(Integer.parseInt(maxCnxns));
    // Increase default max connection per route to 25
    final String maxCnxnsPerRoute = System.getProperty(MAX_POOLED_CONNECTION_PER_ROUTE_KEY, MAX_POOLED_CONNECTION_PER_ROUTE_DEFAULT);
    pool.setDefaultMaxPerRoute(Integer.parseInt(maxCnxnsPerRoute));
    this.authCache = new BasicAuthCache();
    // A single thread-safe HttpClient, pooling connections via the ConnectionManager
    this.client = HttpClients.custom().setConnectionManager(pool).build();
}
Also used : PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) SSLContext(javax.net.ssl.SSLContext) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ClientProtocolException(org.apache.http.client.ClientProtocolException) URISyntaxException(java.net.URISyntaxException) NoHttpResponseException(org.apache.http.NoHttpResponseException) IOException(java.io.IOException) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager)

Example 10 with ConnectionSocketFactory

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

the class HttpClientHelper method createHttpClient.

public static CloseableHttpClient createHttpClient(final int maxRedirects) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    final Registry<ConnectionSocketFactory> socketFactoryRegistry = createSocketFactoryConfigration();
    final BasicCookieStore cookieStore = new BasicCookieStore();
    return HttpClientBuilder.create().setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryRegistry)).setRedirectStrategy(new LaxRedirectStrategy()).setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).setMaxRedirects(maxRedirects).build()).setDefaultCookieStore(cookieStore).setRetryHandler(new StandardHttpRequestRetryHandler()).build();
}
Also used : ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) LaxRedirectStrategy(org.apache.http.impl.client.LaxRedirectStrategy) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) StandardHttpRequestRetryHandler(org.apache.http.impl.client.StandardHttpRequestRetryHandler)

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