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.wso2.carbon.databridge.agent.internal.endpoint.thrift.client.ThriftSecureClientPoolFactory.java

@Override
public Object createClient(String protocol, String hostName, int port)
        throws DataEndpointAgentSecurityException {
    String trustStore, trustStorePw;
    if (protocol.equalsIgnoreCase(DataEndpointConfiguration.Protocol.TCP.toString())) {
        if (params == null) {
            if (getTrustStore() == null) {
                trustStore = System.getProperty("javax.net.ssl.trustStore");
                if (trustStore == null) {
                    throw new DataEndpointAgentSecurityException("No trustStore found");
                } else {
                    setTrustStore(trustStore);
                }/*from   w ww . j  a  va  2  s.c om*/
            }

            if (getTrustStorePassword() == null) {
                trustStorePw = System.getProperty("javax.net.ssl.trustStorePassword");
                if (trustStorePw == null) {
                    throw new DataEndpointAgentSecurityException("No trustStore password found");
                } else {
                    setTrustStorePassword(trustStorePw);
                }
            }

            params = new TSSLTransportFactory.TSSLTransportParameters();
            params.setTrustStore(getTrustStore(), getTrustStorePassword());
        }

        TTransport receiverTransport = null;
        try {
            receiverTransport = TSSLTransportFactory.getClientSocket(hostName, port, 0, params);
            TProtocol tProtocol = new TBinaryProtocol(receiverTransport);
            return new ThriftSecureEventTransmissionService.Client(tProtocol);
        } catch (TTransportException e) {
            throw new DataEndpointAgentSecurityException(
                    "Error while trying to connect to " + protocol + "://" + hostName + ":" + port, e);
        }
    } else {
        //TODO:Error  thrown when connecting in http in tests...
        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;
                }
            };
            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, port);

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

            THttpClient tclient = new THttpClient("https://" + hostName + ":" + port + "/securedThriftReceiver",
                    client);
            TProtocol tProtocol = new TCompactProtocol(tclient);
            ThriftSecureEventTransmissionService.Client authClient = new ThriftSecureEventTransmissionService.Client(
                    tProtocol);
            tclient.open();
            return authClient;
        } catch (Exception e) {
            throw new DataEndpointAgentSecurityException("Cannot create Secure client for " + "https://"
                    + hostName + ":" + port + "/securedThriftReceiver", e);
        }
    }
}

From source file:com.villemos.ispace.httpcrawler.HttpAccessor.java

public int poll() throws Exception {

    /** Always ignore authentication protocol errors. */
    if (ignoreAuthenticationFailure) {
        SSLContext sslContext = SSLContext.getInstance("SSL");

        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new EasyX509TrustManager() }, new SecureRandom());

        SchemeRegistry schemeRegistry = new SchemeRegistry();

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

        SocketFactory sfa = new PlainSocketFactory();
        Scheme httpScheme = new Scheme("http", sfa, 80);
        schemeRegistry.register(httpScheme);

        HttpParams params = new BasicHttpParams();
        ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);

        client = new DefaultHttpClient(cm, params);
    } else {/*from  w ww .j av a2s.  c  o  m*/
        client = new DefaultHttpClient();
    }

    String proxyHost = getHttpCrawlerEndpoint().getProxyHost();
    Integer proxyPort = getHttpCrawlerEndpoint().getProxyPort();

    if (proxyHost != null && proxyPort != null) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    } else {
        ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
        client.setRoutePlanner(routePlanner);
    }

    /** The target location may demand authentication. We setup preemptive authentication. */
    if (getHttpCrawlerEndpoint().getAuthenticationUser() != null
            && getHttpCrawlerEndpoint().getAuthenticationPassword() != null) {
        client.getCredentialsProvider().setCredentials(
                new AuthScope(getHttpCrawlerEndpoint().getDomain(), getHttpCrawlerEndpoint().getPort()),
                new UsernamePasswordCredentials(getHttpCrawlerEndpoint().getAuthenticationUser(),
                        getHttpCrawlerEndpoint().getAuthenticationPassword()));
    }

    /** Set default cookie policy and store. Can be overridden for a specific method using for example;
     *    method.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); 
     */
    client.setCookieStore(cookieStore);
    client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

    String uriStr = getHttpCrawlerEndpoint().getProtocol() + "://" + getHttpCrawlerEndpoint().getDomain();
    if (getHttpCrawlerEndpoint().getPort() != 80) {
        uriStr += ":" + getHttpCrawlerEndpoint().getPort() + "" + getHttpCrawlerEndpoint().getPath();
    } else {
        uriStr += getHttpCrawlerEndpoint().getPath();
    }
    URI uri = new URI(uriStr);

    if (getHttpCrawlerEndpoint().getPort() != 80) {
        target = new HttpHost(getHttpCrawlerEndpoint().getDomain(), getHttpCrawlerEndpoint().getPort(),
                getHttpCrawlerEndpoint().getProtocol());
    } else {
        target = new HttpHost(getHttpCrawlerEndpoint().getDomain());
    }
    localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    /** Default boundary is the domain. */
    getHttpCrawlerEndpoint().getBoundaries()
            .add(getHttpCrawlerEndpoint().getProtocol() + "://" + getHttpCrawlerEndpoint().getDomain());

    HttpUriRequest method = createInitialRequest(uri);
    HttpResponse response = client.execute(target, method, localContext);

    if (response.getStatusLine().getStatusCode() == 200) {
        processSite(uri, response);
    } else if (response.getStatusLine().getStatusCode() == 302) {
        HttpHost target = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        HttpGet get = new HttpGet(target.toURI());
        // HttpGet get = new HttpGet("https://om.eo.esa.int/oem/kt/dashboard.php");

        /** Read the response fully, to clear it. */
        HttpEntity entity = response.getEntity();
        HttpClientConfigurer.readFully(entity.getContent());

        response = client.execute(target, get, localContext);
        processSite(uri, response);
        System.out.println("Final target: " + target);
    } else {
        HttpEntity entity = response.getEntity();
        InputStream instream = entity.getContent();
        System.out.println(HttpClientConfigurer.readFully(instream));
    }

    return 0;
}

