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:net.netheos.pcsapi.providers.StorageProviderFactory.java

/**
 * Builds a specific HttpClient to certain providers
 *
 * @param providerName//from ww  w  .ja  v  a  2 s .  c  om
 * @return client to be used, or null if default should be used.
 */
private static HttpClient buildDedicatedHttpClient(String providerName) throws IOException {
    /**
     * Basic java does not trust CloudMe CA CloudMe CA needs to be added
     */
    if (providerName.equals("cloudme") && !PcsUtils.ANDROID) {
        try {
            KeyStore ks = KeyStore.getInstance("JKS");
            InputStream is = null;

            try {
                is = StorageProviderFactory.class.getResourceAsStream("/cloudme.jks");
                ks.load(is, "changeit".toCharArray());
            } finally {
                PcsUtils.closeQuietly(is);
            }

            SSLContext context = SSLContext.getInstance("TLS");
            TrustManagerFactory caTrustManagerFactory = TrustManagerFactory.getInstance("SunX509");
            caTrustManagerFactory.init(ks);
            context.init(null, caTrustManagerFactory.getTrustManagers(), null);

            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", 80, new PlainSocketFactory()));
            schemeRegistry.register(new Scheme("https", 443, new SSLSocketFactory(context)));

            ClientConnectionManager cnxManager = new PoolingClientConnectionManager(schemeRegistry);

            return new DefaultHttpClient(cnxManager);

        } catch (GeneralSecurityException ex) {
            throw new UnsupportedOperationException("Can't configure HttpClient for Cloud Me", ex);
        }
    }

    return null;
}

From source file:org.gw2InfoViewer.factories.HttpsConnectionFactory.java

public static HttpClient getHttpsClientWithProxy(byte[] sslCertificateBytes, String proxyAddress,
        int proxyPort) {
    DefaultHttpClient httpClient;//ww w.  jav a 2s . c  o m
    Certificate[] sslCertificate;
    HttpHost proxy;

    httpClient = new DefaultHttpClient();
    try {
        sslCertificate = convertByteArrayToCertificate(sslCertificateBytes);

        TrustManagerFactory tf = TrustManagerFactory.getInstance("X509");
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null);
        for (int i = 0; i < sslCertificate.length; i++) {
            ks.setCertificateEntry("StartCom" + i, sslCertificate[i]);
        }

        tf.init(ks);
        TrustManager[] tm = tf.getTrustManagers();

        SSLContext sslCon = SSLContext.getInstance("SSL");
        sslCon.init(null, tm, new SecureRandom());
        SSLSocketFactory socketFactory = new SSLSocketFactory(ks);
        Scheme sch = new Scheme("https", 443, socketFactory);

        proxy = new HttpHost(proxyAddress, proxyPort, "https");
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException
            | KeyManagementException | UnrecoverableKeyException ex) {
        Logger.getLogger(HttpsConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);
    }

    return httpClient;
}

From source file:SandBox.testing.PageFetcher.java

