Example usage for javax.net.ssl SSLContext getSocketFactory

List of usage examples for javax.net.ssl SSLContext getSocketFactory

Introduction

In this page you can find the example usage for javax.net.ssl SSLContext getSocketFactory.

Prototype

public final SSLSocketFactory getSocketFactory() 

Source Link

Document

Returns a SocketFactory object for this context.

Usage

From source file:com.photon.phresco.framework.rest.api.util.FrameworkServiceUtil.java

public static List<CertificateInfo> getCertificate(String host, int port) throws PhrescoException {
    List<CertificateInfo> certificates = new ArrayList<CertificateInfo>();
    CertificateInfo info;/*from   ww  w . ja  v  a  2 s .c  om*/
    try {
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        SSLContext context = SSLContext.getInstance("TLS");
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
        SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
        context.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory factory = context.getSocketFactory();
        SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        try {
            socket.startHandshake();
            socket.close();
        } catch (SSLException e) {

        }
        X509Certificate[] chain = tm.chain;
        for (int i = 0; i < chain.length; i++) {
            X509Certificate x509Certificate = chain[i];
            String subjectDN = x509Certificate.getSubjectDN().getName();
            String[] split = subjectDN.split(",");
            info = new CertificateInfo();
            info.setSubjectDN(subjectDN);
            info.setDisplayName(split[0]);
            info.setCertificate(x509Certificate);
            certificates.add(info);
        }
    } catch (Exception e) {
        throw new PhrescoException(e);
    }
    return certificates;
}

From source file:org.apache.nifi.ldap.tenants.LdapUserGroupProvider.java

