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

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

Introduction

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

Prototype

X509HostnameVerifier BROWSER_COMPATIBLE_HOSTNAME_VERIFIER

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

Click Source Link

Usage

From source file:android.locationprivacy.algorithm.Webservice.java

@Override
public Location obfuscate(Location location) {
    // We do it this way to run network connection in main thread. This
    // way is not the normal one and does not comply to best practices,
    // but the main thread must wait for the obfuscation service reply anyway.
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);//from  www .j av  a  2s  .  c o m

    final String HOST_ADDRESS = configuration.getString("host");
    String username = configuration.getString("username");
    String password = configuration.getString("secret_password");

    Location newLoc = new Location(location);
    double lat = location.getLatitude();
    double lon = location.getLongitude();

    String urlString = HOST_ADDRESS;
    urlString += "?lat=" + lat;
    urlString += "&lon=" + lon;
    URL url;
    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        Log.e(TAG, "Error: could not build URL");
        Log.e(TAG, e.getMessage());
        return null;
    }
    HttpsURLConnection connection = null;
    JSONObject json = null;
    InputStream is = null;
    try {
        connection = (HttpsURLConnection) url.openConnection();
        connection.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        connection.setRequestProperty("Authorization",
                "Basic " + Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP));
        is = connection.getInputStream();

    } catch (IOException e) {
        Log.e(TAG, "Error while connectiong to " + url.toString());
        Log.e(TAG, e.getMessage());
        return null;
    }
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    try {
        String line = reader.readLine();
        System.out.println("Line " + line);
        json = new JSONObject(line);
        newLoc.setLatitude(json.getDouble("lat"));
        newLoc.setLongitude(json.getDouble("lon"));
    } catch (IOException e) {
        Log.e(TAG, "Error: could not read from BufferedReader");
        Log.e(TAG, e.getMessage());
        return null;
    } catch (JSONException e) {
        Log.e(TAG, "Error: could not read from JSON");
        Log.e(TAG, e.getMessage());
        return null;
    }
    connection.disconnect();
    return newLoc;
}

From source file:com.cloudbees.eclipse.core.util.Utils.java

/**
 * @param url//from  w w w.j  av  a  2  s .  c  o m
 *          url to connec. Required to determine proxy settings if available. If <code>null</code> then proxy is not
 *          configured for the client returned.
 * @return
 * @throws CloudBeesException
 */
public final static DefaultHttpClient getAPIClient(String url) throws CloudBeesException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        HttpClientParams.setCookiePolicy(httpclient.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);

        String version = null;
        if (CloudBeesCorePlugin.getDefault() != null) {
            version = CloudBeesCorePlugin.getDefault().getBundle().getVersion().toString();
        } else {
            version = "n/a";
        }
        HttpProtocolParams.setUserAgent(httpclient.getParams(), "CBEclipseToolkit/" + version);

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

        CloudBeesCorePlugin plugin = CloudBeesCorePlugin.getDefault();

        URL truststore;

        if (plugin == null) {
            //Outside the OSGI environment, try to open the stream from the current dir.
            truststore = new File("truststore").toURI().toURL();
        } else {
            truststore = plugin.getBundle().getResource("truststore");
        }

        InputStream instream = truststore.openStream();

        try {
            trustStore.load(instream, "123456".toCharArray());
        } finally {
            instream.close();
        }

        TrustStrategy trustAllStrategy = new TrustStrategy() {
            @Override
            public boolean isTrusted(final X509Certificate[] chain, final String authType)
                    throws CertificateException {
                return true;
            }
        };

        SSLSocketFactory socketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, null, null, trustStore,
                null, trustAllStrategy, SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        // Override https handling to use provided truststore
        @SuppressWarnings("deprecation")
        Scheme sch = new Scheme("https", socketFactory, 443);
        httpclient.getConnectionManager().getSchemeRegistry().register(sch);

        HttpParams params = httpclient.getParams();

        //TODO Make configurable from the UI?
        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);

        if (CloudBeesCorePlugin.getDefault() != null) { // exclude proxy support when running outside eclipse
            IProxyService ps = CloudBeesCorePlugin.getDefault().getProxyService();
            if (ps.isProxiesEnabled()) {

                IProxyData[] pr = ps.select(new URI(url));

                //NOTE! For now we use just the first proxy settings with type HTTP or HTTPS to try out the connection. If configuration has more than 1 conf then for now this likely won't work!
                if (pr != null) {
                    for (int i = 0; i < pr.length; i++) {

                        IProxyData prd = pr[i];

                        if (IProxyData.HTTP_PROXY_TYPE.equals(prd.getType())
                                || IProxyData.HTTPS_PROXY_TYPE.equals(prd.getType())) {

                            String proxyHost = prd.getHost();
                            int proxyPort = prd.getPort();
                            String proxyUser = prd.getUserId();
                            String proxyPass = prd.getPassword();

                            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
                            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

                            if (prd.isRequiresAuthentication()) {
                                List authpref = new ArrayList();
                                authpref.add(AuthPolicy.BASIC);
                                AuthScope authScope = new AuthScope(proxyHost, proxyPort);
                                httpclient.getCredentialsProvider().setCredentials(authScope,
                                        new UsernamePasswordCredentials(proxyUser, proxyPass));
                            }

                            break;

                        }

                    }
                }
            }
        }

        /*      httpclient.getHostConfiguration().setProxy(proxyHost,proxyPort);      
              //if there are proxy credentials available, set those too
              Credentials proxyCredentials = null;
              String proxyUser = beesClientConfiguration.getProxyUser();
              String proxyPassword = beesClientConfiguration.getProxyPassword();
              if(proxyUser != null || proxyPassword != null)
        proxyCredentials = new UsernamePasswordCredentials(proxyUser, proxyPassword);
              if(proxyCredentials != null)
        client.getState().setProxyCredentials(AuthScope.ANY, proxyCredentials);
                
        */

        return httpclient;

    } catch (Exception e) {
        throw new CloudBeesException("Error while initiating access to JSON APIs!", e);
    }
}

