Search in sources :

Example 6 with HttpClientConnectionManager

use of org.apache.http.conn.HttpClientConnectionManager in project openremote by openremote.

the class ExtensibleResteasyClientBuilder method initDefaultEngine43.

// The rest is copy/paste pretty much
public static ApacheHttpClient43Engine initDefaultEngine43(ExtensibleResteasyClientBuilder that) {
    HttpClient httpClient = null;
    HostnameVerifier verifier = null;
    if (that.verifier != null) {
        verifier = new ExtensibleResteasyClientBuilder.VerifierWrapper(that.verifier);
    } else {
        switch(that.policy) {
            case ANY:
                verifier = new NoopHostnameVerifier();
                break;
            case WILDCARD:
                verifier = new DefaultHostnameVerifier();
                break;
            case STRICT:
                verifier = new DefaultHostnameVerifier();
                break;
        }
    }
    try {
        SSLConnectionSocketFactory sslsf = null;
        SSLContext theContext = that.sslContext;
        if (that.disableTrustManager) {
            theContext = SSLContext.getInstance("SSL");
            theContext.init(null, new TrustManager[] { new PassthroughTrustManager() }, new SecureRandom());
            verifier = new NoopHostnameVerifier();
            sslsf = new SSLConnectionSocketFactory(theContext, verifier);
        } else if (theContext != null) {
            sslsf = new SSLConnectionSocketFactory(theContext, verifier) {

                @Override
                protected void prepareSocket(SSLSocket socket) throws IOException {
                    that.prepareSocketForSni(socket);
                }
            };
        } else if (that.clientKeyStore != null || that.truststore != null) {
            SSLContext ctx = SSLContexts.custom().useProtocol(SSLConnectionSocketFactory.TLS).setSecureRandom(null).loadKeyMaterial(that.clientKeyStore, that.clientPrivateKeyPassword != null ? that.clientPrivateKeyPassword.toCharArray() : null).loadTrustMaterial(that.truststore, TrustSelfSignedStrategy.INSTANCE).build();
            sslsf = new SSLConnectionSocketFactory(ctx, verifier) {

                @Override
                protected void prepareSocket(SSLSocket socket) throws IOException {
                    that.prepareSocketForSni(socket);
                }
            };
        } else {
            final SSLContext tlsContext = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
            tlsContext.init(null, null, null);
            sslsf = new SSLConnectionSocketFactory(tlsContext, verifier);
        }
        final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslsf).build();
        HttpClientConnectionManager cm = null;
        if (that.connectionPoolSize > 0) {
            PoolingHttpClientConnectionManager tcm = new PoolingHttpClientConnectionManager(registry, null, null, null, that.connectionTTL, that.connectionTTLUnit);
            tcm.setMaxTotal(that.connectionPoolSize);
            if (that.maxPooledPerRoute == 0) {
                that.maxPooledPerRoute = that.connectionPoolSize;
            }
            tcm.setDefaultMaxPerRoute(that.maxPooledPerRoute);
            cm = tcm;
        } else {
            cm = new BasicHttpClientConnectionManager(registry);
        }
        RequestConfig.Builder rcBuilder = RequestConfig.custom();
        if (that.socketTimeout > -1) {
            rcBuilder.setSocketTimeout((int) that.socketTimeoutUnits.toMillis(that.socketTimeout));
        }
        if (that.establishConnectionTimeout > -1) {
            rcBuilder.setConnectTimeout((int) that.establishConnectionTimeoutUnits.toMillis(that.establishConnectionTimeout));
        }
        if (that.connectionCheckoutTimeoutMs > -1) {
            rcBuilder.setConnectionRequestTimeout(that.connectionCheckoutTimeoutMs);
        }
        // The magic configure()
        httpClient = that.configure(HttpClientBuilder.create().setConnectionManager(cm).setDefaultRequestConfig(rcBuilder.build()).setProxy(that.defaultProxy).disableContentCompression()).build();
        ApacheHttpClient43Engine engine = (ApacheHttpClient43Engine) ApacheHttpClient4EngineFactory.create(httpClient, true);
        engine.setResponseBufferSize(that.responseBufferSize);
        engine.setHostnameVerifier(verifier);
        // this may be null.  We can't really support this with Apache Client.
        engine.setSslContext(theContext);
        return engine;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) PassthroughTrustManager(org.jboss.resteasy.client.jaxrs.engines.PassthroughTrustManager) SecureRandom(java.security.SecureRandom) IOException(java.io.IOException) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ApacheHttpClient43Engine(org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient43Engine) IOException(java.io.IOException) DefaultHostnameVerifier(org.apache.http.conn.ssl.DefaultHostnameVerifier) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) DefaultHostnameVerifier(org.apache.http.conn.ssl.DefaultHostnameVerifier) HttpClient(org.apache.http.client.HttpClient) HttpClientConnectionManager(org.apache.http.conn.HttpClientConnectionManager) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager)

