Example usage for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory

List of usage examples for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory

Introduction

In this page you can find the example usage for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory.

Prototype

public SSLConnectionSocketFactory(final SSLContext sslContext) 

Source Link

Usage

From source file:org.osgpfoundation.osgp.webdemoapp.infra.platform.SoapRequestHelper.java

/**
 * Creates a HttpComponentsMessageSender for communication with the
 * platform./*from   w  w w . ja  v  a  2 s  .c  o  m*/
 *
 * @return HttpComponentsMessageSender
 */
private HttpComponentsMessageSender createHttpMessageSender() {

    final HttpComponentsMessageSender sender = new HttpComponentsMessageSender();

    final HttpClientBuilder builder = HttpClients.custom();
    builder.addInterceptorFirst(new ContentLengthHeaderRemoveInterceptor());
    try {
        final SSLContext sslContext = new SSLContextBuilder()
                .loadKeyMaterial(this.keyStoreHelper.getKeyStore(), this.keyStoreHelper.getKeyStorePwAsChar())
                .loadTrustMaterial(this.keyStoreHelper.getTrustStore()).build();
        final SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(sslContext);
        builder.setSSLSocketFactory(sslConnectionFactory);
        sender.setHttpClient(builder.build());
    } catch (KeyManagementException | UnrecoverableKeyException | NoSuchAlgorithmException
            | KeyStoreException e) {
        e.printStackTrace();
    }

    return sender;
}

From source file:com.arangodb.http.HttpManager.java

public void init() {
    // socket factory for HTTP
    ConnectionSocketFactory plainsf = new PlainConnectionSocketFactory();

    // socket factory for HTTPS
    SSLConnectionSocketFactory sslsf = null;
    if (configure.getSslContext() != null) {
        sslsf = new SSLConnectionSocketFactory(configure.getSslContext());
    } else {//from ww  w . ja v a2s .c  o  m
        sslsf = new SSLConnectionSocketFactory(SSLContexts.createSystemDefault());
    }

    // register socket factories
    Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", plainsf).register("https", sslsf).build();

    // ConnectionManager
    cm = new PoolingHttpClientConnectionManager(r);
    cm.setDefaultMaxPerRoute(configure.getMaxPerConnection());
    cm.setMaxTotal(configure.getMaxTotalConnection());

    Builder custom = RequestConfig.custom();

    // RequestConfig
    if (configure.getConnectionTimeout() >= 0) {
        custom.setConnectTimeout(configure.getConnectionTimeout());
    }
    if (configure.getTimeout() >= 0) {
        custom.setConnectionRequestTimeout(configure.getTimeout());
        custom.setSocketTimeout(configure.getTimeout());
    }
    custom.setStaleConnectionCheckEnabled(configure.isStaleConnectionCheck());

    RequestConfig requestConfig = custom.build();

    HttpClientBuilder builder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig);
    builder.setConnectionManager(cm);

    // KeepAlive Strategy
    ConnectionKeepAliveStrategy keepAliveStrategy = new ConnectionKeepAliveStrategy() {

        @Override
        public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
            // Honor 'keep-alive' header
            HeaderElementIterator it = new BasicHeaderElementIterator(
                    response.headerIterator(HTTP.CONN_KEEP_ALIVE));
            while (it.hasNext()) {
                HeaderElement he = it.nextElement();
                String param = he.getName();
                String value = he.getValue();
                if (value != null && param.equalsIgnoreCase("timeout")) {
                    try {
                        return Long.parseLong(value) * 1000;
                    } catch (NumberFormatException ignore) {
                    }
                }
            }
            // otherwise keep alive for 30 seconds
            return 30 * 1000;
        }

    };
    builder.setKeepAliveStrategy(keepAliveStrategy);

    // Retry Handler
    builder.setRetryHandler(new DefaultHttpRequestRetryHandler(configure.getRetryCount(), false));

    // Proxy
    if (configure.getProxyHost() != null && configure.getProxyPort() != 0) {
        HttpHost proxy = new HttpHost(configure.getProxyHost(), configure.getProxyPort(), "http");

        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
        builder.setRoutePlanner(routePlanner);
    }

    // Client
    client = builder.build();

    // Basic Auth
    // if (configure.getUser() != null && configure.getPassword() != null) {
    // AuthScope scope = AuthScope.ANY; // TODO
    // this.credentials = new
    // UsernamePasswordCredentials(configure.getUser(),
    // configure.getPassword());
    // client.getCredentialsProvider().setCredentials(scope, credentials);
    // }

}

From source file:mx.openpay.client.core.impl.DefaultHttpServiceClient.java

