Search in sources :

Example 1 with Registry

use of org.apache.http.config.Registry in project questdb by bluestreak01.

the class HttpTestUtils method createHttpClient_AcceptsUntrustedCerts.

private static HttpClientBuilder createHttpClient_AcceptsUntrustedCerts() throws Exception {
    HttpClientBuilder b = HttpClientBuilder.create();
    // setup a Trust Strategy that allows all certificates.
    // 
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (arg0, arg1) -> true).build();
    b.setSSLContext(sslContext);
    // here's the special part:
    // -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
    // -- and create a Registry, to register it.
    // 
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, (s, sslSession) -> true);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslSocketFactory).build();
    // now, we create connection-manager using our Registry.
    // -- allows multi-threaded use
    b.setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryRegistry));
    return b;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) SSLContext(javax.net.ssl.SSLContext) RegistryBuilder(org.apache.http.config.RegistryBuilder) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) ContentType(org.apache.http.entity.ContentType) Header(org.apache.http.Header) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) Registry(org.apache.http.config.Registry) java.io(java.io) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) HttpResponse(org.apache.http.HttpResponse) StringBody(org.apache.http.entity.mime.content.StringBody) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) HttpClients(org.apache.http.impl.client.HttpClients) FileBody(org.apache.http.entity.mime.content.FileBody) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) SSLContext(javax.net.ssl.SSLContext) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager)

Example 2 with Registry

use of org.apache.http.config.Registry in project pact-jvm by DiUS.

the class InsecureHttpsRequest method setupInsecureSSL.

private void setupInsecureSSL() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    HttpClientBuilder b = HttpClientBuilder.create();
    // setup a Trust Strategy that allows all certificates.
    //
    TrustStrategy trustStrategy = (chain, authType) -> true;
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, trustStrategy).build();
    b.setSSLContext(sslContext);
    // don't check Hostnames, either.
    //      -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken
    HostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
    // here's the special part:
    //      -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
    //      -- and create a Registry, to register it.
    //
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslSocketFactory).build();
    // now, we create connection-manager using our Registry.
    //      -- allows multi-threaded use
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    b.setConnectionManager(connMgr);
    // finally, build the HttpClient;
    //      -- done!
    this.httpclient = b.build();
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) TrustStrategy(org.apache.http.ssl.TrustStrategy) SSLContext(javax.net.ssl.SSLContext) RegistryBuilder(org.apache.http.config.RegistryBuilder) HttpOptions(org.apache.http.client.methods.HttpOptions) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) KeyStoreException(java.security.KeyStoreException) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) HttpPut(org.apache.http.client.methods.HttpPut) Registry(org.apache.http.config.Registry) HttpGet(org.apache.http.client.methods.HttpGet) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) URI(java.net.URI) HostnameVerifier(javax.net.ssl.HostnameVerifier) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) TrustStrategy(org.apache.http.ssl.TrustStrategy) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) SSLContext(javax.net.ssl.SSLContext) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) HostnameVerifier(javax.net.ssl.HostnameVerifier) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager)

Example 3 with Registry

use of org.apache.http.config.Registry in project stdlib by petergeneric.

the class ResteasyClientFactoryImpl method createHttpClientCustomiser.

/**
 * N.B. This method signature may change in the future to add new parameters
 *
 * @param fastFail
 * @param authScope
 * @param credentials
 * @param preemptiveAuth
 * @param storeCookies
 * @param customiser
 *
 * @return
 */