@Override
public void onConfigured(final AuthorizerConfigurationContext configurationContext)
        throws AuthorizerCreationException {
    final LdapContextSource context = new LdapContextSource();

    final Map<String, Object> baseEnvironment = new HashMap<>();

    // connect/read time out
    setTimeout(configurationContext, baseEnvironment, PROP_CONNECT_TIMEOUT,
            "com.sun.jndi.ldap.connect.timeout");
    setTimeout(configurationContext, baseEnvironment, PROP_READ_TIMEOUT, "com.sun.jndi.ldap.read.timeout");

    // authentication strategy
    final PropertyValue rawAuthenticationStrategy = configurationContext
            .getProperty(PROP_AUTHENTICATION_STRATEGY);
    final LdapAuthenticationStrategy authenticationStrategy;
    try {// www.  ja  v  a 2s  .  co  m
        authenticationStrategy = LdapAuthenticationStrategy.valueOf(rawAuthenticationStrategy.getValue());
    } catch (final IllegalArgumentException iae) {
        throw new AuthorizerCreationException(
                String.format("Unrecognized authentication strategy '%s'. Possible values are [%s]",
                        rawAuthenticationStrategy.getValue(),
                        StringUtils.join(LdapAuthenticationStrategy.values(), ", ")));
    }

    switch (authenticationStrategy) {
    case ANONYMOUS:
        context.setAnonymousReadOnly(true);
        break;
    default:
        final String userDn = configurationContext.getProperty(PROP_MANAGER_DN).getValue();
        final String password = configurationContext.getProperty(PROP_MANAGER_PASSWORD).getValue();

        context.setUserDn(userDn);
        context.setPassword(password);

        switch (authenticationStrategy) {
        case SIMPLE:
            context.setAuthenticationStrategy(new SimpleDirContextAuthenticationStrategy());
            break;
        case LDAPS:
            context.setAuthenticationStrategy(new SimpleDirContextAuthenticationStrategy());

            // indicate a secure connection
            baseEnvironment.put(Context.SECURITY_PROTOCOL, "ssl");

            // get the configured ssl context
            final SSLContext ldapsSslContext = getConfiguredSslContext(configurationContext);
            if (ldapsSslContext != null) {
                // initialize the ldaps socket factory prior to use
                LdapsSocketFactory.initialize(ldapsSslContext.getSocketFactory());
                baseEnvironment.put("java.naming.ldap.factory.socket", LdapsSocketFactory.class.getName());
            }
            break;
        case START_TLS:
            final AbstractTlsDirContextAuthenticationStrategy tlsAuthenticationStrategy = new DefaultTlsDirContextAuthenticationStrategy();

            // shutdown gracefully
            final String rawShutdownGracefully = configurationContext.getProperty("TLS - Shutdown Gracefully")
                    .getValue();
            if (StringUtils.isNotBlank(rawShutdownGracefully)) {
                final boolean shutdownGracefully = Boolean.TRUE.toString()
                        .equalsIgnoreCase(rawShutdownGracefully);
                tlsAuthenticationStrategy.setShutdownTlsGracefully(shutdownGracefully);
            }

            // get the configured ssl context
            final SSLContext startTlsSslContext = getConfiguredSslContext(configurationContext);
            if (startTlsSslContext != null) {
                tlsAuthenticationStrategy.setSslSocketFactory(startTlsSslContext.getSocketFactory());
            }

            // set the authentication strategy
            context.setAuthenticationStrategy(tlsAuthenticationStrategy);
            break;
        }
        break;
    }

    // referrals
    final String rawReferralStrategy = configurationContext.getProperty(PROP_REFERRAL_STRATEGY).getValue();

    final ReferralStrategy referralStrategy;
    try {
        referralStrategy = ReferralStrategy.valueOf(rawReferralStrategy);
    } catch (final IllegalArgumentException iae) {
        throw new AuthorizerCreationException(
                String.format("Unrecognized referral strategy '%s'. Possible values are [%s]",
                        rawReferralStrategy, StringUtils.join(ReferralStrategy.values(), ", ")));
    }

    // using the value as this needs to be the lowercase version while the value is configured with the enum constant
    context.setReferral(referralStrategy.getValue());

    // url
    final String urls = configurationContext.getProperty(PROP_URL).getValue();

    if (StringUtils.isBlank(urls)) {
        throw new AuthorizerCreationException("LDAP identity provider 'Url' must be specified.");
    }

    // connection
    context.setUrls(StringUtils.split(urls));

    // raw user search base
    final PropertyValue rawUserSearchBase = configurationContext.getProperty(PROP_USER_SEARCH_BASE);
    final PropertyValue rawUserObjectClass = configurationContext.getProperty(PROP_USER_OBJECT_CLASS);
    final PropertyValue rawUserSearchScope = configurationContext.getProperty(PROP_USER_SEARCH_SCOPE);

    // if loading the users, ensure the object class set
    if (rawUserSearchBase.isSet() && !rawUserObjectClass.isSet()) {
        throw new AuthorizerCreationException(
                "LDAP user group provider 'User Object Class' must be specified when 'User Search Base' is set.");
    }

    // if loading the users, ensure the search scope is set
    if (rawUserSearchBase.isSet() && !rawUserSearchScope.isSet()) {
        throw new AuthorizerCreationException(
                "LDAP user group provider 'User Search Scope' must be specified when 'User Search Base' is set.");
    }

    // user search criteria
    userSearchBase = rawUserSearchBase.getValue();
    userObjectClass = rawUserObjectClass.getValue();
    userSearchFilter = configurationContext.getProperty(PROP_USER_SEARCH_FILTER).getValue();
    userIdentityAttribute = configurationContext.getProperty(PROP_USER_IDENTITY_ATTRIBUTE).getValue();
    userGroupNameAttribute = configurationContext.getProperty(PROP_USER_GROUP_ATTRIBUTE).getValue();
    userGroupReferencedGroupAttribute = configurationContext
            .getProperty(PROP_USER_GROUP_REFERENCED_GROUP_ATTRIBUTE).getValue();

    try {
        userSearchScope = SearchScope.valueOf(rawUserSearchScope.getValue());
    } catch (final IllegalArgumentException iae) {
        throw new AuthorizerCreationException(
                String.format("Unrecognized user search scope '%s'. Possible values are [%s]",
                        rawUserSearchScope.getValue(), StringUtils.join(SearchScope.values(), ", ")));
    }

    // determine user behavior
    useDnForUserIdentity = StringUtils.isBlank(userIdentityAttribute);
    performUserSearch = StringUtils.isNotBlank(userSearchBase);

    // raw group search criteria
    final PropertyValue rawGroupSearchBase = configurationContext.getProperty(PROP_GROUP_SEARCH_BASE);
    final PropertyValue rawGroupObjectClass = configurationContext.getProperty(PROP_GROUP_OBJECT_CLASS);
    final PropertyValue rawGroupSearchScope = configurationContext.getProperty(PROP_GROUP_SEARCH_SCOPE);

    // if loading the groups, ensure the object class is set
    if (rawGroupSearchBase.isSet() && !rawGroupObjectClass.isSet()) {
        throw new AuthorizerCreationException(
                "LDAP user group provider 'Group Object Class' must be specified when 'Group Search Base' is set.");
    }

    // if loading the groups, ensure the search scope is set
    if (rawGroupSearchBase.isSet() && !rawGroupSearchScope.isSet()) {
        throw new AuthorizerCreationException(
                "LDAP user group provider 'Group Search Scope' must be specified when 'Group Search Base' is set.");
    }

    // group search criteria
    groupSearchBase = rawGroupSearchBase.getValue();
    groupObjectClass = rawGroupObjectClass.getValue();
    groupSearchFilter = configurationContext.getProperty(PROP_GROUP_SEARCH_FILTER).getValue();
    groupNameAttribute = configurationContext.getProperty(PROP_GROUP_NAME_ATTRIBUTE).getValue();
    groupMemberAttribute = configurationContext.getProperty(PROP_GROUP_MEMBER_ATTRIBUTE).getValue();
    groupMemberReferencedUserAttribute = configurationContext
            .getProperty(PROP_GROUP_MEMBER_REFERENCED_USER_ATTRIBUTE).getValue();

    try {
        groupSearchScope = SearchScope.valueOf(rawGroupSearchScope.getValue());
    } catch (final IllegalArgumentException iae) {
        throw new AuthorizerCreationException(
                String.format("Unrecognized group search scope '%s'. Possible values are [%s]",
                        rawGroupSearchScope.getValue(), StringUtils.join(SearchScope.values(), ", ")));
    }

    // determine group behavior
    useDnForGroupName = StringUtils.isBlank(groupNameAttribute);
    performGroupSearch = StringUtils.isNotBlank(groupSearchBase);

    // ensure we are either searching users or groups (at least one must be specified)
    if (!performUserSearch && !performGroupSearch) {
        throw new AuthorizerCreationException(
                "LDAP user group provider 'User Search Base' or 'Group Search Base' must be specified.");
    }

    // ensure group member attribute is set if searching groups but not users
    if (performGroupSearch && !performUserSearch && StringUtils.isBlank(groupMemberAttribute)) {
        throw new AuthorizerCreationException(
                "'Group Member Attribute' is required when searching groups but not users.");
    }

    // ensure that performUserSearch is set when groupMemberReferencedUserAttribute is specified
    if (StringUtils.isNotBlank(groupMemberReferencedUserAttribute) && !performUserSearch) {
        throw new AuthorizerCreationException(
                "''User Search Base' must be set when specifying 'Group Member Attribute - Referenced User Attribute'.");
    }

    // ensure that performGroupSearch is set when userGroupReferencedGroupAttribute is specified
    if (StringUtils.isNotBlank(userGroupReferencedGroupAttribute) && !performGroupSearch) {
        throw new AuthorizerCreationException(
                "'Group Search Base' must be set when specifying 'User Group Name Attribute - Referenced Group Attribute'.");
    }

    // get the page size if configured
    final PropertyValue rawPageSize = configurationContext.getProperty(PROP_PAGE_SIZE);
    if (rawPageSize.isSet() && StringUtils.isNotBlank(rawPageSize.getValue())) {
        pageSize = rawPageSize.asInteger();
    }

    // extract the identity mappings from nifi.properties if any are provided
    identityMappings = Collections.unmodifiableList(IdentityMappingUtil.getIdentityMappings(properties));

    // set the base environment is necessary
    if (!baseEnvironment.isEmpty()) {
        context.setBaseEnvironmentProperties(baseEnvironment);
    }

    try {
        // handling initializing beans
        context.afterPropertiesSet();
    } catch (final Exception e) {
        throw new AuthorizerCreationException(e.getMessage(), e);
    }

    final PropertyValue rawSyncInterval = configurationContext.getProperty(PROP_SYNC_INTERVAL);
    final long syncInterval;
    if (rawSyncInterval.isSet()) {
        try {
            syncInterval = FormatUtils.getTimeDuration(rawSyncInterval.getValue(), TimeUnit.MILLISECONDS);
        } catch (final IllegalArgumentException iae) {
            throw new AuthorizerCreationException(String.format("The %s '%s' is not a valid time duration",
                    PROP_SYNC_INTERVAL, rawSyncInterval.getValue()));
        }
        if (syncInterval < MINIMUM_SYNC_INTERVAL_MILLISECONDS) {
            throw new AuthorizerCreationException(
                    String.format("The %s '%s' is below the minimum value of '%d ms'", PROP_SYNC_INTERVAL,
                            rawSyncInterval.getValue(), MINIMUM_SYNC_INTERVAL_MILLISECONDS));
        }
    } else {
        throw new AuthorizerCreationException(String.format("The '%s' must be specified.", PROP_SYNC_INTERVAL));
    }

    try {
        // perform the initial load, tenants must be loaded as the configured UserGroupProvider is supplied
        // to the AccessPolicyProvider for granting initial permissions
        load(context);

        // ensure the tenants were successfully synced
        if (tenants.get() == null) {
            throw new AuthorizerCreationException("Unable to sync users and groups.");
        }

        // schedule the background thread to load the users/groups
        ldapSync.scheduleWithFixedDelay(() -> load(context), syncInterval, syncInterval, TimeUnit.MILLISECONDS);
    } catch (final AuthorizationAccessException e) {
        throw new AuthorizerCreationException(e);
    }
}

