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

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

Introduction

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

Prototype

public SSLSocketFactory(final SSLContext sslContext) 

Source Link

Usage

From source file:org.apache.ambari.view.hive.client.Connection.java

SSLSocketFactory getTwoWaySSLSocketFactory() throws SQLException {
    SSLSocketFactory socketFactory = null;

    try {//from ww w .  j  a  va  2  s. c o  m
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
                Utils.HiveAuthenticationParams.SUNX509_ALGORITHM_STRING,
                Utils.HiveAuthenticationParams.SUNJSSE_ALGORITHM_STRING);
        String keyStorePath = authParams.get(Utils.HiveAuthenticationParams.SSL_KEY_STORE);
        String keyStorePassword = authParams.get(Utils.HiveAuthenticationParams.SSL_KEY_STORE_PASSWORD);
        KeyStore sslKeyStore = KeyStore.getInstance(Utils.HiveAuthenticationParams.SSL_KEY_STORE_TYPE);

        if (keyStorePath == null || keyStorePath.isEmpty()) {
            throw new IllegalArgumentException(Utils.HiveAuthenticationParams.SSL_KEY_STORE
                    + " Not configured for 2 way SSL connection, keyStorePath param is empty");
        }
        try (FileInputStream fis = new FileInputStream(keyStorePath)) {
            sslKeyStore.load(fis, keyStorePassword.toCharArray());
        }
        keyManagerFactory.init(sslKeyStore, keyStorePassword.toCharArray());

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(Utils.HiveAuthenticationParams.SUNX509_ALGORITHM_STRING);
        String trustStorePath = authParams.get(Utils.HiveAuthenticationParams.SSL_TRUST_STORE);
        String trustStorePassword = authParams.get(Utils.HiveAuthenticationParams.SSL_TRUST_STORE_PASSWORD);
        KeyStore sslTrustStore = KeyStore.getInstance(Utils.HiveAuthenticationParams.SSL_TRUST_STORE_TYPE);

        if (trustStorePath == null || trustStorePath.isEmpty()) {
            throw new IllegalArgumentException(Utils.HiveAuthenticationParams.SSL_TRUST_STORE
                    + " Not configured for 2 way SSL connection");
        }
        try (FileInputStream fis = new FileInputStream(trustStorePath)) {
            sslTrustStore.load(fis, trustStorePassword.toCharArray());
        }
        trustManagerFactory.init(sslTrustStore);
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
                new SecureRandom());
        socketFactory = new SSLSocketFactory(context);
    } catch (Exception e) {
        throw new SQLException("Error while initializing 2 way ssl socket factory ", e);
    }
    return socketFactory;
}

From source file:uk.ac.bbsrc.tgac.miso.core.manager.ERASubmissionManager.java

/**
 * Builds a "trusting" trust manager. This is totally horrible and basically ignores everything that SSL stands for.
 * This allows connection to self-signed certificate hosts, bypassing the normal validation exceptions that occur.
 * <p/>// w  ww. j av  a2 s.c o m
 * Use at your own risk - again, this is horrible!
 */
public DefaultHttpClient getEvilTrustingTrustManager(DefaultHttpClient httpClient) {
    try {
        // First create a trust manager that won't care about any SSL self-cert problems - eurgh!
        X509TrustManager trustManager = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
                log.warn("BYPASSING CLIENT TRUSTED CHECK!");
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
                log.warn("BYPASSING SERVER TRUSTED CHECK!");
            }

            public X509Certificate[] getAcceptedIssuers() {
                log.warn("BYPASSING CERTIFICATE ISSUER CHECKS!");
                return null;
            }
        };

        // Now put the trust manager into an SSLContext
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null, new TrustManager[] { trustManager }, null);
        SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        // If you want a thread safe client, use the ThreadSafeConManager, but
        // otherwise just grab the one from the current client, and get hold of its
        // schema registry. THIS IS THE KEY THING.
        ClientConnectionManager ccm = httpClient.getConnectionManager();
        SchemeRegistry schemeRegistry = ccm.getSchemeRegistry();

        // Register our new socket factory with the typical SSL port and the
        // correct protocol name.
        schemeRegistry.register(new Scheme("https", sf, 443));

        // Finally, apply the ClientConnectionManager to the Http Client
        // or, as in this example, create a new one.
        return new DefaultHttpClient(ccm, httpClient.getParams());
    } catch (Throwable t) {
        log.warn("Something nasty happened with the EvilTrustingTrustManager. Warranty is null and void!");
        t.printStackTrace();
        return null;
    }
}