public PageFetcher(CrawlConfig config) {
    super(config);

    HttpParams params = new BasicHttpParams();
    HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params);
    paramsBean.setVersion(HttpVersion.HTTP_1_1);
    paramsBean.setContentCharset("UTF-8");
    paramsBean.setUseExpectContinue(false);

    params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
    params.setParameter(CoreProtocolPNames.USER_AGENT, config.getUserAgentString());
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout());
    params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout());

    params.setBooleanParameter("http.protocol.handle-redirects", false);

    SSLContext sslContext = null;
    try {//from w ww  . j a  v  a2 s .com
        sslContext = SSLContext.getInstance("SSL");
        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                System.out.println("getAcceptedIssuers =============");
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
                System.out.println("checkClientTrusted =============");
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
                System.out.println("checkServerTrusted =============");
            }
        } }, new SecureRandom());
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    SSLSocketFactory sf = new SSLSocketFactory(sslContext);
    Scheme httpsScheme = new Scheme("https", 443, sf);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(httpsScheme);

    //SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

    if (config.isIncludeHttpsPages()) {
        schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
    }

    connectionManager = new PoolingClientConnectionManager(schemeRegistry);
    connectionManager.setMaxTotal(config.getMaxTotalConnections());
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());
    httpClient = new DefaultHttpClient(connectionManager, params);

    if (config.getProxyHost() != null) {

        if (config.getProxyUsername() != null) {
            httpClient.getCredentialsProvider().setCredentials(
                    new AuthScope(config.getProxyHost(), config.getProxyPort()),
                    new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()));
        }

        HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort());
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {

        @Override
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            Header contentEncoding = entity.getContentEncoding();
            if (contentEncoding != null) {
                HeaderElement[] codecs = contentEncoding.getElements();
                for (HeaderElement codec : codecs) {
                    if (codec.getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }
        }

    });

    if (connectionMonitorThread == null) {
        connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager);
    }
    connectionMonitorThread.start();

}

From source file:com.dgwave.osrs.OsrsClient.java

/**
 * Creates a connection manager from configuration - handles test mode
 * @return ClientConnectionManager/* w ww  .  j a v a2 s .  c  o m*/
 * @throws OsrsException
 */
private ClientConnectionManager getConnectionManager() throws OsrsException {

    // Create and initialize scheme registry
    SchemeRegistry schemeRegistry = new SchemeRegistry();

    boolean testMode = "test".equals(OsrsConfig.getValue("osrs.environment"));
    int port = Integer.parseInt(OsrsConfig.getValue("osrs.port"));
    int sslPort = Integer.parseInt(OsrsConfig.getValue("osrs.sslPort"));
    schemeRegistry.register(new Scheme("http", port, PlainSocketFactory.getSocketFactory()));

    Scheme sslScheme;
    if (testMode) {
        try {
            sslScheme = new Scheme("https", sslPort, new SSLSocketFactory(getTestTrustStore()));
        } catch (Exception e) {
            throw new OsrsException("Error creating test SSL scheme", e);
        }
    } else {
        sslScheme = new Scheme("https", sslPort, SSLSocketFactory.getSocketFactory());
    }
    schemeRegistry.register(sslScheme);

    // Create an HttpClient with the PoolingClientConnManager (thread-safe).
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    ClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry, 60, TimeUnit.SECONDS);
    return cm;
}

From source file:org.globus.workspace.cloud.client.util.CumulusParameterConvert.java

CumulusProtocolSocketFactory() throws Exception {
    //TrustStrategy ts = new TrustSelfSignedStrategy();
    TrustStrategy ts = new CumulusAlwaysTrustStrategy();
    psf = new SSLSocketFactory(ts);
}

From source file:org.wso2.carbon.databridge.agent.thrift.internal.pool.client.secure.SecureClientPoolFactory.java