From source file:pt.lunacloud.http.AmazonHttpClient.java

/**
 * Disables the default strict hostname verification in this client and
 * instead uses a browser compatible hostname verification strategy (i.e.
 * cert hostname wildcards are evaulated more liberally).
 *//* w ww  .  j  av a2s.c o  m*/
public void disableStrictHostnameVerification() {
    try {
        SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry();

        SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getDefault(),
                SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        Scheme https = new Scheme("https", 443, sf);

        schemeRegistry.register(https);
    } catch (NoSuchAlgorithmException e) {
        throw new LunacloudClientException(
                "Unable to access default SSL context to disable strict hostname verification");
    }
}

From source file:cn.ctyun.amazonaws.http.AmazonHttpClient.java

/**
 * Disables the default strict hostname verification in this client and
 * instead uses a browser compatible hostname verification strategy (i.e.
 * cert hostname wildcards are evaulated more liberally).
 *///from   www  . jav  a2  s. c o m
public void disableStrictHostnameVerification() {

    /*
     * If SSL cert checking for endpoints is disabled, we don't need
     * to do any changes to the SSL context.
     */
    if (System.getProperty("com.amazonaws.sdk.disableCertChecking") != null) {
        return;
    }

    try {
        SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry();

        SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getDefault(),
                SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        Scheme https = new Scheme("https", 443, sf);

        schemeRegistry.register(https);
    } catch (NoSuchAlgorithmException e) {
        throw new AmazonClientException(
                "Unable to access default SSL context to disable strict hostname verification");
    }
}

From source file:org.commonjava.maven.galley.transport.htcli.internal.LocationSSLSocketFactory.java