From source file:bixo.fetcher.SimpleHttpFetcher.java

private synchronized void init() {
    if (_httpClient == null) {
        // Create and initialize HTTP parameters
        HttpParams params = new BasicHttpParams();

        // TODO KKr - w/4.1, switch to new api (ThreadSafeClientConnManager)
        // cm.setMaxTotalConnections(_maxThreads);
        // cm.setDefaultMaxPerRoute(Math.max(10, _maxThreads/10));
        ConnManagerParams.setMaxTotalConnections(params, _maxThreads);

        // Set the maximum time we'll wait for a spare connection in the
        // connection pool. We
        // shouldn't actually hit this, as we make sure (in FetcherManager) that
        // the max number
        // of active requests doesn't exceed the value returned by getMaxThreads()
        // here.//from   w  w  w. java  2  s . c  om
        ConnManagerParams.setTimeout(params, CONNECTION_POOL_TIMEOUT);

        // Set the socket and connection timeout to be something reasonable.
        HttpConnectionParams.setSoTimeout(params, _socketTimeout);
        HttpConnectionParams.setConnectionTimeout(params, _connectionTimeout);

        // Even with stale checking enabled, a connection can "go stale" between
        // the check and the
        // next request. So we still need to handle the case of a closed socket
        // (from the server side),
        // and disabling this check improves performance.
        HttpConnectionParams.setStaleCheckingEnabled(params, false);

        // FUTURE - set this on a per-route (host) basis when we have per-host
        // policies for
        // doing partner crawls. We could define a BixoConnPerRoute class that
        // supports this.
        ConnPerRouteBean connPerRoute = new ConnPerRouteBean(_fetcherPolicy.getMaxConnectionsPerHost());
        ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);

        HttpProtocolParams.setVersion(params, _httpVersion);
        HttpProtocolParams.setUserAgent(params, _userAgent.getUserAgentString());
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setHttpElementCharset(params, "UTF-8");
        HttpProtocolParams.setUseExpectContinue(params, true);

        // TODO KKr - set on connection manager params, or client params?
        CookieSpecParamBean cookieParams = new CookieSpecParamBean(params);
        cookieParams.setSingleHeader(true);

        // Create and initialize scheme registry
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        SSLSocketFactory sf = null;

        for (String contextName : SSL_CONTEXT_NAMES) {
            try {
                SSLContext sslContext = SSLContext.getInstance(contextName);
                sslContext.init(null, new TrustManager[] { new DummyX509TrustManager(null) }, null);
                sf = new SSLSocketFactory(sslContext);
                break;
            } catch (NoSuchAlgorithmException e) {
                LOGGER.debug("SSLContext algorithm not available: " + contextName);
            } catch (Exception e) {
                LOGGER.debug("SSLContext can't be initialized: " + contextName, e);
            }
        }

        if (sf != null) {
            sf.setHostnameVerifier(new DummyX509HostnameVerifier());
            schemeRegistry.register(new Scheme("https", sf, 443));
        } else {
            LOGGER.warn("No valid SSLContext found for https");
        }

        // Use ThreadSafeClientConnManager since more than one thread will be
        // using the HttpClient.
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
        _httpClient = new DefaultHttpClient(cm, params);
        _httpClient.setHttpRequestRetryHandler(new MyRequestRetryHandler(_maxRetryCount));
        _httpClient.setRedirectHandler(new MyRedirectHandler(_fetcherPolicy.getRedirectMode()));
        _httpClient.addRequestInterceptor(new MyRequestInterceptor());

        params = _httpClient.getParams();
        // FUTURE KKr - support authentication
        HttpClientParams.setAuthenticating(params, false);
        HttpClientParams.setCookiePolicy(params, CookiePolicy.BEST_MATCH);

        ClientParamBean clientParams = new ClientParamBean(params);
        if (_fetcherPolicy.getMaxRedirects() == 0) {
            clientParams.setHandleRedirects(false);
        } else {
            clientParams.setHandleRedirects(true);
            clientParams.setMaxRedirects(_fetcherPolicy.getMaxRedirects());
        }

        // Set up default headers. This helps us get back from servers what we
        // want.
        HashSet<Header> defaultHeaders = new HashSet<Header>();
        defaultHeaders
                .add(new BasicHeader(HttpHeaderNames.ACCEPT_LANGUAGE, _fetcherPolicy.getAcceptLanguage()));
        defaultHeaders.add(new BasicHeader(HttpHeaderNames.ACCEPT_CHARSET, DEFAULT_ACCEPT_CHARSET));
        defaultHeaders.add(new BasicHeader(HttpHeaderNames.ACCEPT, DEFAULT_ACCEPT));

        clientParams.setDefaultHeaders(defaultHeaders);
    }
}