From source file:org.wso2.carbon.identity.thrift.authentication.client.internal.pool.SecureClientPoolFactory.java

@Override
public AuthenticatorService.Client makeObject(Object key)
        throws ThriftAuthenticationException, TTransportException {
    String[] keyElements = constructKeyElements((String) key);
    if (keyElements[0].equals(ThriftAuthenticationClient.Protocol.SSL.toString())) {
        if (params == null) {
            if (trustStore == null) {
                trustStore = System.getProperty("javax.net.ssl.trustStore");
                if (trustStore == null) {
                    throw new ThriftAuthenticationException("No trustStore found");
                }//  w  ww  .ja  v a2 s.com
            }

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

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

        TTransport receiverTransport = TSSLTransportFactory.getClientSocket(keyElements[1],
                Integer.parseInt(keyElements[2]), 0, params);

        TProtocol protocol = new TBinaryProtocol(receiverTransport);
        return new AuthenticatorService.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(ThriftAuthenticationClientConstants.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(keyElements[2]));

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

            THttpClient tclient = new THttpClient(
                    "https://" + keyElements[1] + ":" + keyElements[2] + "/thriftAuthenticator", client);
            TProtocol protocol = new TCompactProtocol(tclient);
            AuthenticatorService.Client authClient = new AuthenticatorService.Client(protocol);
            tclient.open();
            return authClient;
        } catch (Exception e) {
            throw new ThriftAuthenticationException(
                    "Cannot create Secure client for " + keyElements[1] + ":" + keyElements[2], e);
        }
    }
}

From source file:es.tid.fiware.rss.oauth.service.OauthManager.java

/**
 * Read needed properties from file./*from  w w  w.  ja va  2 s  .c  o  m*/
 */
@PostConstruct
private void readProperties() throws Exception {
    externalLogin = oauthProperties.getProperty("config.externalLogin");
    baseSite = oauthProperties.getProperty("config.baseUrl");
    clientId = oauthProperties.getProperty("config.client_id");
    clientSecret = oauthProperties.getProperty("config.client_secret");
    authorizeUrl = oauthProperties.getProperty("config.authorizeUrl");
    accessTokenUrl = oauthProperties.getProperty("config.accessTokenUrl");
    callbackURL = oauthProperties.getProperty("config.callbackURL");
    userInfoUrl = oauthProperties.getProperty("config.userInfoUrl");
    grantedRole = oauthProperties.getProperty("config.grantedRole");
    getApplicationsUrl = oauthProperties.getProperty("config.getApplications");
    useOauth = oauthProperties.getProperty("config.useOauth");
    // avoid certificate checking for problems regarding with them.
    SSLContext ctx = SSLContext.getInstance("TLS");
    X509TrustManager tm = new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    ctx.init(null, new TrustManager[] { tm }, null);
    SSLSocketFactory ssf = new SSLSocketFactory(ctx);
    ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    httpclient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", ssf, 443));
}

From source file:com.mymed.android.myjam.controller.CallManager.java

protected SchemeRegistry createSchemeRegistry(Context context) {
    InputStream certInStream = context.getResources().openRawResource(R.raw.mymed_truststore);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    // Create and initialize scheme registry
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    SSLSocketFactory sslf = null;

    try {/* w  w  w  .j a  v a 2 s  .c o  m*/
        KeyStore mymedTrusted = KeyStore.getInstance("BKS");

        mymedTrusted.load(certInStream, "alcotra".toCharArray());

        sslf = new SSLSocketFactory(mymedTrusted);

        sslf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (KeyStoreException e) {
        Log.e(TAG, "Wrong keystore type.", e);
    } catch (KeyManagementException e) {
        Log.e(TAG, "Error creating SSLSocketFactory.", e);
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "Error creating SSLSocketFactory.", e);
    } catch (UnrecoverableKeyException e) {
        Log.e(TAG, "Error creating SSLSocketFactory.", e);
    } catch (CertificateException e) {
        Log.e(TAG, "Error loading keystore certificate.", e);
    } catch (IOException e) {
        Log.e(TAG, "Error creating scheme registry.", e);
    } finally {

        if (sslf != null) {
            schemeRegistry.register(new Scheme("https", sslf, 8081));
        }
        try {
            certInStream.close();
        } catch (IOException e) {
            Log.e(TAG, "Error closing the certificate stream.", e);
        }

    }
    return schemeRegistry;
}

