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

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

Introduction

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

Prototype

X509HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER

To view the source code for org.apache.http.conn.ssl SSLSocketFactory ALLOW_ALL_HOSTNAME_VERIFIER.

Click Source Link

Usage

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");
                }/*from w ww . j  av a2  s  .c om*/
            }

            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:com.codingPower.framework.worker.FileNetWorker.java

/**
 * ?httpClient//from   ww w. j a  v a2  s .c  om
 * @return
 */
protected HttpClient getHttpClient() {

    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }

}

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 . ja  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:es.tid.fiware.rss.oauth.service.OauthManager.java

/**
 * Read needed properties from file.//from  w  w w . j  ava2  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:cn.com.loopj.android.http.MySSLSocketFactory.java

/**
 * Returns a SSlSocketFactory which trusts all certificates
 *
 * @return SSLSocketFactory/*from   w w w .  j  a va  2 s  .c o m*/
 */
public static SSLSocketFactory getFixedSocketFactory() {
    SSLSocketFactory socketFactory;
    try {
        socketFactory = new MySSLSocketFactory(getKeystore());
        socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (Throwable t) {
        t.printStackTrace();
        socketFactory = SSLSocketFactory.getSocketFactory();
    }
    return socketFactory;
}

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  2s.  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:hu.balazsbakai.sq.util.RestUtil.java

private DefaultHttpClient getNewTrustedHttpClient() {
    try {//w  ww .j  av a  2 s. c  om
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new CustomTrustedSSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, SOCKET_TIMEOUT);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        LogUtil.e("Exception", e);
        return new DefaultHttpClient();
    }
}

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 {/* w ww .  ja va2s.  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:com.rsa.redchallenge.standaloneapp.utils.RestInteractor.java

private static DefaultHttpClient getHttpClient() {

    if (ApplicationConstant.SA_BASE_URL.contains("https")) {
        TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
            @Override/*from   ww  w . java  2 s .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();
    }
}