From source file:com.archivas.clienttools.arcutils.impl.adapter.HCAPAdapter.java

public SchemeRegistry getHcapProtocolSchemeRegistryForHttpClient(SSLCertificateCallback sslExceptionCallback)
        throws StorageAdapterException {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    try {//from  w  w  w . j  av a 2s .c o m
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        // Note: SSLContext.init takes an array of TrustManager instances, so we could in theory
        // provide more than one
        // implementation here.
        TrustManager X509TrustManager = new GetCertsX509TrustManager((HCAPProfile) getProfile(),
                sslExceptionCallback);
        sslcontext.init(null, new TrustManager[] { X509TrustManager }, null);
        SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslcontext);

        // We are doing this here because we did the verification that would be done if we had
        // set this to
        // STRICT_HOSTNAME_VERIFIER in the init we called above.
        sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        Scheme https = new Scheme("https", sslSocketFactory, 443);
        schemeRegistry.register(https);

        getAdditionalHcapProtocolSchemeRegistryForHttpClient(schemeRegistry, sslExceptionCallback);

    } catch (NoSuchAlgorithmException e) {
        LOG.log(Level.INFO, "Unable to initialize SSL for https protocol!", e);
        throw new StorageAdapterException("Unable to initialize SSL for https protocol", e);
    } catch (NoSuchProviderException e) {
        LOG.log(Level.INFO, "Unable to initialize SSL for https protocol!", e);
        throw new StorageAdapterException("Unable to initialize SSL for https protocol", e);
    } catch (KeyStoreException e) {
        LOG.log(Level.INFO, "Unable to initialize SSL for https protocol!", e);
        throw new StorageAdapterException("Unable to initialize SSL for https protocol", e);
    } catch (KeyManagementException e) {
        LOG.log(Level.INFO, "Unable to initialize SSL for https protocol!", e);
        throw new StorageAdapterException("Unable to initialize SSL for https protocol", e);
    }

    return schemeRegistry;
}

From source file:crawlercommons.fetcher.SimpleHttpFetcher.java