private synchronized SSLSocketFactory getSSLFactory(final HttpLocation loc) throws IOException {
    //        logger.info( "Finding SSLSocketFactory for repo: {}", repo.getKey() );

    SSLSocketFactory factory = null; // repoFactories.get( repo );
    if (factory == null) {
        KeyStore ks = null;// w ww . j a  v a2s . c  om
        KeyStore ts = null;

        final String kcPem = loc.getKeyCertPem();
        final String kcPass = passwordManager.getPassword(new PasswordEntry(loc, PasswordEntry.KEY_PASSWORD));
        if (kcPem != null) {
            if (kcPass == null || kcPass.length() < 1) {
                logger.error("Invalid configuration. Location: {} cannot have an empty key password!",
                        loc.getUri());
                throw new IOException("Location: " + loc.getUri() + " is misconfigured!");
            }

            try {
                ks = SSLUtils.readKeyAndCert(kcPem, kcPass);

                //                    final StringBuilder sb = new StringBuilder();
                //                    sb.append( "Keystore contains the following certificates:" );
                //
                //                    for ( final Enumeration<String> aliases = ks.aliases(); aliases.hasMoreElements(); )
                //                    {
                //                        final String alias = aliases.nextElement();
                //                        final X509Certificate cert = (X509Certificate) ks.getCertificate( alias );
                //
                //                        if ( cert != null )
                //                        {
                //                            sb.append( "\n" )
                //                              .append( cert.getSubjectDN() );
                //                        }
                //                    }
                //                    sb.append( "\n" );
                //                    logger.info( sb.toString() );
            } catch (final CertificateException e) {
                logger.error(String.format(
                        "Invalid configuration. Location: %s has an invalid client certificate! Error: %s",
                        loc.getUri(), e.getMessage()), e);
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            } catch (final KeyStoreException e) {
                logger.error(String.format(
                        "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s",
                        loc.getUri(), e.getMessage()), e);
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            } catch (final NoSuchAlgorithmException e) {
                logger.error(String.format(
                        "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s",
                        loc.getUri(), e.getMessage()), e);
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            } catch (final InvalidKeySpecException e) {
                logger.error(
                        String.format("Invalid configuration. Invalid client key for repository: %s. Error: %s",
                                loc.getUri(), e.getMessage()),
                        e);
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            }
        }

        final String sPem = loc.getServerCertPem();
        //            logger.info( "Server certificate PEM:\n{}", sPem );
        if (sPem != null) {
            try {
                ts = SSLUtils.readCerts(sPem, loc.getHost());

                //                    final StringBuilder sb = new StringBuilder();
                //                    sb.append( "Trust store contains the following certificates:" );
                //
                //                    for ( final Enumeration<String> aliases = ts.aliases(); aliases.hasMoreElements(); )
                //                    {
                //                        final String alias = aliases.nextElement();
                //                        final X509Certificate cert = (X509Certificate) ts.getCertificate( alias );
                //                        if ( cert != null )
                //                        {
                //                            sb.append( "\n" )
                //                              .append( cert.getSubjectDN() );
                //                        }
                //                    }
                //                    sb.append( "\n" );
                //                    logger.info( sb.toString() );
            } catch (final CertificateException e) {
                logger.error(String.format(
                        "Invalid configuration. Location: %s has an invalid server certificate! Error: %s",
                        loc.getUri(), e.getMessage()), e);
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            } catch (final KeyStoreException e) {
                logger.error(String.format(
                        "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s",
                        loc.getUri(), e.getMessage()), e);
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            } catch (final NoSuchAlgorithmException e) {
                logger.error(String.format(
                        "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s",
                        loc.getUri(), e.getMessage()), e);
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            }
        }

        if (ks != null || ts != null) {
            try {
                factory = new SSLSocketFactory(SSLSocketFactory.TLS, ks, kcPass, ts, null, null,
                        SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

                // repoFactories.put( repo, factory );
            } catch (final KeyManagementException e) {
                logger.error(
                        "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}",
                        e, loc.getUri(), e.getMessage());
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            } catch (final UnrecoverableKeyException e) {
                logger.error(
                        "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}",
                        e, loc.getUri(), e.getMessage());
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            } catch (final NoSuchAlgorithmException e) {
                logger.error(
                        "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}",
                        e, loc.getUri(), e.getMessage());
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            } catch (final KeyStoreException e) {
                logger.error(
                        "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}",
                        e, loc.getUri(), e.getMessage());
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            }
        }
    }

    return factory;
}

From source file:com.neusou.bioroid.restful.RestfulClient.java

/**
 * Creates a <b>RestfulClient</b><br/><br/>
 * The intent actions will generated with the following rule: <br/><br/>
 * &lt;the package name of the supplied context&gt;.&lt;the supplied name&gt;.restful.&lt;the action name&gt;
 * /*from   ww w  .  j  a va2  s . c om*/
 * <br/><br/>Example: with context has package name com.neusou.facegraph and FB as the restful client name:<br/><br/>
 * com.neusou.facegraph.FB.restful.PROCESS_RESPONSE<br/>
 * com.neusou.facegraph.FB.restful.EXECUTE_REQUEST<br/>
 * com.neusou.facegraph.FB.restful.EXECUTE_REQUEST
 * <br/>
 * @param context context
 * @param name the unique name of the restful client
 */
public RestfulClient(Context context, String name) {
    if (name == null) {
        throw new IllegalArgumentException("name can not be null");
    }

    if (context == null) {
        Logger.l(Logger.WARN, LOG_TAG, "Required Context argument is null.");
    }

    mContext = context;
    mName = name;

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

    SchemeRegistry scheme = new SchemeRegistry();
    scheme.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
    sslSocketFactory.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    scheme.register(new Scheme("https", sslSocketFactory, 443));

    ThreadSafeClientConnManager tscm = new ThreadSafeClientConnManager(httpParams, scheme);

    httpClient = new DefaultHttpClient(tscm, httpParams);
    httpClient.setReuseStrategy(new ConnectionReuseStrategy() {
        @Override
        public boolean keepAlive(HttpResponse response, HttpContext context) {
            return false;
        }
    });

    mExecutor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            //   Logger.l(Logger.DEBUG, LOG_TAG, "rejectedExecution. #activethread:"+executor.getActiveCount()+", queue.size:"+executor.getQueue().size());            
        }
    });

    if (context != null) {
        setContext(context);
    }
}

