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 javax.net.ssl.SSLSocketFactory socketfactory,
            final String[] supportedProtocols, final String[] supportedCipherSuites,
            final X509HostnameVerifier hostnameVerifier) 

Source Link

Usage

From source file:org.openbaton.marketplace.core.VNFPackageManagement.java

private CloseableHttpClient getHttpClientForSsl(RequestConfig config) {
    SSLContext sslContext = null;
    try {/*from   w  ww  . ja  va2s . c  o m*/
        sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
    } catch (NoSuchAlgorithmException e) {
        log.error("Could not initialize the HttpClient for SSL connections");
        log.error(e.getMessage(), e);
    } catch (KeyManagementException e) {
        log.error("Could not initialize the HttpClient for SSL connections");
        log.error(e.getMessage(), e);
    } catch (KeyStoreException e) {
        log.error("Could not initialize the HttpClient for SSL connections");
        log.error(e.getMessage(), e);
    }

    // necessary to trust self signed certificates
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
            new String[] { "TLSv1" }, null, new NoopHostnameVerifier());

    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslConnectionSocketFactory).build();

    return HttpClientBuilder.create().setDefaultRequestConfig(config)
            .setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryRegistry))
            .setSSLSocketFactory(sslConnectionSocketFactory).build();
}

From source file:de.stklcode.jvault.connector.HTTPVaultConnector.java

/**
 * Create a custom socket factory from trusted CA certificate.
 *
 * @return The factory.//w  w  w.  ja v a2 s  .c om
 * @throws TlsException An error occured during initialization of the SSL context.
 * @since 0.8.0
 */
private SSLConnectionSocketFactory createSSLSocketFactory() throws TlsException {
    try {
        // Create Keystore with trusted certificate.
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setCertificateEntry("trustedCert", trustedCaCert);

        // Initialize TrustManager.
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);

        // Create context usint this TrustManager.
        SSLContext context = SSLContext.getInstance(tlsVersion);
        context.init(null, tmf.getTrustManagers(), new SecureRandom());

        return new SSLConnectionSocketFactory(context, null, null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException
            | KeyManagementException e) {
        throw new TlsException(Error.INIT_SSL_CONTEXT, e);
    }
}

From source file:com.gargoylesoftware.htmlunit.HttpWebConnection.java

/**
 * Has the exact logic in HttpClientBuilder, but with the ability to configure
 * <code>socketFactory</code>.
 *///  w w w. ja  v  a  2  s. c  o  m