private synchronized void init() {
    if (_httpClient == null) {
        // Create and initialize HTTP parameters
        HttpParams params = new BasicHttpParams();

        // TODO KKr - w/4.1, switch to new api (ThreadSafeClientConnManager)
        // cm.setMaxTotalConnections(_maxThreads);
        // cm.setDefaultMaxPerRoute(Math.max(10, _maxThreads/10));
        ConnManagerParams.setMaxTotalConnections(params, _maxThreads);

        // Set the maximum time we'll wait for a spare connection in the connection pool. We
        // shouldn't actually hit this, as we make sure (in FetcherManager) that the max number
        // of active requests doesn't exceed the value returned by getMaxThreads() here.
        ConnManagerParams.setTimeout(params, CONNECTION_POOL_TIMEOUT);

        // Set the socket and connection timeout to be something reasonable.
        HttpConnectionParams.setSoTimeout(params, _socketTimeout);
        HttpConnectionParams.setConnectionTimeout(params, _connectionTimeout);

        // Even with stale checking enabled, a connection can "go stale" between the check and the
        // next request. So we still need to handle the case of a closed socket (from the server side),
        // and disabling this check improves performance.
        HttpConnectionParams.setStaleCheckingEnabled(params, false);

        // FUTURE - set this on a per-route (host) basis when we have per-host policies for
        // doing partner crawls. We could define a BixoConnPerRoute class that supports this.
        ConnPerRouteBean connPerRoute = new ConnPerRouteBean(getMaxConnectionsPerHost());
        ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);

        HttpProtocolParams.setVersion(params, _httpVersion);
        HttpProtocolParams.setUserAgent(params, _userAgent.getUserAgentString());
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setHttpElementCharset(params, "UTF-8");
        HttpProtocolParams.setUseExpectContinue(params, true);

        // TODO KKr - set on connection manager params, or client params?
        CookieSpecParamBean cookieParams = new CookieSpecParamBean(params);
        cookieParams.setSingleHeader(true);

        // Create and initialize scheme registry
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        SSLSocketFactory sf = null;

        for (String contextName : SSL_CONTEXT_NAMES) {
            try {
                SSLContext sslContext = SSLContext.getInstance(contextName);
                sslContext.init(null, new TrustManager[] { new DummyX509TrustManager(null) }, null);
                sf = new SSLSocketFactory(sslContext);
                break;
            } catch (NoSuchAlgorithmException e) {
                LOGGER.debug("SSLContext algorithm not available: " + contextName);
            } catch (Exception e) {
                LOGGER.debug("SSLContext can't be initialized: " + contextName, e);
            }//from  www  .  j  a  va 2 s.com
        }

        if (sf != null) {
            sf.setHostnameVerifier(new DummyX509HostnameVerifier());
            schemeRegistry.register(new Scheme("https", sf, 443));
        } else {
            LOGGER.warn("No valid SSLContext found for https");
        }

        // Use ThreadSafeClientConnManager since more than one thread will be using the HttpClient.
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
        _httpClient = new DefaultHttpClient(cm, params);
        _httpClient.setHttpRequestRetryHandler(new MyRequestRetryHandler(_maxRetryCount));
        _httpClient.setRedirectHandler(new MyRedirectHandler(getRedirectMode()));
        _httpClient.addRequestInterceptor(new MyRequestInterceptor());

        params = _httpClient.getParams();
        // FUTURE KKr - support authentication
        HttpClientParams.setAuthenticating(params, false);
        HttpClientParams.setCookiePolicy(params, CookiePolicy.BEST_MATCH);

        ClientParamBean clientParams = new ClientParamBean(params);
        if (getMaxRedirects() == 0) {
            clientParams.setHandleRedirects(false);
        } else {
            clientParams.setHandleRedirects(true);
            clientParams.setMaxRedirects(getMaxRedirects());
        }

        // Set up default headers. This helps us get back from servers what we want.
        HashSet<Header> defaultHeaders = new HashSet<Header>();
        defaultHeaders.add(new BasicHeader(HttpHeaders.ACCEPT_LANGUAGE, getAcceptLanguage()));
        defaultHeaders.add(new BasicHeader(HttpHeaders.ACCEPT_CHARSET, DEFAULT_ACCEPT_CHARSET));
        defaultHeaders.add(new BasicHeader(HttpHeaders.ACCEPT_ENCODING, DEFAULT_ACCEPT_ENCODING));
        defaultHeaders.add(new BasicHeader(HttpHeaders.ACCEPT, DEFAULT_ACCEPT));

        clientParams.setDefaultHeaders(defaultHeaders);
    }
}

From source file:com.archivas.clienttools.arcutils.impl.adapter.Hcp3AuthNamespaceAdapter.java

