Search in sources :

Example 26 with SSLConnectionSocketFactory

use of org.apache.http.conn.ssl.SSLConnectionSocketFactory in project credhub by cloudfoundry-incubator.

the class RestTemplateFactory method createRestTemplate.

public RestTemplate createRestTemplate(String trustStorePath, String trustStorePassword) throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, KeyManagementException {
    File trustStore = new File(trustStorePath);
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(trustStore, trustStorePassword.toCharArray()).build();
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext);
    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
    return new RestTemplate(requestFactory);
}
Also used : HttpClient(org.apache.http.client.HttpClient) RestTemplate(org.springframework.web.client.RestTemplate) SSLContext(javax.net.ssl.SSLContext) HttpComponentsClientHttpRequestFactory(org.springframework.http.client.HttpComponentsClientHttpRequestFactory) File(java.io.File) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory)

Example 27 with SSLConnectionSocketFactory

use of org.apache.http.conn.ssl.SSLConnectionSocketFactory in project LogHub by fbacchella.

the class AbstractHttpSender method configure.

@Override
public boolean configure(Properties properties) {
    endPoints = Helpers.stringsToUrl(destinations, port, protocol, logger);
    if (endPoints.length == 0) {
        return false;
    }
    // Create the senders threads and the common queue
    batch = new Batch();
    threads = new Thread[publisherThreads];
    for (int i = 1; i <= publisherThreads; i++) {
        String tname = getPublishName() + "Publisher" + i;
        threads[i - 1] = new Thread(publisher) {

            {
                setDaemon(false);
                setName(tname);
                start();
            }
        };
    }
    // The HTTP connection management
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setUserAgent(VersionInfo.getUserAgent("LogHub-HttpClient", "org.apache.http.client", HttpClientBuilder.class));
    // Set the Configuration manager
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", new SSLConnectionSocketFactory(properties.ssl)).build();
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
    cm.setDefaultMaxPerRoute(2);
    cm.setMaxTotal(2 * publisherThreads);
    cm.setValidateAfterInactivity(timeout * 1000);
    builder.setConnectionManager(cm);
    if (properties.ssl != null) {
        builder.setSSLContext(properties.ssl);
    }
    builder.setDefaultRequestConfig(RequestConfig.custom().setConnectionRequestTimeout(timeout * 1000).setConnectTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build());
    builder.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).setSoKeepAlive(true).setSoTimeout(timeout * 1000).build());
    builder.setDefaultConnectionConfig(ConnectionConfig.custom().build());
    builder.disableCookieManagement();
    builder.setRetryHandler(new HttpRequestRetryHandler() {

        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            return false;
        }
    });
    client = builder.build();
    if (user != null && password != null) {
        credsProvider = new BasicCredentialsProvider();
        for (URL i : endPoints) {
            credsProvider.setCredentials(new AuthScope(i.getHost(), i.getPort()), new UsernamePasswordCredentials(user, password));
        }
    }
    // Schedule a task to flush every 5 seconds
    Runnable flush = () -> {
        synchronized (publisher) {
            long now = new Date().getTime();
            if ((now - lastFlush) > 5000) {
                batches.add(batch);
                batch = new Batch();
                publisher.notify();
            }
        }
    };
    properties.registerScheduledTask(getPublishName() + "Flusher", flush, 5000);
    return true;
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpContext(org.apache.http.protocol.HttpContext) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) URL(java.net.URL) Date(java.util.Date) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) AuthScope(org.apache.http.auth.AuthScope) HttpRequestRetryHandler(org.apache.http.client.HttpRequestRetryHandler)

Example 28 with SSLConnectionSocketFactory

use of org.apache.http.conn.ssl.SSLConnectionSocketFactory in project LogHub by fbacchella.

the class TestHttpSsl method TestHcComplex.

@Test
public void TestHcComplex() throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, KeyManagementException {
    CloseableHttpClient client = null;
    ;
    try {
        int publisherThreads = 1;
        int timeout = 2;
        // The HTTP connection management
        HttpClientBuilder builder = HttpClientBuilder.create();
        builder.setUserAgent(VersionInfo.getUserAgent("LogHub-HttpClient", "org.apache.http.client", HttpClientBuilder.class));
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", new SSLConnectionSocketFactory(getContext.get(), localhostVerifier)).build();
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
        cm.setDefaultMaxPerRoute(2);
        cm.setMaxTotal(2 * publisherThreads);
        cm.setValidateAfterInactivity(timeout * 1000);
        builder.setConnectionManager(cm);
        builder.setDefaultRequestConfig(RequestConfig.custom().setConnectionRequestTimeout(timeout * 1000).setConnectTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build());
        builder.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).setSoKeepAlive(true).setSoTimeout(timeout * 1000).build());
        builder.setDefaultConnectionConfig(ConnectionConfig.custom().setCharset(Charset.forName("UTF-8")).build());
        builder.disableCookieManagement();
        client = builder.build();
        HttpClientContext context = HttpClientContext.create();
        HttpHost host;
        RequestLine requestLine = new BasicRequestLine("GET", theurl.getPath(), HttpVersion.HTTP_1_1);
        BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest(requestLine);
        host = new HttpHost(theurl.getHost(), theurl.getPort(), "https");
        CloseableHttpResponse response = client.execute(host, request, context);
        Assert.assertEquals(200, response.getStatusLine().getStatusCode());
        try {
            HttpEntity entity = response.getEntity();
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        if (client != null) {
            client.close();
        }
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpEntity(org.apache.http.HttpEntity) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) RequestLine(org.apache.http.RequestLine) BasicRequestLine(org.apache.http.message.BasicRequestLine) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) HttpHost(org.apache.http.HttpHost) BasicRequestLine(org.apache.http.message.BasicRequestLine) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) BasicHttpEntityEnclosingRequest(org.apache.http.message.BasicHttpEntityEnclosingRequest) Test(org.junit.Test)