From source file:org.gvnix.service.roo.addon.addon.security.SecurityServiceImpl.java

/**
 * Get certificates in the chain of the host server and import them.
 * <p>/*from   w w  w.ja  v  a2  s .c om*/
 * Tries to get the certificates in the certificates chain of the host
 * server and import them to:
 * <ol>
 * <li>A custom keystore in <code>SRC_MAIN_RESOURCES/gvnix-cacerts</code></li>
 * <li>The JVM cacerts keystore in
 * <code>$JAVA_HOME/jre/lib/security/cacerts</code>. Here we can have a
 * problem if JVM <code>cacerts</code> file is not writable by the user due
 * to file permissions. In this case we throw an exception informing about
 * the error.</li>
 * </ol>
 * </p>
 * <p>
 * With that operation we can try again to get the WSDL.<br/>
 * Also it exports the chain certificates to <code>.cer</code> files in
 * <code>SRC_MAIN_RESOURCES</code>, so the developer can distribute them for
 * its installation in other environments or just in case we reach the
 * problem with the JVM <code>cacerts</code> file permissions.
 * </p>
 * 
 * @see GvNix509TrustManager#saveCertFile(String, X509Certificate,
 *      FileManager, PathResolver)
 * @see <a href=
 *      "http://download.oracle.com/javase/6/docs/technotes/tools/solaris/keytool.html"
 *      >Java SE keytool</a>.
 */