@Override
public ThriftSecureEventTransmissionService.Client makeObject(Object key)
        throws AgentSecurityException, TTransportException {
    String[] keyElements = key.toString().split(AgentConstants.SEPARATOR);
    if (keyElements[2].equals(ReceiverConfiguration.Protocol.TCP.toString())) {
        if (params == null) {
            if (trustStore == null) {
                trustStore = System.getProperty("javax.net.ssl.trustStore");
                if (trustStore == null) {
                    throw new AgentSecurityException("No trustStore found");
                }// ww w.j av  a  2s .  c o m
                // trustStore = "/home/suho/projects/wso2/trunk/carbon/distribution/product/modules/distribution/target/wso2carbon-4.0.0-SNAPSHOT/repository/resources/security/client-truststore.jks";
            }

            if (trustStorePassword == null) {
                trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword");
                if (trustStorePassword == null) {
                    throw new AgentSecurityException("No trustStore password found");
                }
                //trustStorePassword = "wso2carbon";
            }

            params = new TSSLTransportFactory.TSSLTransportParameters();
            params.setTrustStore(trustStore, trustStorePassword);
        }

        String[] hostNameAndPort = keyElements[3].split(AgentConstants.HOSTNAME_AND_PORT_SEPARATOR);

        TTransport receiverTransport = null;
        try {
            receiverTransport = TSSLTransportFactory.getClientSocket(
                    HostAddressFinder.findAddress(hostNameAndPort[0]), Integer.parseInt(hostNameAndPort[1]), 0,
                    params);
        } catch (SocketException ignored) {
            //already checked
        }

        TProtocol protocol = new TBinaryProtocol(receiverTransport);
        return new ThriftSecureEventTransmissionService.Client(protocol);
    } else {
        try {
            TrustManager easyTrustManager = new X509TrustManager() {
                public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                        throws java.security.cert.CertificateException {
                }

                public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                        throws java.security.cert.CertificateException {
                }

                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            String[] hostNameAndPort = keyElements[3].split(AgentConstants.HOSTNAME_AND_PORT_SEPARATOR);

            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[] { easyTrustManager }, null);
            SSLSocketFactory sf = new SSLSocketFactory(sslContext);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            Scheme httpsScheme = new Scheme("https", sf, Integer.parseInt(hostNameAndPort[1]));

            DefaultHttpClient client = new DefaultHttpClient();
            client.getConnectionManager().getSchemeRegistry().register(httpsScheme);

            THttpClient tclient = new THttpClient("https://" + keyElements[3] + "/securedThriftReceiver",
                    client);
            TProtocol protocol = new TCompactProtocol(tclient);
            ThriftSecureEventTransmissionService.Client authClient = new ThriftSecureEventTransmissionService.Client(
                    protocol);
            tclient.open();
            return authClient;
        } catch (Exception e) {
            throw new AgentSecurityException("Cannot create Secure client for " + keyElements[3], e);
        }
    }
}

From source file:com.jkoolcloud.jesl.net.http.HttpClient.java

/**
 * {@inheritDoc}//  w ww .  j a  v a  2  s.c om
 */
@Override
public synchronized void connect() throws IOException {
    try {
        if (secure) {
            SSLSocketFactory ssf = null;
            if (!StringUtils.isEmpty(sslKeystore)) {
                SSLContextFactory scf = new SSLContextFactory(sslKeystore, sslKeystorePwd, sslKeystorePwd);
                ssf = new SSLSocketFactory(scf.getSslContext(true));
            } else {
                ssf = new SSLSocketFactory(SSLContext.getDefault());
            }
            Scheme secureScheme = new Scheme("https", port, ssf);
            schemeReg = new SchemeRegistry();
            schemeReg.register(secureScheme);
        }
        route = new HttpRoute(httpHost, null, httpProxy, secure, RouteInfo.TunnelType.PLAIN,
                RouteInfo.LayerType.PLAIN);
        if (schemeReg != null) {
            connMgr = new BasicClientConnectionManager(schemeReg);
        } else {
            connMgr = new BasicClientConnectionManager();
        }
        connReq = connMgr.requestConnection(route, null);
        connection = connReq.getConnection(0, null);
        connection.open(route, new BasicHttpContext(), new BasicHttpParams());
        logger.log(OpLevel.DEBUG, "Connected to {0}{1}", uri,
                (httpProxy != null ? " via proxy " + httpProxy : ""));
    } catch (Throwable e) {
        close();
        throw new IOException("Failed to connect to uri=" + uri + ", reason=" + e.getMessage(), e);
    }
}

From source file:com.mindprotectionkit.freephone.signaling.SignalingSocket.java