public Consumer<HttpClientBuilder> createHttpClientCustomiser(final boolean fastFail, final AuthScope authScope, final Credentials credentials, final boolean preemptiveAuth, final boolean storeCookies, Consumer<HttpClientBuilder> customiser) {
    // Customise timeouts if fast fail mode is enabled
    if (fastFail) {
        customiser = concat(customiser, b -> {
            RequestConfig.Builder requestBuilder = RequestConfig.custom();
            requestBuilder.setConnectTimeout((int) fastFailConnectionTimeout.getMilliseconds()).setSocketTimeout((int) fastFailSocketTimeout.getMilliseconds());
            b.setDefaultRequestConfig(requestBuilder.build());
        });
    }
    // If credentials were supplied then we should set them up
    if (credentials != null) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        if (authScope != null)
            credentialsProvider.setCredentials(authScope, credentials);
        else
            credentialsProvider.setCredentials(AuthScope.ANY, credentials);
        // Set up bearer auth scheme provider if we're using bearer credentials
        if (credentials instanceof BearerCredentials) {
            customiser = concat(customiser, b -> {
                Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register("Bearer", new BearerAuthSchemeProvider()).build();
                b.setDefaultAuthSchemeRegistry(authSchemeRegistry);
            });
        }
        // Set up the credentials customisation
        customiser = concat(customiser, b -> b.setDefaultCredentialsProvider(credentialsProvider));
        if (preemptiveAuth && credentials instanceof BearerCredentials)
            customiser = concat(customiser, b -> b.addInterceptorFirst(new PreemptiveBearerAuthInterceptor()));
        else
            customiser = concat(customiser, b -> b.addInterceptorLast(new PreemptiveBasicAuthInterceptor()));
    }
    // If cookies are enabled then set up a cookie store
    if (storeCookies)
        customiser = concat(customiser, b -> b.setDefaultCookieStore(new BasicCookieStore()));
    return customiser;
}
Also used : AuthSchemeProvider(org.apache.http.auth.AuthSchemeProvider) RegistryBuilder(org.apache.http.config.RegistryBuilder) Inject(com.google.inject.Inject) Timeout(com.peterphi.std.threading.Timeout) LogReportMessageBodyWriter(com.peterphi.std.guice.common.logging.logreport.jaxrs.LogReportMessageBodyWriter) RequestConfig(org.apache.http.client.config.RequestConfig) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) CommonTypesParamConverterProvider(com.peterphi.std.guice.restclient.converter.CommonTypesParamConverterProvider) ProxySelector(java.net.ProxySelector) NoConnectionReuseStrategy(org.apache.http.impl.NoConnectionReuseStrategy) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) ResteasyProviderFactory(org.jboss.resteasy.spi.ResteasyProviderFactory) ShutdownManager(com.peterphi.std.guice.common.shutdown.iface.ShutdownManager) Registry(org.apache.http.config.Registry) Credentials(org.apache.http.auth.Credentials) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) ApacheHttpClient4Engine(org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine) SystemDefaultRoutePlanner(org.apache.http.impl.conn.SystemDefaultRoutePlanner) Doc(com.peterphi.std.annotation.Doc) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) StoppableService(com.peterphi.std.guice.common.shutdown.iface.StoppableService) AuthScope(org.apache.http.auth.AuthScope) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) Named(com.google.inject.name.Named) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) CredentialsProvider(org.apache.http.client.CredentialsProvider) Singleton(com.google.inject.Singleton) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) RegistryBuilder(org.apache.http.config.RegistryBuilder) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) Registry(org.apache.http.config.Registry)

Example 4 with Registry

use of org.apache.http.config.Registry in project ovirt-engine-sdk-java by oVirt.

the class ConnectionBuilder45 method createConnectionSocketFactoryRegistry.

private Registry createConnectionSocketFactoryRegistry() {
    String protocol = getProtocol();
    Registry registry = null;
    // Create SSL/TLS or plain connection:
    if (HTTP_PROTOCOL.equals(protocol)) {
        ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
        registry = RegistryBuilder.<ConnectionSocketFactory>create().register(HTTP_PROTOCOL, plainsf).build();
    } else if (HTTPS_PROTOCOL.equals(protocol)) {
        try {
            LayeredConnectionSocketFactory sslsf = null;
            if (this.insecure) {
                SSLContext sslcontext = SSLContext.getInstance("TLS");
                sslcontext.init(null, new TrustManager[] { noCaTrustManager }, null);
                sslsf = new SSLConnectionSocketFactory(sslcontext, NoopHostnameVerifier.INSTANCE);
            } else {
                SSLContextBuilder sslContextBuilder = SSLContexts.custom();
                if (trustStoreFile != null) {
                    sslContextBuilder.loadTrustMaterial(new File(trustStoreFile), this.trustStorePassword != null ? this.trustStorePassword.toCharArray() : null);
                }
                SSLContext sslContext = sslContextBuilder.build();
                sslsf = new SSLConnectionSocketFactory(sslContext, new DefaultHostnameVerifier());
            }
            registry = RegistryBuilder.<ConnectionSocketFactory>create().register(HTTPS_PROTOCOL, sslsf).build();
        } catch (NoSuchAlgorithmException e) {
            throw new Error(NO_TLS_ERROR, e);
        } catch (KeyManagementException e) {
            throw new Error(BAD_KEY_ERROR, e);
        } catch (KeyStoreException e) {
            throw new Error(KEY_STORE_ERROR, e);
        } catch (FileNotFoundException e) {
            throw new Error(KEY_STORE_FILE_NOT_FOUND_ERROR, e);
        } catch (CertificateException e) {
            throw new Error(CERTIFICATE_ERROR, e);
        } catch (IOException e) {
            throw new Error(IO_ERROR, e);
        }
    } else {
        throw new Error(BAD_PROTOCOL_ERROR + protocol);
    }
    return registry;
}
Also used : LayeredConnectionSocketFactory(org.apache.http.conn.socket.LayeredConnectionSocketFactory) FileNotFoundException(java.io.FileNotFoundException) Error(org.ovirt.engine.sdk4.Error) CertificateException(java.security.cert.CertificateException) Registry(org.apache.http.config.Registry) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) KeyManagementException(java.security.KeyManagementException) TrustManager(javax.net.ssl.TrustManager) 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) DefaultHostnameVerifier(org.apache.http.conn.ssl.DefaultHostnameVerifier) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) File(java.io.File)