protected CloseableHttpClient initHttpClient(final boolean requirePoolManager, final int connectionTimeout,
        final int socketTimeout) {
    CloseableHttpClient httpClient;//from  ww w  .jav  a 2s.c om
    HttpClientConnectionManager manager;

    SSLConnectionSocketFactory sslSocketFactory;
    SSLContext tlsContext;
    try {
        try {
            tlsContext = new SSLContextBuilder().useProtocol("TLSv1.2").build();
        } catch (GeneralSecurityException e) {
            log.warn("Could not force protocol TLSv1.2: {}", e.getMessage());
            tlsContext = new SSLContextBuilder().build();
        }
        sslSocketFactory = new SSLConnectionSocketFactory(tlsContext);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    if (requirePoolManager) {
        manager = new PoolingHttpClientConnectionManager(
                RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslSocketFactory).build());
    } else {
        manager = new BasicHttpClientConnectionManager(
                RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslSocketFactory).build());
    }

    this.requestConfig = RequestConfig.custom().setConnectTimeout(connectionTimeout)
            .setSocketTimeout(socketTimeout).build();
    ConnectionConfig connnectionConfig = ConnectionConfig.custom().setCharset(Charset.forName("UTF-8")).build();
    httpClient = HttpClientBuilder.create().setConnectionManager(manager)
            .setDefaultConnectionConfig(connnectionConfig).setDefaultRequestConfig(this.requestConfig).build();
    return httpClient;
}

From source file:org.hawkular.client.RestFactory.java

public HttpClient getHttpClient() {
    SSLContextBuilder builder = new SSLContextBuilder();
    try {//from   w w  w  .  j a  v a 2s. c  o m
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        builder.loadTrustMaterial(keyStore, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] trustedCert, String nameConstraints)
                    throws CertificateException {
                return true;
            }
        });
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        return httpclient;

    } catch (Exception ex) {
        _logger.error("Exception, ", ex);
        return null;
    }
}

From source file:com.ethercamp.harmony.service.ImportContractIndexTest.java

@BeforeClass
public static void beforeClass() throws Exception {
    // ignore https errors
    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();

    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    Unirest.setHttpClient(httpclient);//from   w  w w .j  a va 2 s.c  o m

    SystemProperties.getDefault()
            .setBlockchainConfig(new FrontierConfig(new FrontierConfig.FrontierConstants() {
                @Override
                public BigInteger getMINIMUM_DIFFICULTY() {
                    return BigInteger.ONE;
                }
            }));
}

From source file:org.hawkular.client.core.jaxrs.RestFactory.java

private HttpClient getHttpClient() {
    CloseableHttpClient httpclient = null;

    try {/*from  ww  w. j  a v  a2 s  .co  m*/
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(keyStore, (TrustStrategy) (trustedCert, nameConstraints) -> true);

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
        httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        _logger.error("Failed to create HTTPClient: {}", e);
    }

    return httpclient;
}

From source file:ph.com.globe.connect.HttpRequest.java

/**
 * Send post request to the specified url.
 * //from   w  w w .ja v a2  s.  co  m
 * @return CloseableHttpResponse
 * @throws HttpRequestException http request exception
 */
public CloseableHttpResponse sendPost() throws HttpRequestException {
    // try building up
    try {
        // initialize ssl context builder
        SSLContextBuilder builder = new SSLContextBuilder();

        // set trust self signed strategy
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());

        // initialize ssl socket connection factory
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(builder.build());

        // default http client
        CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();

        // create request method
        HttpPost post = new HttpPost(this.url);

        // set default user agent
        post.setHeader("User-Agent", this.USER_AGENT);
        // set default content type
        post.setHeader("Content-Type", this.CONTENT_TYPE);

        // convert data to json string
        JSONObject data = new JSONObject(this.data);

        try {
            // set the string entity
            StringEntity entity = new StringEntity(data.toString());

            // set post data
            post.setEntity(entity);
        } catch (UnsupportedEncodingException e) {
            // throw exception
            throw new HttpRequestException(e.getMessage());
        }

        // try request
        try {
            // execute request and get the response
            CloseableHttpResponse response = client.execute(post);

            return response;
        } catch (IOException e) {
            // throw an exception
            throw new HttpRequestException(e.getMessage());
        }
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        // throw an exception
        throw new HttpRequestException(e.getMessage());
    }
}

From source file:com.ecofactor.qa.automation.consumerapi.dr.HTTPSClient.java

/**
 * Gets the http client./*from   w  w w .  ja  v a  2s. c o  m*/
 *
 * @param certificate the certificate
 * @param password the password
 * @return the http client
 */
public static CloseableHttpClient getPKCSKeyHttpClient(final String certificate, final String password) {

    try {
        final KeyStore keystore = KeyStore.getInstance("pkcs12");
        keystore.load(HTTPSClient.class.getClassLoader().getResourceAsStream(certificate),
                password.toCharArray());
        final SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadKeyMaterial(keystore, password.toCharArray());
        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());

        final CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf)
                .setHostnameVerifier(new AllowAllHostnameVerifier()).build();
        return httpClient;
    } catch (UnrecoverableKeyException | KeyManagementException | KeyStoreException | NoSuchAlgorithmException
            | CertificateException | IOException e) {
        LOGGER.error("Error processing SSL certificates in HTTPS method. Reason ::: " + e);
        return null;
    }
}