private PoolingHttpClientConnectionManager createConnectionManager(final HttpClientBuilder builder) {
    final ConnectionSocketFactory socketFactory = new SocksConnectionSocketFactory();

    LayeredConnectionSocketFactory sslSocketFactory;
    try {
        sslSocketFactory = (LayeredConnectionSocketFactory) FieldUtils.readDeclaredField(builder,
                "sslSocketFactory", true);
        final SocketConfig defaultSocketConfig = (SocketConfig) FieldUtils.readDeclaredField(builder,
                "defaultSocketConfig", true);
        final ConnectionConfig defaultConnectionConfig = (ConnectionConfig) FieldUtils
                .readDeclaredField(builder, "defaultConnectionConfig", true);
        final boolean systemProperties = (Boolean) FieldUtils.readDeclaredField(builder, "systemProperties",
                true);
        final int maxConnTotal = (Integer) FieldUtils.readDeclaredField(builder, "maxConnTotal", true);
        final int maxConnPerRoute = (Integer) FieldUtils.readDeclaredField(builder, "maxConnPerRoute", true);
        HostnameVerifier hostnameVerifier = (HostnameVerifier) FieldUtils.readDeclaredField(builder,
                "hostnameVerifier", true);
        final SSLContext sslcontext = (SSLContext) FieldUtils.readDeclaredField(builder, "sslContext", true);

        if (sslSocketFactory == null) {
            final String[] supportedProtocols = systemProperties
                    ? StringUtils.split(System.getProperty("https.protocols"), ',')
                    : null;
            final String[] supportedCipherSuites = systemProperties
                    ? StringUtils.split(System.getProperty("https.cipherSuites"), ',')
                    : null;
            if (hostnameVerifier == null) {
                hostnameVerifier = SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
            }
            if (sslcontext != null) {
                sslSocketFactory = new SSLConnectionSocketFactory(sslcontext, supportedProtocols,
                        supportedCipherSuites, hostnameVerifier);
            } else {
                if (systemProperties) {
                    sslSocketFactory = new SSLConnectionSocketFactory(
                            (SSLSocketFactory) SSLSocketFactory.getDefault(), supportedProtocols,
                            supportedCipherSuites, hostnameVerifier);
                } else {
                    sslSocketFactory = new SSLConnectionSocketFactory(SSLContexts.createDefault(),
                            hostnameVerifier);
                }
            }
        }

        final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
                RegistryBuilder.<ConnectionSocketFactory>create().register("http", socketFactory)
                        .register("https", sslSocketFactory).build());
        if (defaultSocketConfig != null) {
            connectionManager.setDefaultSocketConfig(defaultSocketConfig);
        }
        if (defaultConnectionConfig != null) {
            connectionManager.setDefaultConnectionConfig(defaultConnectionConfig);
        }
        if (systemProperties) {
            String s = System.getProperty("http.keepAlive", "true");
            if ("true".equalsIgnoreCase(s)) {
                s = System.getProperty("http.maxConnections", "5");
                final int max = Integer.parseInt(s);
                connectionManager.setDefaultMaxPerRoute(max);
                connectionManager.setMaxTotal(2 * max);
            }
        }
        if (maxConnTotal > 0) {
            connectionManager.setMaxTotal(maxConnTotal);
        }
        if (maxConnPerRoute > 0) {
            connectionManager.setDefaultMaxPerRoute(maxConnPerRoute);
        }
        return connectionManager;
    } catch (final IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

From source file:net.geoprism.dashboard.DashboardMap.java

/**
 * Makes a getMap request to geoserver and returns the response as a ByteArrayOutputStream
 * /*from  ww w  .j  av a2s  . c  o  m*/
 * @throws NoSuchAlgorithmException
 * 
 * @requestURL = geoserver getMap() or getLegendGraphic() request url
 */
private byte[] requestGeoserverImage(String requestURL) {
    InputStream inStream = null;
    ByteArrayOutputStream outStream = null;
    CloseableHttpResponse response = null;
    CloseableHttpClient client = null;
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

        // StorePath and StorePass must be set for the systems keystore
        trustStore.load(new FileInputStream(GeoserverProperties.getGeoserverKeystorePath()),
                GeoserverProperties.getGeoserverKeystorePass().toCharArray());

        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(trustStore, GeoserverProperties.getGeoserverKeystorePass().toCharArray())
                .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();

        //
        // TODO: socket factory load once ever
        //
        SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
                new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        client = HttpClients.custom()
                // Allow all hostnames regardless of what is specified in the certificate
                .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
                // Use the provided SSL socket factory
                .setSSLSocketFactory(factory)
                // Set a default cookie store which will be used in all of the requests
                .setDefaultCookieStore(new BasicCookieStore()).build();
        HttpGet method = new HttpGet(requestURL);
        response = client.execute(method);
        inStream = response.getEntity().getContent();
        outStream = new ByteArrayOutputStream();
        // Copy the input stream to the output stream
        IOUtils.copy(inStream, outStream);
    } catch (MalformedURLException e) {
        String error = "The URL is not formated correctly.";
        throw new ProgrammingErrorException(error, e);
    } catch (IOException e) {
        String error = "Could not make the request to the map server.";
        throw new ProgrammingErrorException(error, e);
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (inStream != null) {
            try {
                inStream.close();
            } catch (IOException e) {
                String error = "Could not close stream.";
                throw new ProgrammingErrorException(error, e);
            }
        }

        if (outStream != null) {
            try {
                outStream.close();
            } catch (IOException e) {
                String error = "Could not close stream.";
                throw new ProgrammingErrorException(error, e);
            }
        }
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                String error = "Could not close stream.";
                throw new ProgrammingErrorException(error, e);
            }
        }
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                String error = "Could not close stream.";
                throw new ProgrammingErrorException(error, e);
            }
        }
    }

    return outStream.toByteArray();
}

From source file:ddf.test.itests.platform.TestSecurity.java

private HttpClient createHttpClient(String protocol, String[] cipherSuites,
        CredentialsProvider credentialsProvider) throws KeyManagementException, NoSuchAlgorithmException {
    SSLContext context = SSLContexts.custom().useProtocol(protocol).build();

    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(context, null, cipherSuites,
            SSLConnectionSocketFactory.getDefaultHostnameVerifier());

    return HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider)
            .setSSLSocketFactory(socketFactory).build();
}

From source file:org.apache.http.conn.ssl.SSLConnectionSocketFactory.java

/**
 * Obtains default SSL socket factory with an SSL context based on system properties
 * as described in/*from   w  w w  .  j av a2  s .  co m*/
 * <a href="http://docs.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html">
 * Java&#x2122; Secure Socket Extension (JSSE) Reference Guide</a>.
 *
 * @return default system SSL socket factory
 */
public static SSLConnectionSocketFactory getSystemSocketFactory() throws SSLInitializationException {
    return new SSLConnectionSocketFactory(
            (javax.net.ssl.SSLSocketFactory) javax.net.ssl.SSLSocketFactory.getDefault(),
            split(System.getProperty("https.protocols")), split(System.getProperty("https.cipherSuites")),
            getDefaultHostnameVerifier());
}

From source file:org.codice.solr.factory.impl.HttpClientBuilder.java

