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 javax.net.ssl.SSLSocketFactory socketfactory,
        final X509HostnameVerifier hostnameVerifier) 

Source Link

Usage

From source file:org.alfresco.http.SharedHttpClientProvider.java

/**
 * See <a href="http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html">Connection management</a>.
 * //from   w w  w . j  a  v a2 s .  c  om
 * @param maxNumberOfConnections        the maximum number of Http connections in the pool
 * @param connectionTimeoutMs           the time to wait for a connection from the pool before failure
 * @param socketTimeoutMs               the time to wait for data activity on a connection before failure
 * @param socketTtlMs                   the time for a socket to remain alive before being forcibly closed (0 for infinite)
 */
public SharedHttpClientProvider(int maxNumberOfConnections, int connectionTimeoutMs, int socketTimeoutMs,
        int socketTtlMs) {
    SSLSocketFactory sslSf = null;
    try {
        TrustStrategy sslTs = new TrustAnyTrustStrategy();
        sslSf = new SSLSocketFactory(sslTs, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (Throwable e) {
        throw new RuntimeException("Unable to construct HttpClientProvider.", e);
    }

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 8080, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, sslSf));
    schemeRegistry.register(new Scheme("https", 80, sslSf));

    httpClientCM = new PoolingClientConnectionManager(schemeRegistry, (long) socketTtlMs,
            TimeUnit.MILLISECONDS);
    // Increase max total connections
    httpClientCM.setMaxTotal(maxNumberOfConnections);
    // Ensure that we don't throttle on a per-scheme basis (BENCH-45)
    httpClientCM.setDefaultMaxPerRoute(maxNumberOfConnections);

    httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeoutMs);
    HttpConnectionParams.setSoTimeout(httpParams, socketTimeoutMs);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setStaleCheckingEnabled(httpParams, true);
    HttpConnectionParams.setSoKeepalive(httpParams, true);

}

From source file:com.dumiduh.das.AnalyticsAPIInvoker.java

private String invokePost(String url, String username, String pwd, String type, String payload) {
    TrustStrategyExt strategy = new TrustStrategyExt();

    String jsonString = "";
    try {/*from w ww. java  2s  .  c  o m*/
        SSLSocketFactory sf = new SSLSocketFactory(strategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", Integer.parseInt(port), sf));
        ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);

        DefaultHttpClient client = new DefaultHttpClient(ccm);

        StringEntity stringEntity = new StringEntity(payload);
        HttpPost post = new HttpPost();
        post.setEntity(stringEntity);
        String header = "Basic " + getBase64EncodedToken(username, pwd);
        post.setHeader("Authorization", header);
        post.setHeader("Accept", "application/json");
        post.setHeader("Content-Type", "application/json");

        HttpResponse resp = client.execute(post);
        if (type.equals("body")) {
            BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));

            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }
            jsonString = result.toString();
        } else if (type.equals("header")) {
            StringBuffer result = new StringBuffer();
            Header[] headers = resp.getAllHeaders();
            for (Header h : headers) {

                result.append(h.getName() + " : " + h.getValue());
            }
            result.append("status code : " + resp.getStatusLine().getStatusCode());
            jsonString = result.toString();
        }

        client.close();

    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyManagementException ex) {
        Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyStoreException ex) {
        Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnrecoverableKeyException ex) {
        Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NumberFormatException ex) {
        Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return jsonString;
}

From source file:ch.cyberduck.core.http.HttpSession.java