From source file:com.amazonaws.client.service.AmazonHttpClient.java

/**
 * Disables the default strict hostname verification in this client and
 * instead uses a browser compatible hostname verification strategy (i.e.
 * cert hostname wildcards are evaulated more liberally).
 *//*from  w ww  .  ja va  2s.  c  o  m*/
public void disableStrictHostnameVerification() {

    /*
     * If SSL cert checking for endpoints is disabled, we don't need
     * to do any changes to the SSL context.
     */
    if (System.getProperty(DISABLE_CERT_CHECKING_SYSTEM_PROPERTY) != null) {
        return;
    }

    try {
        SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry();

        SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getDefault(),
                SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        Scheme https = new Scheme("https", 443, sf);

        schemeRegistry.register(https);
    } catch (NoSuchAlgorithmException e) {
        throw new AmazonClientException(
                "Unable to access default SSL context to disable strict hostname verification");
    }
}

From source file:com.redhat.rcm.version.util.InputUtils.java

private static void setupClient() throws VManException {
    if (client == null) {
        SSLSocketFactory sslSocketFactory;
        try {//from ww  w .j  a  v a2s .  c o  m
            sslSocketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, null, null, trustKs, null,
                    new TrustSelfSignedStrategy(), SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            //                sslSocketFactory =
            //                    new SSLSocketFactory( SSLSocketFactory.TLS, null, null, trustKs, null, null,
            //                                          SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER );
        } catch (final KeyManagementException e) {
            logger.error("Failed to setup SSL socket factory: {}", e, e.getMessage());
            throw new VManException("Failed to setup SSL socket factory: %s", e, e.getMessage());
        } catch (final UnrecoverableKeyException e) {
            logger.error("Failed to setup SSL socket factory: {}", e, e.getMessage());
            throw new VManException("Failed to setup SSL socket factory: %s", e, e.getMessage());
        } catch (final NoSuchAlgorithmException e) {
            logger.error("Failed to setup SSL socket factory: {}", e, e.getMessage());
            throw new VManException("Failed to setup SSL socket factory: %s", e, e.getMessage());
        } catch (final KeyStoreException e) {
            logger.error("Failed to setup SSL socket factory: {}", e, e.getMessage());
            throw new VManException("Failed to setup SSL socket factory: %s", e, e.getMessage());
        }

        final ThreadSafeClientConnManager ccm = new ThreadSafeClientConnManager();
        ccm.getSchemeRegistry().register(new Scheme("https", 443, sslSocketFactory));

        final DefaultHttpClient hc = new DefaultHttpClient(ccm);
        hc.setRedirectStrategy(new DefaultRedirectStrategy());

        final String proxyHost = System.getProperty("http.proxyHost");
        final int proxyPort = Integer.parseInt(System.getProperty("http.proxyPort", "-1"));

        if (proxyHost != null && proxyPort > 0) {
            final HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            hc.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
        }

        client = hc;
    }
}

From source file:com.marklogic.client.impl.JerseyServices.java

@Override
public void connect(String host, int port, String database, String user, String password,
        Authentication authenType, SSLContext context, SSLHostnameVerifier verifier) {
    X509HostnameVerifier x509Verifier = null;
    if (verifier == null) {
        if (context != null)
            x509Verifier = SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
    } else if (verifier == SSLHostnameVerifier.ANY)
        x509Verifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    else if (verifier == SSLHostnameVerifier.COMMON)
        x509Verifier = SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
    else if (verifier == SSLHostnameVerifier.STRICT)
        x509Verifier = SSLSocketFactory.STRICT_HOSTNAME_VERIFIER;
    else if (context != null)
        x509Verifier = new HostnameVerifierAdapter(verifier);
    else/*from w  w w  . ja  va  2 s.  co m*/
        throw new IllegalArgumentException("Null SSLContent but non-null SSLHostnameVerifier for client");

    connect(host, port, database, user, password, authenType, context, x509Verifier);
}