Example 29 with SSLConnectionSocketFactory

use of org.apache.http.conn.ssl.SSLConnectionSocketFactory in project fabric8 by fabric8io.

the class JolokiaClients method createJolokiaClient.

protected J4pClient createJolokiaClient(Container container, String jolokiaUrl) {
    String name = container.getName();
    LOG.debug("Creating jolokia client for : " + name + " at URL: " + jolokiaUrl);
    J4pClientBuilder builder = J4pClient.url(jolokiaUrl);
    if (useKubeProxy) {
        // When using the https proxy, inject the Kubernetes client's SSL context
        URL masterUrl = getKubernetes().getMasterUrl();
        if (masterUrl != null && masterUrl.toString().startsWith("https")) {
            try {
                SSLContext sslCtx = SSLUtils.sslContext(kubernetes.getConfiguration());
                ConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslCtx);
                builder = builder.sslConnectionSocketFactory(factory);
            } catch (Exception e) {
                LOG.warn("Unable to inject the Kubernetes SSL context into the Jolokia client. Using the default context", e);
            }
        }
    }
    AuthenticationMode mode = locateAuthenticationMode();
    switch(mode) {
        case BEARER:
            builder = builder.authenticator(new BearerTokenAuthenticator());
            String token = kubernetes.getConfiguration().getOauthToken();
            builder = builder.user(token);
            break;
        case BASIC:
            builder = builder.authenticator(new BasicAuthenticator());
            if (Strings.isNotBlank(user)) {
                builder = builder.user(user);
            }
            if (Strings.isNotBlank(password)) {
                builder = builder.password(password);
            }
            break;
        default:
            throw new IllegalStateException("Unsupported authentication mode: " + mode);
    }
    return builder.build();
}
Also used : ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) BasicAuthenticator(org.jolokia.client.BasicAuthenticator) J4pClientBuilder(org.jolokia.client.J4pClientBuilder) SSLContext(javax.net.ssl.SSLContext) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) URL(java.net.URL)

Example 30 with SSLConnectionSocketFactory

use of org.apache.http.conn.ssl.SSLConnectionSocketFactory in project ovirt-engine by oVirt.

the class HttpClientBuilder method build.

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);
                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);
        poolManager.setValidateAfterInactivity(validateAfterInactivity == null ? 100 : validateAfterInactivity);
        connectionManager = poolManager;
    } else {
        connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry);
    }
    // Create the client:
    return org.apache.http.impl.client.HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).setSSLHostnameVerifier(sslHostnameVerifier).setConnectionManager(connectionManager).setRetryHandler(new StandardHttpRequestRetryHandler(retryCount == null ? 1 : retryCount, true)).build();
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) SSLContext(javax.net.ssl.SSLContext) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) KeyStore(java.security.KeyStore) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) HostnameVerifier(javax.net.ssl.HostnameVerifier) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) StandardHttpRequestRetryHandler(org.apache.http.impl.client.StandardHttpRequestRetryHandler) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) X509TrustManager(javax.net.ssl.X509TrustManager) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) 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)

Aggregations

SSLConnectionSocketFactory (org.apache.http.conn.ssl.SSLConnectionSocketFactory)179 SSLContext (javax.net.ssl.SSLContext)109 ConnectionSocketFactory (org.apache.http.conn.socket.ConnectionSocketFactory)72 PlainConnectionSocketFactory (org.apache.http.conn.socket.PlainConnectionSocketFactory)61 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)58 SSLContextBuilder (org.apache.http.ssl.SSLContextBuilder)58 IOException (java.io.IOException)49 TrustSelfSignedStrategy (org.apache.http.conn.ssl.TrustSelfSignedStrategy)45 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)44 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)41 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)35 KeyManagementException (java.security.KeyManagementException)34 NoopHostnameVerifier (org.apache.http.conn.ssl.NoopHostnameVerifier)33 HttpClient (org.apache.http.client.HttpClient)28 RequestConfig (org.apache.http.client.config.RequestConfig)28 KeyStoreException (java.security.KeyStoreException)27 KeyStore (java.security.KeyStore)26 HostnameVerifier (javax.net.ssl.HostnameVerifier)26 CertificateException (java.security.cert.CertificateException)24 HttpComponentsClientHttpRequestFactory (org.springframework.http.client.HttpComponentsClientHttpRequestFactory)24