Example usage for javax.net.ssl HttpsURLConnection setDefaultSSLSocketFactory

List of usage examples for javax.net.ssl HttpsURLConnection setDefaultSSLSocketFactory

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection setDefaultSSLSocketFactory.

Prototype

public static void setDefaultSSLSocketFactory(SSLSocketFactory sf) 

Source Link

Document

Sets the default SSLSocketFactory inherited by new instances of this class.

Usage

From source file:net.subclient.subsonic.SubsonicConnection.java

/**
 * Prepares HTTPS connections to accept any domains and self-signed certificates
 * @throws NoSuchAlgorithmException //from  w  w w  . ja  v  a 2 s  .  c  o m
 * @throws KeyManagementException 
 */
private void setSSLProperties() throws NoSuchAlgorithmException, KeyManagementException {
    //Disable certificate chacks to force trust self-signed certificates
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

        @Override
        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };
    SSLContext sc = null;
    sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    //Set a hostname verifier that trust any hostname
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        @Override
        public boolean verify(String arg0, SSLSession arg1) {
            return true;
        }
    };
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}

From source file:com.tsavo.trade.TradeBot.java

public static void initSSL() throws KeyManagementException, NoSuchAlgorithmException {

    // SSL Certificates trustStore ----------------------------------------
    // Set the SSL certificate for mtgox - Read up on Java Trust store.
    // System.setProperty("javax.net.ssl.trustStore", "trader.jks");
    // System.setProperty("javax.net.ssl.trustStorePassword", "zabbas"); //
    // I/* www  .j av  a  2s. com*/

    class MyManager implements X509TrustManager {

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }

    }

    TrustManager[] managers = new TrustManager[] { new MyManager() };
    final SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, managers, new SecureRandom());

    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });

    // System.setProperty("javax.net.debug","ssl"); //Uncomment for
    // debugging SSL errors

}

From source file:org.parosproxy.paros.network.SSLConnector.java

public SSLSocketFactory getClientSocketFactory(String type) {
    // Trust all invalid server certificate
    TrustManager[] trustMgr = new TrustManager[] { new RelaxedX509TrustManager() };

    try {//from  ww w  .  j  av  a  2  s . c  o  m
        SSLContext sslContext = SSLContext.getInstance(type);
        java.security.SecureRandom x = new java.security.SecureRandom();
        x.setSeed(System.currentTimeMillis());
        if (relaxedTrust) {
            sslContext.init(null, trustMgr, x);
        } else {
            sslContext.init(null, null, x);
        }
        clientSSLSockFactory = createDecoratedClientSslSocketFactory(sslContext.getSocketFactory());
        HttpsURLConnection.setDefaultSSLSocketFactory(clientSSLSockFactory);

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }

    return clientSSLSockFactory;

}

From source file:org.moe.cli.utils.GrabUtils.java

/**
 * Download file from remote/*from w w w .  j  a  v  a  2  s . c  om*/
 * @param link address of remote file
 * @param output symbolic link to the local file system where the downloaded file will be stored
 * @throws FileAlreadyExistsException if output file has already exists
 * @throws FileNotFoundException if link isn't present
 * @throws UnsupportedTypeException if URI links to file with unsupported type
 * @throws IOException if operation couldn't be successfully completed because of other reasons
 */
public static void downloadFileFromRemote(@NonNull URI link, @NonNull File output)
        throws FileAlreadyExistsException, FileNotFoundException, UnsupportedTypeException, IOException {

    if (output.exists()) {
        throw new FileAlreadyExistsException(output.toString() + " already exists!");
    }

    String scheme = link.getScheme();
    if (scheme == null) {
        throw new UnsupportedTypeException("Scheme should not be null!");
    } else if (scheme.equals("https")) {
        // Create a new trust manager that trust all certificates
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };

        // Activate the new trust manager
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            throw new IOException(e);
        }
    }

    URL url = link.normalize().toURL();
    FileUtils.copyURLToFile(url, output); //TODO: Timeout?...
}

From source file:com.adguard.compiler.Main.java

/**
 * Disable SSL validation (it may work wrong sometimes)
 *
 * @throws NoSuchAlgorithmException/* w  w w .  ja v  a2s. c  om*/
 * @throws KeyManagementException
 */