protected Document installCertificates(String loc, String pass)
        throws NoSuchAlgorithmException, KeyStoreException, Exception, KeyManagementException,
        MalformedURLException, IOException, UnknownHostException, SocketException, SAXException {

    // Create a SSL context
    SSLContext context = SSLContext.getInstance("TLS");
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

    // Passphrase of the keystore: "changeit" by default
    char[] passArray = (StringUtils.isNotBlank(pass) ? pass.toCharArray() : "changeit".toCharArray());

    // Get the project keystore and copy it from JVM if not exists
    File keystore = getProjectKeystore();

    tmf.init(GvNix509TrustManager.loadKeyStore(keystore, passArray));

    X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
    GvNix509TrustManager tm = new GvNix509TrustManager(defaultTrustManager);
    context.init(null, new TrustManager[] { tm }, null);
    SSLSocketFactory factory = context.getSocketFactory();

    // Open URL location (default 443 port if not defined)
    URL url = new URL(loc);
    String host = url.getHost();
    int port = url.getPort() == -1 ? 443 : url.getPort();
    SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
    socket.setSoTimeout(10000);

    Document doc = null;
    try {

        socket.startHandshake();
        URLConnection connection = url.openConnection();
        if (connection instanceof HttpsURLConnection) {
            ((HttpsURLConnection) connection).setSSLSocketFactory(factory);
        }

        doc = XmlUtils.getDocumentBuilder().parse(connection.getInputStream());

        socket.close();

    } catch (SSLException ssle) {

        // Get needed certificates for this host
        getCerts(tm, host, keystore, passArray);
        doc = getWsdl(loc, pass);

    } catch (IOException ioe) {

        invalidHostCert(passArray, keystore, tm, host);
    }

    Validate.notNull(doc, "No valid document format");
    return doc;
}