public void getAdditionalHcapProtocolSchemeRegistryForHttpClient(SchemeRegistry schemeRegistry,
        SSLCertificateCallback sslExceptionCallback) throws StorageAdapterException {
    try {/* ww  w  .j  av  a  2 s. c  om*/
        SSLSocketFactory getCertsFactory;
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        TrustManager tm = new GetCertsX509TrustManager(getProfile(), sslExceptionCallback);
        sslcontext.init(null, new TrustManager[] { tm }, null);
        getCertsFactory = new SSLSocketFactory(sslcontext);
        getCertsFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        getCertsFactory = new SSLSocketFactory(sslcontext);
        Scheme getCerts = new Scheme("getcerts", getCertsFactory, 443);
        schemeRegistry.register(getCerts);

    } catch (Exception e) {
        LOG.log(Level.INFO, "Unable to initialize SSL for hcaphttps protocol!", e);
        throw new StorageAdapterException("Unable to initialize SSL for https protocol", e);
    }
}

From source file:org.apache.nifi.processors.solr.SolrProcessor.java

/**
 * Create a SolrClient based on the type of Solr specified.
 *
 * @param context//from  www  .  jav a2 s  .co  m
 *          The context
 * @return an HttpSolrClient or CloudSolrClient
 */
protected SolrClient createSolrClient(final ProcessContext context, final String solrLocation) {
    final Integer socketTimeout = context.getProperty(SOLR_SOCKET_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS)
            .intValue();
    final Integer connectionTimeout = context.getProperty(SOLR_CONNECTION_TIMEOUT)
            .asTimePeriod(TimeUnit.MILLISECONDS).intValue();
    final Integer maxConnections = context.getProperty(SOLR_MAX_CONNECTIONS).asInteger();
    final Integer maxConnectionsPerHost = context.getProperty(SOLR_MAX_CONNECTIONS_PER_HOST).asInteger();
    final SSLContextService sslContextService = context.getProperty(SSL_CONTEXT_SERVICE)
            .asControllerService(SSLContextService.class);
    final String jaasClientAppName = context.getProperty(JAAS_CLIENT_APP_NAME).getValue();

    final ModifiableSolrParams params = new ModifiableSolrParams();
    params.set(HttpClientUtil.PROP_SO_TIMEOUT, socketTimeout);
    params.set(HttpClientUtil.PROP_CONNECTION_TIMEOUT, connectionTimeout);
    params.set(HttpClientUtil.PROP_MAX_CONNECTIONS, maxConnections);
    params.set(HttpClientUtil.PROP_MAX_CONNECTIONS_PER_HOST, maxConnectionsPerHost);

    // has to happen before the client is created below so that correct configurer would be set if neeeded
    if (!StringUtils.isEmpty(jaasClientAppName)) {
        System.setProperty("solr.kerberos.jaas.appname", jaasClientAppName);
        HttpClientUtil.setConfigurer(new Krb5HttpClientConfigurer());
    }

    final HttpClient httpClient = HttpClientUtil.createClient(params);

    if (sslContextService != null) {
        final SSLContext sslContext = sslContextService.createSSLContext(SSLContextService.ClientAuth.REQUIRED);
        final SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslContext);
        final Scheme httpsScheme = new Scheme("https", 443, sslSocketFactory);
        httpClient.getConnectionManager().getSchemeRegistry().register(httpsScheme);
    }

    if (SOLR_TYPE_STANDARD.equals(context.getProperty(SOLR_TYPE).getValue())) {
        return new HttpSolrClient(solrLocation, httpClient);
    } else {
        final String collection = context.getProperty(COLLECTION).evaluateAttributeExpressions().getValue();
        final Integer zkClientTimeout = context.getProperty(ZK_CLIENT_TIMEOUT)
                .asTimePeriod(TimeUnit.MILLISECONDS).intValue();
        final Integer zkConnectionTimeout = context.getProperty(ZK_CONNECTION_TIMEOUT)
                .asTimePeriod(TimeUnit.MILLISECONDS).intValue();

        CloudSolrClient cloudSolrClient = new CloudSolrClient(solrLocation, httpClient);
        cloudSolrClient.setDefaultCollection(collection);
        cloudSolrClient.setZkClientTimeout(zkClientTimeout);
        cloudSolrClient.setZkConnectTimeout(zkConnectionTimeout);
        return cloudSolrClient;
    }
}