private static void disableSslValidation() throws NoSuchAlgorithmException, KeyManagementException {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };

    // Install the all-trusting trust manager
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}

From source file:com.lxh.util.image.OtherUtils.java

/**
 * HttpS//  www.  ja v a  2s  . c  o  m
 */
public static void trustAllHttpsURLConnection() {
    // Create a trust manager that does not validate certificate chains
    if (sslSocketFactory == null) {
        //            TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
        //                @Override
        //                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        //                    return null;
        //                }
        //
        //                @Override
        //                public void checkClientTrusted(X509Certificate[] certs,
        //                                               String authType) {
        //                }
        //
        //                @Override
        //                public void checkServerTrusted(X509Certificate[] certs,
        //                                               String authType) {
        //                }
        //            }
        //            };
        //            try {
        //                SSLContext sslContext = SSLContext.getInstance("TLS");
        //                sslContext.init(null, trustAllCerts, null);
        //                sslSocketFactory = sslContext.getSocketFactory();
        //            } catch (Throwable e) {
        //                LogUtils.e(e.getMessage(), e);
        //            }
    }

    if (sslSocketFactory != null) {
        HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
        HttpsURLConnection
                .setDefaultHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
    }
}

From source file:org.eurekastreams.server.service.actions.strategies.links.ConnectionFacade.java

/**
 * Get the connection.//from   w  ww.  ja v  a  2  s . co  m
 *
 * @param inUrl
 *            the url.
 * @param inAccountId
 *            account id of the user making the request.
 * @return the connection.
 * @throws MalformedURLException
 *             If the URL is invalid.
 */
protected HttpURLConnection getConnection(final String inUrl, final String inAccountId)
        throws MalformedURLException {
    HttpURLConnection connection = null;

    if (proxyHost.length() > 0) {
        System.setProperty("https.proxyHost", proxyHost);
        System.setProperty("https.proxyPort", proxyPort);
    }

    log.info("Using Proxy: " + proxyHost + ":" + proxyPort);

    URL url = getUrl(inUrl);
    try {
        // Some sites e.g. Google Images and Digg will not respond to an unrecognized User-Agent.

        if ("https".equals(url.getProtocol())) {
            log.trace("Using HTTPS");

            // Install the all-trusting trust manager
            try {
                SSLContext sc = SSLContext.getInstance("SSL");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                log.trace("Installed all-trusting trust manager.");
            } catch (Exception e) {
                log.error("Error setting SSL Context");
            }

            connection = (HttpsURLConnection) url.openConnection();

            ((HttpsURLConnection) connection).setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(final String hostname, final SSLSession session) {
                    log.trace("Accepting host name.");
                    return true;
                }
            });
        } else {
            URLConnection plainConnection = url.openConnection();

            if (plainConnection instanceof HttpURLConnection) {
                log.trace("Using HTTP");
                connection = (HttpURLConnection) plainConnection;
            } else {
                log.info("Closing non-HTTP connection.");
                return null;
            }
        }

        connection.setConnectTimeout(connectionTimeOut);

        // Decorate the connection.
        for (ConnectionFacadeDecorator decorator : decorators) {
            decorator.decorate(connection, inAccountId);
        }
    } catch (Exception e) {
        log.error("caught exception: ", e);
    }

    return connection;
}

From source file:edu.duke.cabig.c3pr.webservice.integration.SubjectMassCreator.java

private static void disableSSLVerification() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }//from  ww  w  .j av  a 2  s  .c o  m

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

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

    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        e.printStackTrace();
    }

    com.sun.net.ssl.HostnameVerifier hv = new com.sun.net.ssl.HostnameVerifier() {

        public boolean verify(String urlHostname, String certHostname) {
            return true;
        }
    };
    com.sun.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(hv);

    HostnameVerifier hv2 = new HostnameVerifier() {

        public boolean verify(String urlHostName, SSLSession session) {
            return true;
        }
    };
    HttpsURLConnection.setDefaultHostnameVerifier(hv2);

}

From source file:com.polyvi.xface.extension.filetransfer.XFileTransferExt.java

/**
 * JSON//from w  w  w  . j a v  a  2s. c om
 * @param appWorkSpace ?
 * @param source       ?URL
 * @param target       
 * @param args         ??
 * @param callbackCtx   nativejs
 * @return             JSON
 * @throws IOException
 * @throws JSONException
 */