From source file:com.axelor.apps.account.ebics.client.HttpRequestSender.java

private DefaultHttpClient getSecuredHttpClient(Certificate cert) throws AxelorException {

    DefaultHttpClient client = new DefaultHttpClient();

    try {//from   w  ww. j  a v a2  s.c  o m
        KeyStore keystore = KeyStore.getInstance("jks");
        char[] password = "NoPassword".toCharArray();
        keystore.load(null, password);
        keystore.setCertificateEntry("certficate.host", cert);
        Scheme https = new Scheme("https", 443, new SSLSocketFactory(keystore));
        client.getConnectionManager().getSchemeRegistry().register(https);
    } catch (Exception e) {
        e.printStackTrace();
        throw new AxelorException(I18n.get("Error adding certificate"), IException.TECHNICAL);
    }

    return client;
}

From source file:es.tid.fiware.fiwareconnectors.cygnus.http.HttpClientFactory.java

/**
 * Gets a SchemeRegistry object accepting all the X509 certificates by default.
 * @return A SchemeRegistry object.//from   ww  w .  j  a v a2 s .c  o  m
 */
private SchemeRegistry getSchemeRegistry() {
    // http://stackoverflow.com/questions/2703161/how-to-ignore-ssl-certificate-errors-in-apache-httpclient-4-0

    SSLContext sslContext = null;

    try {
        sslContext = SSLContext.getInstance("SSL");
    } catch (NoSuchAlgorithmException e) {
        logger.fatal("Fatal error (SSL cannot be used, no such algorithm. Details=" + e.getMessage() + ")");
        return null;
    } // try catch

    try {
        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            } // getAcceptedIssuers

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            } // getAcceptedIssuers

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            } // checkServerTrusted
        } }, new SecureRandom());
    } catch (KeyManagementException e) {
        logger.fatal("Fatal error (Cannot ignore SSL certificates. Details=" + e.getMessage() + ")");
        return null;
    } // try catch

    if (sslContext == null) {
        logger.fatal("Fatal error (Cannot ignore SSL certificates, SSL context is null)");
        return null;
    } // if

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

From source file:com.longle1.facedetection.TimedAsyncHttpResponseHandler.java

public void executePut(String putURL, RequestParams params, String filename) {
    try {/*from w w  w.ja va2  s  .  c om*/
        AsyncHttpClient client = new AsyncHttpClient();
        FileEntity fe = null;
        fe = new FileEntity(new File(filename), "audio/wav");

        // Add SSL
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(mContext.getResources().openRawResource(R.raw.truststore), "changeit".toCharArray());
        SSLSocketFactory sf = new SSLSocketFactory(trustStore);
        client.setSSLSocketFactory(sf);

        client.setTimeout(30000);

        client.put(null, putURL + "?" + params.toString(), fe, null, this);
    } catch (Exception e) {
        e.printStackTrace();
    }
    Log.i("executePut", "done");
}

From source file:org.jclouds.http.apachehc.config.ApacheHCHttpCommandExecutorServiceModule.java

@Singleton
@Provides/*from w ww  .ja  v  a2s .c o  m*/
final ClientConnectionManager newClientConnectionManager(HttpParams params, X509HostnameVerifier verifier,
        SSLContext context, Closer closer) throws NoSuchAlgorithmException, KeyManagementException {

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

    SSLSocketFactory sf = new SSLSocketFactory(context);
    sf.setHostnameVerifier(verifier);
    schemeRegistry.register(new Scheme("https", sf, 443));

    final ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    closer.addToClose(new Closeable() {
        @Override
        public void close() throws IOException {
            cm.shutdown();
        }
    });
    return cm;
}

From source file:org.dataconservancy.archive.impl.fcrepo.ri.MultiThreadedHttpClient.java

private static SSLSocketFactory createSSLSocketFactory(boolean skipSSLTrustCheck,
        boolean skipSSLHostnameVerification) {
    SSLContext sslContext = null;
    try {/*from   w  ww .  jav  a2s.  co m*/
        if (skipSSLTrustCheck) {
            sslContext = SSLContext.getInstance("TLS");
            TrustManager easyTrustManager = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    // Oh, I am easy!
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    // Oh, I am easy!
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            sslContext.init(null, new TrustManager[] { easyTrustManager }, null);
        } else {
            sslContext = SSLContext.getDefault();
        }
    } catch (KeyManagementException wontHappen) {
        throw new RuntimeException(wontHappen);
    } catch (NoSuchAlgorithmException wontHappen) {
        throw new RuntimeException(wontHappen);
    }
    SSLSocketFactory factory = new SSLSocketFactory(sslContext);
    if (skipSSLHostnameVerification) {
        factory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    }
    return factory;
}