From source file:com.vmware.o11n.plugin.crypto.service.CryptoCertificateService.java

/**
 * Returns the certificate chain provided by the HTTPS server.
 *
 * The first certificate identifies the server.
 * The remainder should verify the cert upto a trusted root.
 *
 *
 * @param url/*from w  w  w.  j  a  v  a2  s.  co  m*/
 * @return
 * @throws IOException
 * @throws KeyManagementException
 * @throws NoSuchAlgorithmException
 */
public List<X509Certificate> getCertHttps(URL url)
        throws IOException, KeyManagementException, NoSuchAlgorithmException {
    ArrayList<X509Certificate> toReturn = new ArrayList<>();

    // Setup a temp ssl context that accepts all certificates for this connection
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
        private X509Certificate[] certToReturn;

        @Override
        public void checkClientTrusted(X509Certificate[] c, String s) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] c, String s) {
            certToReturn = c;
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return certToReturn;
        }
    } }, null);

    //Setup a temp hostname verifier that verifies all hostnames for this connection
    HostnameVerifier hv = new HostnameVerifier() {
        @Override
        public boolean verify(String s, SSLSession ss) {
            return true;
        }
    };
    HttpsURLConnection httpsConn = null;
    try {
        httpsConn = (HttpsURLConnection) url.openConnection();

        httpsConn.setSSLSocketFactory(sslContext.getSocketFactory());
        httpsConn.setHostnameVerifier(hv);
        httpsConn.connect();

        Certificate[] certs = httpsConn.getServerCertificates();

        for (Certificate cert : certs) {
            if (cert instanceof X509Certificate) {
                toReturn.add((X509Certificate) cert);
            }
        }
    } finally {
        if (httpsConn != null) {
            httpsConn.disconnect();
        }
    }
    return toReturn;
}

From source file:org.broad.igv.util.HttpUtils.java

/**
 * Code for disabling SSL certification//from   ww w .j  a  v  a  2 s  . co m
 */
private void disableCertificateValidation() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[0];
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (NoSuchAlgorithmException e) {
    } catch (KeyManagementException e) {
    }

}

From source file:com.cloudera.beeswax.BeeswaxServiceImpl.java