private XExtensionResult download(String appWorkSpace, String source, String target, JSONArray args,
        XCallbackContext callbackCtx) throws JSONException {
    HttpURLConnection connection = null;
    try {
        boolean trustEveryone = args.optBoolean(2);
        String objectId = args.getString(3);
        if (target.contains(":")) {
            JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, connection);
            XLog.e(CLASS_NAME, ILLEGAL_ARGUMENT_EXCEPTION_NAME_CONTAINS_COLON);
            return new XExtensionResult(XExtensionResult.Status.ERROR, error);
        }
        XWhiteList whiteList = mWebContext.getApplication().getAppInfo().getWhiteList();
        if (null != whiteList && !whiteList.isUrlWhiteListed(source)) {
            XLog.e(CLASS_NAME, "Source URL is not in white list: '" + source + "'");
            JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection);
            return new XExtensionResult(XExtensionResult.Status.IO_EXCEPTION, error);
        }
        File file = new File(appWorkSpace, target);

        if (!XFileUtils.isFileAncestorOf(appWorkSpace, file.getCanonicalPath())) {
            JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, connection);
            XLog.e(CLASS_NAME, ILLEGAL_ARGUMENT_EXCEPTION_NOT_IN_ROOT_DIR);
            return new XExtensionResult(XExtensionResult.Status.ERROR, error);
        }
        file.getParentFile().mkdirs();

        // ?
        URL url = new URL(source);
        //TODO:??????
        connection = getURLConnection(url, trustEveryone);
        ;
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(CONNECTION_TIME_OUT_MILLISECONDS);
        setCookieProperty(connection, source);
        connection.connect();
        XLog.d(CLASS_NAME, "Download file:" + url);

        InputStream inputStream = connection.getInputStream();
        byte[] buffer = new byte[XConstant.BUFFER_LEN];
        int bytesRead = 0;
        long totalBytes = 0;

        FileTransferProgress progress = new FileTransferProgress();
        if (connection.getContentEncoding() == null) {
            progress.setLengthComputable(true);
            progress.setTotal(connection.getContentLength());
        }

        FileOutputStream outputStream = new FileOutputStream(file);
        while ((bytesRead = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, bytesRead);
            totalBytes += bytesRead;
            if (objectId != null) {
                //?js??object ID?
                progress.setLoaded(totalBytes);
                XExtensionResult progressResult = new XExtensionResult(XExtensionResult.Status.OK,
                        progress.toJSONObject());
                progressResult.setKeepCallback(true);
                callbackCtx.sendExtensionResult(progressResult);
            }
            synchronized (abortTriggered) {
                if (objectId != null && abortTriggered.contains(objectId)) {
                    abortTriggered.remove(objectId);
                    throw new AbortException(ABORT_EXCEPTION_DOWNLOAD_ABORTED);
                }
            }
        }
        outputStream.close();
        inputStream.close();
        XLog.d(CLASS_NAME, "Saved file: " + target);
        JSONObject entry = XFileUtils.getEntry(appWorkSpace, file);
        // 
        if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) {
            ((HttpsURLConnection) connection).setHostnameVerifier(mDefaultHostnameVerifier);
            HttpsURLConnection.setDefaultSSLSocketFactory(mDefaultSSLSocketFactory);
        }
        return new XExtensionResult(XExtensionResult.Status.OK, entry);
    } catch (AbortException e) {
        JSONObject error = createFileTransferError(ABORTED_ERR, source, target, connection);
        return new XExtensionResult(XExtensionResult.Status.ERROR, error);
    } catch (FileNotFoundException e) {
        JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, connection);
        XLog.e(CLASS_NAME, error.toString());
        return new XExtensionResult(XExtensionResult.Status.ERROR, error);
    } catch (MalformedURLException e) {
        JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, connection);
        XLog.e(CLASS_NAME, error.toString());
        return new XExtensionResult(XExtensionResult.Status.ERROR, error);
    } catch (Exception e) {
        JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection);
        XLog.e(CLASS_NAME, error.toString());
        return new XExtensionResult(XExtensionResult.Status.IO_EXCEPTION, error);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}