Example 5 with Registry

use of org.apache.http.config.Registry in project dropwizard by dropwizard.

the class HttpClientBuilderTest method canUseACustomHostnameVerifierWhenTlsConfigurationSpecified.

@Test
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 = getInaccessibleField(SSLConnectionSocketFactory.class, "hostnameVerifier");
    assertThat(hostnameVerifierField.get(socketFactory)).isSameAs(customVerifier);
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) 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) NTCredentials(org.apache.http.auth.NTCredentials) SystemDefaultDnsResolver(org.apache.http.impl.conn.SystemDefaultDnsResolver) Proxy(java.net.Proxy) InstrumentedHttpRequestExecutor(com.codahale.metrics.httpclient.InstrumentedHttpRequestExecutor) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) 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) HttpRequest(org.apache.http.HttpRequest) InetSocketAddress(java.net.InetSocketAddress) Test(org.junit.jupiter.api.Test) 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) 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) HttpRequestExecutor(org.apache.http.protocol.HttpRequestExecutor) Mockito.spy(org.mockito.Mockito.spy) Duration(io.dropwizard.util.Duration) ProxyConfiguration(io.dropwizard.client.proxy.ProxyConfiguration) ArgumentCaptor(org.mockito.ArgumentCaptor) Credentials(org.apache.http.auth.Credentials) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SystemDefaultRoutePlanner(org.apache.http.impl.conn.SystemDefaultRoutePlanner) HttpRequestRetryHandler(org.apache.http.client.HttpRequestRetryHandler) HTTP(org.apache.http.protocol.HTTP) Nullable(javax.annotation.Nullable) Environment(io.dropwizard.setup.Environment) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) MetricRegistry(com.codahale.metrics.MetricRegistry) AuthConfiguration(io.dropwizard.client.proxy.AuthConfiguration) ServiceUnavailableRetryStrategy(org.apache.http.client.ServiceUnavailableRetryStrategy) IOException(java.io.IOException) HttpProcessor(org.apache.http.protocol.HttpProcessor) Mockito.when(org.mockito.Mockito.when) 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) AfterEach(org.junit.jupiter.api.AfterEach) 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) Collections(java.util.Collections) 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.jupiter.api.Test)

Aggregations

Registry (org.apache.http.config.Registry)13 SSLConnectionSocketFactory (org.apache.http.conn.ssl.SSLConnectionSocketFactory)11 SSLContext (javax.net.ssl.SSLContext)9 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)9 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)9 IOException (java.io.IOException)8 ConnectionSocketFactory (org.apache.http.conn.socket.ConnectionSocketFactory)8 RegistryBuilder (org.apache.http.config.RegistryBuilder)7 HttpResponse (org.apache.http.HttpResponse)6 HttpGet (org.apache.http.client.methods.HttpGet)6 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)6 PlainConnectionSocketFactory (org.apache.http.conn.socket.PlainConnectionSocketFactory)5 KeyManagementException (java.security.KeyManagementException)4 KeyStoreException (java.security.KeyStoreException)4 RequestConfig (org.apache.http.client.config.RequestConfig)4 SSLContextBuilder (org.apache.http.ssl.SSLContextBuilder)4 ProxySelector (java.net.ProxySelector)3 URI (java.net.URI)3 CertificateException (java.security.cert.CertificateException)3 HostnameVerifier (javax.net.ssl.HostnameVerifier)3