/**
 * Create a new BeeswaxServiceImpl.//from w  w  w.j ava  2s  .  c om
 *
 * @param dtHost The Hue host (ip or hostname).
 * @param dtPort The port Desktop runs on.
 * @param dtHttps Whether Desktop is running https.
 * @param queryLifetime The life time of a cached query.
 */
public BeeswaxServiceImpl(String dtHost, int dtPort, boolean dtHttps, long queryLifetime) {
    LogContext.initLogCapture();
    this.executor = Executors.newCachedThreadPool(new NamingThreadFactory("Beeswax-%d"));
    this.runningQueries = new ConcurrentHashMap<String, RunningQueryState>();
    this.queryLifetime = queryLifetime;

    if (dtPort == -1) {
        this.notifyUrl = null;
    } else {
        String protocol;
        if (dtHttps) {
            try {
                // Disable SSL verification. HUE cert may be signed by untrusted CA.
                SSLContext sslcontext = SSLContext.getInstance("SSL");
                sslcontext.init(null, new DummyX509TrustManager[] { new DummyX509TrustManager() },
                        new SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
            } catch (NoSuchAlgorithmException ex) {
                LOG.warn("Failed to disable SSL certificate check " + ex);
            } catch (KeyManagementException ex) {
                LOG.warn("Failed to disable SSL certificate check " + ex);
            }
            DummyHostnameVerifier dummy = new DummyHostnameVerifier();
            HttpsURLConnection.setDefaultHostnameVerifier(dummy);
            protocol = "https";
        } else {
            protocol = "http";
        }
        this.notifyUrl = protocol + "://" + dtHost + ":" + dtPort + NOTIFY_URL_BASE;
    }

    // A daemon thread that periodically evict stale RunningQueryState objects
    Thread evicter = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                long now = System.currentTimeMillis();
                for (Map.Entry<String, RunningQueryState> entry : runningQueries.entrySet()) {
                    RunningQueryState rqState = entry.getValue();
                    //safe guard against small value of lifetime, only clean FINISHED or EXCEPTION state
                    if ((rqState.state == QueryState.FINISHED || rqState.state == QueryState.EXCEPTION)
                            && rqState.getAtime() + getQueryLifetime() < now) {
                        String id = entry.getKey();
                        runningQueries.remove(id);
                        LOG.debug("Removed " + rqState.toString());
                        Thread.yield(); // be nice
                    }
                }

                LogContext.garbageCollect(getQueryLifetime());

                long wakeup = now + EVICTION_INTERVAL;
                while (System.currentTimeMillis() < wakeup) {
                    try {
                        Thread.sleep(EVICTION_INTERVAL);
                    } catch (InterruptedException e) {
                    }
                }
            }
        }
    }, "Evicter");
    evicter.setDaemon(true);
    evicter.start();
}

From source file:org.kymjs.kjframe.http.httpclient.HttpRequestBuilder.java

/**
 * Setup SSL connection.//  w ww .  j a va  2s  . co m
 */