public org.apache.http.impl.client.HttpClientBuilder get() {

    final org.apache.http.impl.client.HttpClientBuilder httpClientBuilder = HttpClients.custom()
            .setDefaultCookieStore(new BasicCookieStore()).setMaxConnTotal(128).setMaxConnPerRoute(32);

    if (useTls()) {
        String[] defaultProtocols = AccessController.doPrivileged(
                (PrivilegedAction<String[]>) () -> commaSeparatedToArray(System.getProperty(HTTPS_PROTOCOLS)));

        String[] defaultCipherSuites = AccessController
                .doPrivileged((PrivilegedAction<String[]>) () -> commaSeparatedToArray(
                        System.getProperty(HTTPS_CIPHER_SUITES)));

        httpClientBuilder.setSSLSocketFactory(new SSLConnectionSocketFactory(getSslContext(), defaultProtocols,
                defaultCipherSuites, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER));
    }//w  ww .ja v  a2s .co  m
    if (isConfiguredForBasicAuth()) {
        httpClientBuilder.setDefaultCredentialsProvider(getCredentialsProvider());
        httpClientBuilder.addInterceptorFirst(new PreemptiveAuth(new BasicScheme()));
    }
    return httpClientBuilder;
}

From source file:org.codice.solr.factory.SolrClientFactory.java

private static CloseableHttpClient getHttpClient(boolean retryRequestsOnError) {
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(getSslContext(),
            getProtocols(), getCipherSuites(), SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    HttpRequestRetryHandler solrRetryHandler = new SolrHttpRequestRetryHandler();

    HttpClientBuilder builder = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory)
            .setDefaultCookieStore(new BasicCookieStore()).setMaxConnTotal(128).setMaxConnPerRoute(32);

    if (retryRequestsOnError) {
        builder.setRetryHandler(solrRetryHandler);
    }//from   w  ww  .j  a  v  a  2s  . c o  m

    return builder.build();
}

From source file:org.codice.solr.factory.SolrServerFactory.java

private static CloseableHttpClient getHttpClient() {
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(getSslContext(),
            getProtocols(), getCipherSuites(), SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

    return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory)
            .setDefaultCookieStore(new BasicCookieStore()).setMaxConnTotal(128).setMaxConnPerRoute(32).build();
}

From source file:org.openhab.binding.fritzboxtr064.internal.Tr064Comm.java

/**
 * Creates an Apache HTTP Client object, ignoring SSL Exceptions like self signed
 * certificates, and sets Auth. Scheme to Digest Auth.
 *
 * @param fboxUrl/*from w  w  w.ja  v  a2 s . c  om*/
 *            the URL from config file of fbox to connect to
 * @return the ready-to-use httpclient for tr064 requests
 */
private synchronized CloseableHttpClient createTr064HttpClient(String fboxUrl) {
    CloseableHttpClient hc = null;
    // Convert URL String from config in easy explotable URI object
    URIBuilder uriFbox = null;
    try {
        uriFbox = new URIBuilder(fboxUrl);
    } catch (URISyntaxException e) {
        logger.error("Invalid FritzBox URL! {}", e.getMessage());
        return null;
    }
    // Create context of the http client
    _httpClientContext = HttpClientContext.create();
    CookieStore cookieStore = new BasicCookieStore();
    _httpClientContext.setCookieStore(cookieStore);

    // SETUP AUTH
    // Auth is specific for this target
    HttpHost target = new HttpHost(uriFbox.getHost(), uriFbox.getPort(), uriFbox.getScheme());
    // Add digest authentication with username/pw from global config
    CredentialsProvider credp = new BasicCredentialsProvider();
    credp.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(_user, _pw));
    // Create AuthCache instance. Manages authentication based on server response
    AuthCache authCache = new BasicAuthCache();
    // Generate DIGEST scheme object, initialize it and add it to the local auth
    // cache. Digeste is standard for fbox auth SOAP
    DigestScheme digestAuth = new DigestScheme();
    digestAuth.overrideParamter("realm", "HTTPS Access"); // known from fbox specification
    digestAuth.overrideParamter("nonce", ""); // never known at first request
    authCache.put(target, digestAuth);
    // Add AuthCache to the execution context
    _httpClientContext.setAuthCache(authCache);

    // SETUP SSL TRUST
    SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
    SSLConnectionSocketFactory sslsf = null;
    try {
        sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); // accept self signed certs
        // dont verify hostname against cert CN
        sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), null, null,
                new NoopHostnameVerifier());
    } catch (Exception ex) {
        logger.error(ex.getMessage());
    }

    // Set timeout values
    RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(4000).setConnectTimeout(4000)
            .setConnectionRequestTimeout(4000).build();

    // BUILDER
    // setup builder with parameters defined before
    hc = HttpClientBuilder.create().setSSLSocketFactory(sslsf) // set the SSL options which trust every self signed
            // cert
            .setDefaultCredentialsProvider(credp) // set auth options using digest
            .setDefaultRequestConfig(rc) // set the request config specifying timeout
            .build();

    return hc;
}