protected AbstractHttpClient http(final String hostname) {
    if (!clients.containsKey(hostname)) {
        final HttpParams params = new BasicHttpParams();

        HttpProtocolParams.setVersion(params, org.apache.http.HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, getEncoding());
        HttpProtocolParams.setUserAgent(params, getUserAgent());

        AuthParams.setCredentialCharset(params, Preferences.instance().getProperty("http.credentials.charset"));

        HttpConnectionParams.setTcpNoDelay(params, true);
        HttpConnectionParams.setSoTimeout(params, timeout());
        HttpConnectionParams.setConnectionTimeout(params, timeout());
        HttpConnectionParams.setSocketBufferSize(params,
                Preferences.instance().getInteger("http.socket.buffer"));
        HttpConnectionParams.setStaleCheckingEnabled(params, true);

        HttpClientParams.setRedirecting(params, true);
        HttpClientParams.setAuthenticating(params, true);
        HttpClientParams.setCookiePolicy(params, CookiePolicy.BEST_MATCH);

        // Sets the timeout in milliseconds used when retrieving a connection from the ClientConnectionManager
        HttpClientParams.setConnectionManagerTimeout(params,
                Preferences.instance().getLong("http.manager.timeout"));

        SchemeRegistry registry = new SchemeRegistry();
        // Always register HTTP for possible use with proxy
        registry.register(new Scheme(ch.cyberduck.core.Scheme.http.toString(), host.getPort(),
                PlainSocketFactory.getSocketFactory()));
        registry.register(new Scheme(ch.cyberduck.core.Scheme.https.toString(), host.getPort(),
                new SSLSocketFactory(
                        new CustomTrustSSLProtocolSocketFactory(this.getTrustManager()).getSSLContext(),
                        new X509HostnameVerifier() {
                            @Override
                            public void verify(String host, SSLSocket ssl) throws IOException {
                                log.warn("Hostname verification disabled for:" + host);
                            }/*from   w w  w  .  j  a v  a2s.c o  m*/

                            @Override
                            public void verify(String host, X509Certificate cert) throws SSLException {
                                log.warn("Hostname verification disabled for:" + host);
                            }

                            @Override
                            public void verify(String host, String[] cns, String[] subjectAlts)
                                    throws SSLException {
                                log.warn("Hostname verification disabled for:" + host);
                            }

                            @Override
                            public boolean verify(String s, javax.net.ssl.SSLSession sslSession) {
                                log.warn("Hostname verification disabled for:" + s);
                                return true;
                            }
                        })));
        if (Preferences.instance().getBoolean("connection.proxy.enable")) {
            final Proxy proxy = ProxyFactory.get();
            if (ch.cyberduck.core.Scheme.https.equals(this.getHost().getProtocol().getScheme())) {
                if (proxy.isHTTPSProxyEnabled(host)) {
                    ConnRouteParams.setDefaultProxy(params,
                            new HttpHost(proxy.getHTTPSProxyHost(host), proxy.getHTTPSProxyPort(host)));
                }
            }
            if (ch.cyberduck.core.Scheme.http.equals(this.getHost().getProtocol().getScheme())) {
                if (proxy.isHTTPProxyEnabled(host)) {
                    ConnRouteParams.setDefaultProxy(params,
                            new HttpHost(proxy.getHTTPProxyHost(host), proxy.getHTTPProxyPort(host)));
                }
            }
        }
        PoolingClientConnectionManager manager = new PoolingClientConnectionManager(registry);
        manager.setMaxTotal(Preferences.instance().getInteger("http.connections.total"));
        manager.setDefaultMaxPerRoute(Preferences.instance().getInteger("http.connections.route"));
        AbstractHttpClient http = new DefaultHttpClient(manager, params);
        this.configure(http);
        clients.put(hostname, http);
    }
    return clients.get(hostname);
}

From source file:com.rsa.redchallenge.standaloneapp.utils.RestInteractor.java

private static DefaultHttpClient getHttpClient() {

    if (ApplicationConstant.SA_BASE_URL.contains("https")) {
        TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
            @Override//w  w  w. ja  v a  2s  . c o m
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return false;
            }
        };

        SSLSocketFactory sf = null;
        try {
            sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        } catch (NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException
                | KeyManagementException e) {
            e.printStackTrace();
        }

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", 443, sf));
        ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);

        return new DefaultHttpClient(ccm);
    } else {
        return new DefaultHttpClient();
    }
}

From source file:gov.nih.nci.nbia.StandaloneDMV1.java