private static void setupSecureConnection(Context context, HttpsURLConnection conn) throws IOException {
    final SSLContext sslContext;
    try {
        // SSL certificates are provided by the Guardian Project:
        // https://github.com/guardianproject/cacert
        if (trustManagers == null) {
            // Load SSL certificates:
            // http://nelenkov.blogspot.com/2011/12/using-custom-certificate-trust-store-on.html
            // Earlier Android versions do not have updated root CA
            // certificates, resulting in connection errors.
            final KeyStore keyStore = loadCertificates(context);

            final CustomTrustManager customTrustManager = new CustomTrustManager(keyStore);
            trustManagers = new TrustManager[] { customTrustManager };
        }

        // Init SSL connection with custom certificates.
        // The same SecureRandom instance is used for every connection to
        // speed up initialization.
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagers, SECURE_RANDOM);
    } catch (GeneralSecurityException e) {
        final IOException ioe = new IOException("Failed to initialize SSL engine");
        ioe.initCause(e);
        throw ioe;
    }

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        // Fix slow read:
        // http://code.google.com/p/android/issues/detail?id=13117
        // Prior to ICS, the host name is still resolved even if we already
        // know its IP address, for each connection.
        final SSLSocketFactory delegate = sslContext.getSocketFactory();
        final SSLSocketFactory socketFactory = new SSLSocketFactory() {
            @Override
            public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
                InetAddress addr = InetAddress.getByName(host);
                injectHostname(addr, host);
                return delegate.createSocket(addr, port);
            }

            @Override
            public Socket createSocket(InetAddress host, int port) throws IOException {
                return delegate.createSocket(host, port);
            }

            @Override
            public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
                    throws IOException, UnknownHostException {
                return delegate.createSocket(host, port, localHost, localPort);
            }

            @Override
            public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort)
                    throws IOException {
                return delegate.createSocket(address, port, localAddress, localPort);
            }

            private void injectHostname(InetAddress address, String host) {
                try {
                    Field field = InetAddress.class.getDeclaredField("hostName");
                    field.setAccessible(true);
                    field.set(address, host);
                } catch (Exception ignored) {
                }
            }

            @Override
            public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
                injectHostname(s.getInetAddress(), host);
                return delegate.createSocket(s, host, port, autoClose);
            }

            @Override
            public String[] getDefaultCipherSuites() {
                return delegate.getDefaultCipherSuites();
            }

            @Override
            public String[] getSupportedCipherSuites() {
                return delegate.getSupportedCipherSuites();
            }
        };
        conn.setSSLSocketFactory(socketFactory);
    } else {
        conn.setSSLSocketFactory(sslContext.getSocketFactory());
    }

    conn.setHostnameVerifier(new BrowserCompatHostnameVerifier());
}

From source file:com.hichinaschool.flashcards.async.Connection.java

private Payload doInBackgroundDownloadSharedDeck(Payload data) {
    String url = (String) data.data[0];
    String colFilename = AnkiDroidApp.getCurrentAnkiDroidDirectory() + "/tmpImportFile.apkg";
    URL fileUrl;/*from w w w  .  ja v  a 2s .  c o  m*/
    URLConnection conn;
    InputStream cont = null;
    try {
        fileUrl = new URL(url);
        if (url.startsWith("https")) {
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new TrustManager[] { new EasyX509TrustManager(null) }, null);
            HttpsURLConnection httpsConn = (HttpsURLConnection) fileUrl.openConnection();
            httpsConn.setSSLSocketFactory(context.getSocketFactory());
            conn = httpsConn;
        } else {
            conn = (HttpURLConnection) fileUrl.openConnection();
        }
        conn.setConnectTimeout(10000);
        conn.setReadTimeout(10000);
        cont = conn.getInputStream();
    } catch (MalformedURLException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundDownloadSharedDeck: ", e);
        data.success = false;
        return data;
    } catch (IOException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundDownloadSharedDeck: ", e);
        data.success = false;
        return data;
    } catch (NoSuchAlgorithmException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundDownloadSharedDeck: ", e);
        data.success = false;
        return data;
    } catch (KeyStoreException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundDownloadSharedDeck: ", e);
        return data;
    } catch (KeyManagementException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundDownloadSharedDeck: ", e);
        data.success = false;
        return data;
    }
    if (cont == null) {
        data.success = false;
        return data;
    }
    File file = new File(colFilename);
    OutputStream output = null;
    try {
        file.createNewFile();
        output = new BufferedOutputStream(new FileOutputStream(file));
        byte[] buf = new byte[Utils.CHUNK_SIZE];
        int len;
        int count = 0;
        while ((len = cont.read(buf)) >= 0) {
            output.write(buf, 0, len);
            count += len;
            publishProgress(new Object[] { count / 1024 });
        }
        output.close();
    } catch (IOException e) {
        try {
            output.close();
        } catch (IOException e1) {
            // do nothing
        }
        // no write access or sd card full
        file.delete();
        data.success = false;
        return data;
    }
    data.success = true;
    data.result = colFilename;
    return data;
}