Example 7 with HttpClientConnectionManager

use of org.apache.http.conn.HttpClientConnectionManager in project jersey by jersey.

the class HelloWorldTest method testAsyncClientRequests.

@Test
public void testAsyncClientRequests() throws InterruptedException {
    HttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    ClientConfig cc = new ClientConfig();
    cc.property(ApacheClientProperties.CONNECTION_MANAGER, connectionManager);
    cc.connectorProvider(new ApacheConnectorProvider());
    Client client = ClientBuilder.newClient(cc);
    WebTarget target = client.target(getBaseUri());
    final int REQUESTS = 20;
    final CountDownLatch latch = new CountDownLatch(REQUESTS);
    final long tic = System.currentTimeMillis();
    final Map<Integer, String> results = new ConcurrentHashMap<Integer, String>();
    for (int i = 0; i < REQUESTS; i++) {
        final int id = i;
        target.path(ROOT_PATH).request().async().get(new InvocationCallback<Response>() {

            @Override
            public void completed(Response response) {
                try {
                    final String result = response.readEntity(String.class);
                    results.put(id, result);
                } finally {
                    latch.countDown();
                }
            }

            @Override
            public void failed(Throwable error) {
                Logger.getLogger(HelloWorldTest.class.getName()).log(Level.SEVERE, "Failed on throwable", error);
                results.put(id, "error: " + error.getMessage());
                latch.countDown();
            }
        });
    }
    assertTrue(latch.await(10 * getAsyncTimeoutMultiplier(), TimeUnit.SECONDS));
    final long toc = System.currentTimeMillis();
    Logger.getLogger(HelloWorldTest.class.getName()).info("Executed in: " + (toc - tic));
    StringBuilder resultInfo = new StringBuilder("Results:\n");
    for (int i = 0; i < REQUESTS; i++) {
        String result = results.get(i);
        resultInfo.append(i).append(": ").append(result).append('\n');
    }
    Logger.getLogger(HelloWorldTest.class.getName()).info(resultInfo.toString());
    for (int i = 0; i < REQUESTS; i++) {
        String result = results.get(i);
        assertEquals(HelloWorldResource.CLICHED_MESSAGE, result);
    }
}
Also used : CountDownLatch(java.util.concurrent.CountDownLatch) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Response(javax.ws.rs.core.Response) HttpResponse(org.apache.http.HttpResponse) WebTarget(javax.ws.rs.client.WebTarget) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) HttpClientConnectionManager(org.apache.http.conn.HttpClientConnectionManager) ClientConfig(org.glassfish.jersey.client.ClientConfig) Client(javax.ws.rs.client.Client) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) JerseyTest(org.glassfish.jersey.test.JerseyTest) Test(org.junit.Test)

Example 8 with HttpClientConnectionManager

use of org.apache.http.conn.HttpClientConnectionManager in project wildfly by wildfly.

the class WebSecurityCERTTestCase method getHttpsClient.