private Socket constructSSLSocket(Context context, String host, int port) throws SignalingException {
    try {/* www  .ja  v  a2  s. c om*/
        AssetManager assetManager = context.getAssets();
        InputStream keyStoreInputStream = assetManager.open("whisper.store");
        KeyStore trustStore = KeyStore.getInstance("BKS");

        trustStore.load(keyStoreInputStream, "whisper".toCharArray());

        SSLSocketFactory sslSocketFactory = new SSLSocketFactory(trustStore);

        if (Release.SSL) {
            sslSocketFactory.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        } else {
            Log.w("SignalingSocket", "Disabling hostname verification...");
            sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        }

        return timeoutHackConnect(sslSocketFactory, host, port);
    } catch (IOException ioe) {
        throw new SignalingException(ioe);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException(e);
    } catch (KeyStoreException e) {
        throw new IllegalArgumentException(e);
    } catch (CertificateException e) {
        throw new IllegalArgumentException(e);
    } catch (KeyManagementException e) {
        throw new IllegalArgumentException(e);
    } catch (UnrecoverableKeyException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:iristk.speech.nuancecloud.JSpeexNuanceCloudRecognizerListener.java

@SuppressWarnings("deprecation")
private HttpClient getHttpClient() throws NoSuchAlgorithmException, KeyManagementException {
    // Standard HTTP parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUseExpectContinue(params, false);
    // Initialize the HTTP client
    httpclient = new DefaultHttpClient(params);

    // Initialize/setup SSL
    TrustManager easyTrustManager = new X509TrustManager() {
        @Override/*from w  ww. java 2  s  .  co  m*/
        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws java.security.cert.CertificateException {
            // TODO Auto-generated method stub
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws java.security.cert.CertificateException {
            // TODO Auto-generated method stub
        }

        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            // TODO Auto-generated method stub
            return null;
        }
    };

    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme sch = new Scheme("https", sf, 443);
    httpclient.getConnectionManager().getSchemeRegistry().register(sch);

    // Return the initialized instance of our httpclient
    return httpclient;
}

From source file:org.wso2.bam.integration.tests.reciever.RESTAPITestCase.java

@BeforeClass(groups = { "wso2.bam" })
private static void init() {

    DATA_RECEIVER = "/datareceiver/1.0.0";

    //        host = FrameworkSettings.HOST_NAME;
    //        httpsPort = Integer.parseInt(FrameworkSettings.HTTPS_PORT);

    restAppParentURL = "https://" + host + ":" + httpsPort + DATA_RECEIVER;
    streamsURL = restAppParentURL + "/streams";

    streamURL = restAppParentURL + "/stream";
    stockQuoteVersion1URL = streamURL + "/stockquote.stream/1.0.2/";

    stockQuoteVersion2URL = streamURL + "/stockquote.stream.2/2.0.0";

    stockQuoteVersion3URL = streamURL + "/labit.stream/0.0.3";
    stockQuoteVersion4URL = streamURL + "/eu.ima.event.stream/1.2.0";
    stockQuoteVersion5URL = streamURL + "/eu.ima.event.stream.2/1.3.0";

    try {/*  ww  w  . j ava2  s. c  o m*/
        events1 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/events1.json"));
        events2 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/events2.json"));
        events3 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/events3.json"));
        events4 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/events4.json"));
        events5 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/events5.json"));

        streamdefn1 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/streamdefn1.json"));
        streamdefn2 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/streamdefn2.json"));
        streamdefn3 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/streamdefn3.json"));
        streamdefn4 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/streamdefn4.json"));
        streamdefn5 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/streamdefn5.json"));

        TrustManager easyTrustManager = new X509TrustManager() {
            public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                    throws java.security.cert.CertificateException {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                    throws java.security.cert.CertificateException {
            }

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { easyTrustManager }, null);
        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme httpsScheme = new Scheme("https", sf, httpsPort);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "utf-8");
        params.setBooleanParameter("http.protocol.expect-continue", false);

        client = new DefaultHttpClient(params);
        client.getConnectionManager().getSchemeRegistry().register(httpsScheme);

    } catch (Exception e) {
        e.printStackTrace();
        fail();
    }
}