private static List<String> connectAndReadFromURL(URL url, String fileName) {
    List<String> data = null;
    DefaultHttpClient httpClient = null;
    TrustStrategy easyStrategy = new TrustStrategy() {
        @Override/*w  w w. j  av  a  2s  . c om*/
        public boolean isTrusted(X509Certificate[] certificate, String authType) throws CertificateException {
            return true;
        }
    };
    try {
        // SSLContext sslContext = SSLContext.getInstance("SSL");
        // set up a TrustManager that trusts everything
        // sslContext.init(null, new TrustManager[] { new
        // EasyX509TrustManager(null)}, null);

        SSLSocketFactory sslsf = new SSLSocketFactory(easyStrategy,
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme httpsScheme = new Scheme("https", 443, sslsf);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(httpsScheme);
        schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(schemeRegistry);

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 50000);
        HttpConnectionParams.setSoTimeout(httpParams, new Integer(12000));
        httpClient = new DefaultHttpClient(ccm, httpParams);
        httpClient.setRoutePlanner(new ProxySelectorRoutePlanner(schemeRegistry, ProxySelector.getDefault()));
        // // Additions by lrt for tcia -
        // // attempt to reduce errors going through a Coyote Point
        // Equalizer load balance switch
        httpClient.getParams().setParameter("http.socket.timeout", new Integer(12000));
        httpClient.getParams().setParameter("http.socket.receivebuffer", new Integer(16384));
        httpClient.getParams().setParameter("http.tcp.nodelay", true);
        httpClient.getParams().setParameter("http.connection.stalecheck", false);
        // // end lrt additions

        HttpPost httpPostMethod = new HttpPost(url.toString());

        List<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>();
        postParams.add(new BasicNameValuePair("serverjnlpfileloc", fileName));
        UrlEncodedFormEntity query = new UrlEncodedFormEntity(postParams);
        httpPostMethod.setEntity(query);
        HttpResponse response = httpClient.execute(httpPostMethod);
        // int responseCode = response.getStatusLine().getStatusCode();
        // System.out.println("Response code for requesting datda file: " +
        // responseCode);
        InputStream inputStream = response.getEntity().getContent();
        data = IOUtils.readLines(inputStream);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
    }
    return data;
}

From source file:wsattacker.plugin.intelligentdos.requestSender.Http4RequestSenderImpl.java

private SSLSocketFactory get() {

    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new TrustAllManager() };

    // Install the all-trusting trust manager
    try {/*w  w  w .  j  a v a 2 s  . c  o  m*/
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        return new SSLSocketFactory(sc, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (RuntimeException e) {
        ;
    } catch (Exception e) {
        ;
    }

    return null;

}

From source file:ua.pp.msk.cliqr.GetProcessorImpl.java

private void init(URL targetURL, String user, String password) throws ClientSslException {
    this.targetUrl = targetURL;
    logger.debug("Initializing " + this.getClass().getName() + " with target URL " + targetURL.toString());
    HttpHost htHost = new HttpHost(targetUrl.getHost(), targetUrl.getPort(), targetUrl.getProtocol());

    AuthCache aCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    aCache.put(htHost, basicAuth);//from   www . j a v  a 2  s.  c o m

    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password);
    BasicCredentialsProvider cProvider = new BasicCredentialsProvider();
    cProvider.setCredentials(new AuthScope(htHost), creds);
    logger.debug("Credential provider: " + cProvider.toString());

    context = new BasicHttpContext();
    ClientContextConfigurer cliCon = new ClientContextConfigurer(context);
    cliCon.setCredentialsProvider(cProvider);
    context.setAttribute(ClientContext.AUTH_CACHE, aCache);
    SSLSocketFactory sslConnectionSocketFactory = null;
    try {
        sslConnectionSocketFactory = new SSLSocketFactory(new TrustSelfSignedStrategy(),
                new CliQrHostnameVerifier());
    } catch (KeyManagementException ex) {
        logger.error("Cannot manage secure keys", ex);
        throw new ClientSslException("Cannot manage secure keys", ex);
    } catch (KeyStoreException ex) {
        logger.error("Cannot build SSL context due to KeyStore error", ex);
        throw new ClientSslException("Cannot build SSL context due to KeyStore error", ex);
    } catch (NoSuchAlgorithmException ex) {
        logger.error("Unsupported security algorithm", ex);
        throw new ClientSslException("Unsupported security algorithm", ex);
    } catch (UnrecoverableKeyException ex) {
        logger.error("Unrecoverable key", ex);
        throw new ClientSslException("Unrecoverrable key", ex);
    }

    DefaultHttpClient defClient = new DefaultHttpClient();
    defClient.setRedirectStrategy(new CliQrRedirectStrategy());
    defClient.setCredentialsProvider(cProvider);
    Scheme https = new Scheme("https", 443, sslConnectionSocketFactory);
    defClient.getConnectionManager().getSchemeRegistry().register(https);
    defClient.setTargetAuthenticationStrategy(new TargetAuthenticationStrategy());
    client = defClient;
}