private static CloseableHttpClient getHttpsClient(String alias) {
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        JBossJSSESecurityDomain jsseSecurityDomain = new JBossJSSESecurityDomain("client-cert");
        jsseSecurityDomain.setKeyStorePassword("changeit");
        ClassLoader tccl = Thread.currentThread().getContextClassLoader();
        URL keystore = tccl.getResource("security/client.keystore");
        jsseSecurityDomain.setKeyStoreURL(keystore.getPath());
        jsseSecurityDomain.setClientAlias(alias);
        jsseSecurityDomain.reloadKeyAndTrustStore();
        KeyManager[] keyManagers = jsseSecurityDomain.getKeyManagers();
        TrustManager[] trustManagers = jsseSecurityDomain.getTrustManagers();
        ctx.init(keyManagers, trustManagers, null);
        HostnameVerifier verifier = (string, ssls) -> true;
        //SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(ctx, verifier);
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", ssf).build();
        HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);
        return HttpClientBuilder.create().setSSLSocketFactory(ssf).setSSLHostnameVerifier(new NoopHostnameVerifier()).setConnectionManager(ccm).build();
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}
Also used : SSLContext(javax.net.ssl.SSLContext) RegistryBuilder(org.apache.http.config.RegistryBuilder) Arquillian(org.jboss.arquillian.junit.Arquillian) URL(java.net.URL) ServerSetup(org.jboss.as.arquillian.api.ServerSetup) RunWith(org.junit.runner.RunWith) TrustManager(javax.net.ssl.TrustManager) JBossJSSESecurityDomain(org.jboss.security.JBossJSSESecurityDomain) WebCERTTestsSecurityDomainSetup(org.jboss.as.test.integration.web.security.WebCERTTestsSecurityDomainSetup) StatusLine(org.apache.http.StatusLine) RunAsClient(org.jboss.arquillian.container.test.api.RunAsClient) Registry(org.apache.http.config.Registry) ArquillianResource(org.jboss.arquillian.test.api.ArquillianResource) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) HostnameVerifier(javax.net.ssl.HostnameVerifier) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) ShrinkWrap(org.jboss.shrinkwrap.api.ShrinkWrap) WebArchive(org.jboss.shrinkwrap.api.spec.WebArchive) CommonCriteria(org.jboss.as.test.categories.CommonCriteria) Test(org.junit.Test) HttpClientConnectionManager(org.apache.http.conn.HttpClientConnectionManager) Category(org.junit.experimental.categories.Category) KeyManager(javax.net.ssl.KeyManager) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) HttpGet(org.apache.http.client.methods.HttpGet) Deployment(org.jboss.arquillian.container.test.api.Deployment) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) HttpResponse(org.apache.http.HttpResponse) SecuredServlet(org.jboss.as.test.integration.web.security.SecuredServlet) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) ManagementClient(org.jboss.as.arquillian.container.ManagementClient) Assert.assertEquals(org.junit.Assert.assertEquals) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) SSLContext(javax.net.ssl.SSLContext) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) JBossJSSESecurityDomain(org.jboss.security.JBossJSSESecurityDomain) URL(java.net.URL) TrustManager(javax.net.ssl.TrustManager) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) HostnameVerifier(javax.net.ssl.HostnameVerifier) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) HttpClientConnectionManager(org.apache.http.conn.HttpClientConnectionManager) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) KeyManager(javax.net.ssl.KeyManager) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager)

Example 9 with HttpClientConnectionManager

use of org.apache.http.conn.HttpClientConnectionManager in project ats-framework by Axway.

the class HttpsClient method connect.

/**
     * Connect to a remote host using basic authentication.
     *
     * @param hostname the host to connect to
     * @param userName the user name
     * @param password the password for the provided user name
     * @throws FileTransferException
     */
@Override
public void connect(String hostname, String userName, String password) throws FileTransferException {
    super.connect(hostname, userName, password);
    // trust everybody
    try {
        SSLContext sslContext = SslUtils.getTrustAllSSLContext();
        SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(sslContext, encryptionProtocols, cipherSuites, new NoopHostnameVerifier());
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", ssf).build();
        HttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        this.httpBuilder.setConnectionManager(connectionManager).setSchemePortResolver(new DefaultSchemePortResolver());
        this.httpClient = this.httpBuilder.build();
    } catch (Exception e) {
        throw new FileTransferException("Error setting trust manager", e);
    }
}
Also used : FileTransferException(com.axway.ats.common.filetransfer.FileTransferException) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) DefaultSchemePortResolver(org.apache.http.impl.conn.DefaultSchemePortResolver) SSLContext(javax.net.ssl.SSLContext) HttpClientConnectionManager(org.apache.http.conn.HttpClientConnectionManager) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) CertificateException(java.security.cert.CertificateException) GeneralSecurityException(java.security.GeneralSecurityException) FileTransferException(com.axway.ats.common.filetransfer.FileTransferException) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager)

Aggregations

HttpClientConnectionManager (org.apache.http.conn.HttpClientConnectionManager)9 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)6 ConnectionSocketFactory (org.apache.http.conn.socket.ConnectionSocketFactory)5 SSLConnectionSocketFactory (org.apache.http.conn.ssl.SSLConnectionSocketFactory)5 SSLContext (javax.net.ssl.SSLContext)4 NoopHostnameVerifier (org.apache.http.conn.ssl.NoopHostnameVerifier)4 BasicHttpClientConnectionManager (org.apache.http.impl.conn.BasicHttpClientConnectionManager)4 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)3 Test (org.junit.Test)3 IOException (java.io.IOException)2 CertificateException (java.security.cert.CertificateException)2 HashMap (java.util.HashMap)2 Client (javax.ws.rs.client.Client)2 WebTarget (javax.ws.rs.client.WebTarget)2 HttpResponse (org.apache.http.HttpResponse)2 PlainConnectionSocketFactory (org.apache.http.conn.socket.PlainConnectionSocketFactory)2 ClientConfig (org.glassfish.jersey.client.ClientConfig)2 FileTransferException (com.axway.ats.common.filetransfer.FileTransferException)1 URI (java.net.URI)1 URL (java.net.URL)1