From source file:org.vsearchd.crawler.backend.BackendSessionHTTPS.java

private Scheme getHttpSslTheme(String url) throws Exception {
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, getTrustManager(), null);
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    SSLSocketFactory socketFactory = new SSLSocketFactory(sc, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    return new Scheme("https", Integer.valueOf(this.getBackendServer().getPort()), socketFactory);
}

From source file:com.mgmtp.perfload.core.client.web.config.HttpClientManagerModule.java

/**
 * If the property {@code ssl.trust.all} equals {@code true}, a {@link TrustAllManager} is
 * installed, i. e. all certificates are trusted, and host name verification is turned off.
 * Otherwise, {@link LtSSLSocketFactory} is registered for HTTPS, if either a key store, a trust
 * store or both are configured using the following properties:</p>
 * <p>/* ww  w . j  av  a 2s.c  om*/
 * <ul>
 * <li>{@code javax.net.ssl.keyStore}</li>
 * <li>{@code javax.net.ssl.keyStorePassword}</li>
 * <li>{@code javax.net.ssl.keyStoreType}</li>
 * <li>{@code javax.net.ssl.trustStore}</li>
 * <li>{@code javax.net.ssl.trustStorePassword}</li>
 * <li>{@code javax.net.ssl.trustStoreType}</li>
 * </ul>
 * </p>
 * <p>
 * {@code javax.net.ssl.trustStore} and {@code javax.net.ssl.keyStore} must point to resources
 * on the classpath.
 * </p>
 * 
 * @param properties
 *            the properties
 * @return the {@link SchemeRegistry} the SchemeRegistry used for the HttpClient's
 *         {@link ClientConnectionManager} registered for HTTPS
 */
@Provides
@Singleton
protected SchemeRegistry provideSchemeRegistry(final PropertiesMap properties) {
    SchemeRegistry registry = SchemeRegistryFactory.createDefault();

    if (properties.getBoolean(SSL_TRUST_ALL)) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[] { new TrustAllManager() }, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx, new AllowAllHostnameVerifier());
            registry.register(new Scheme("https", 443, ssf));
        } catch (GeneralSecurityException ex) {
            Throwables.propagate(ex);
        }
    } else {
        String keyStore = trimToNull(properties.get(KEY_STORE));
        String trustStore = trimToNull(properties.get(TRUST_STORE));

        if (keyStore != null || trustStore != null) {
            String keyStorePassword = trimToNull(properties.get(KEY_STORE_PASSWORD));
            String keyStoreType = trimToNull(properties.get(KEY_STORE_TYPE));

            String trustStorePassword = trimToNull(properties.get(TRUST_STORE_PASSWORD));
            String trustStoreType = trimToNull(properties.get(TRUST_STORE_TYPE));

            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            URL keyStoreUrl = keyStore != null ? loader.getResource(keyStore) : null;
            URL trustStoreUrl = trustStore != null ? loader.getResource(trustStore) : null;

            LayeredSchemeSocketFactory socketFactory = new LtSSLSocketFactory(keyStoreUrl, keyStorePassword,
                    keyStoreType, trustStoreUrl, trustStorePassword, trustStoreType);

            registry.register(new Scheme(HTTPS, 443, socketFactory));
        }
    }
    return registry;
}