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:com.maxl.java.aips2sqlite.AllDown.java

private void setNoValidation() throws Exception {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override/*from   w ww.j  av  a2 s .c o m*/
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

        @Override
        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            // Do nothing
        }
    } };

    // 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() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

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

From source file:edu.harvard.hms.dbmi.bd2k.irct.ri.i2b2.I2B2XMLResourceImplementation.java

private HttpClientBuilder ignoreCertificate() throws NoSuchAlgorithmException, KeyManagementException {
    System.setProperty("jsse.enableSNIExtension", "false");

    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }//www.j  a  v a 2 s .c  om

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

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

    SSLContext sslContext;

    sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
            NoopHostnameVerifier.INSTANCE);

    Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslsf).build();

    HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);

    return HttpClients.custom().setConnectionManager(cm);
}

From source file:com.zoffcc.applications.aagtl.HTMLDownloader.java

private void trust_Every_ssl_cert() {
    // NEVER enable this on a production release!!!!!!!!!!
    try {//ww  w .j  a  v a2s  .  c om
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                Log.d("aagtl", "DANGER !!! trusted hostname=" + hostname + " DANGER !!!");
                // return true -> mean we trust this cert !! DANGER !! DANGER !!
                return true;
            }
        });
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, new X509TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                Log.d("aagtl", "DANGER !!! 222222222");
                return new java.security.cert.X509Certificate[0];
            }

            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
                    throws java.security.cert.CertificateException {
                Log.d("aagtl", "DANGER !!! 333333333");
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
                    throws java.security.cert.CertificateException {
                Log.d("aagtl", "DANGER !!! 444444444444");
            }
        } }, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
    } catch (Exception e) {
        e.printStackTrace();
    }
    // NEVER enable this on a production release!!!!!!!!!!
}

From source file:com.photon.phresco.framework.impl.SCMManagerImpl.java

void additionalAuthentication(String passPhrase) {
    final String passwordPhrase = passPhrase;
    JschConfigSessionFactory sessionFactory = new JschConfigSessionFactory() {
        @Override//from  w  w w.  java 2  s.c o  m
        protected void configure(OpenSshConfig.Host hc, Session session) {
            CredentialsProvider provider = new CredentialsProvider() {
                @Override
                public boolean isInteractive() {
                    return false;
                }

                @Override
                public boolean supports(CredentialItem... items) {
                    return true;
                }

                @Override
                public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem {
                    for (CredentialItem item : items) {
                        if (item instanceof CredentialItem.StringType) {
                            ((CredentialItem.StringType) item).setValue(passwordPhrase);
                        }
                    }
                    return true;
                }
            };
            UserInfo userInfo = new CredentialsProviderUserInfo(session, provider);
            // Unknown host key for ssh
            java.util.Properties config = new java.util.Properties();
            config.put(STRICT_HOST_KEY_CHECKING, NO);
            session.setConfig(config);

            session.setUserInfo(userInfo);
        }
    };

    SshSessionFactory.setInstance(sessionFactory);

    /*
     * Enable clone of https url by trusting those urls
     */
    // 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(java.security.cert.X509Certificate[] certs, String authType) {
        }

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

    final String https_proxy = System.getenv(HTTPS_PROXY);
    final String http_proxy = System.getenv(HTTP_PROXY);

    ProxySelector.setDefault(new ProxySelector() {
        final ProxySelector delegate = ProxySelector.getDefault();

        @Override
        public List<Proxy> select(URI uri) {
            // Filter the URIs to be proxied

            if (uri.toString().contains(HTTPS) && StringUtils.isNotEmpty(http_proxy) && http_proxy != null) {
                try {
                    URI httpsUri = new URI(https_proxy);
                    String host = httpsUri.getHost();
                    int port = httpsUri.getPort();
                    return Arrays.asList(new Proxy(Type.HTTP, InetSocketAddress.createUnresolved(host, port)));
                } catch (URISyntaxException e) {
                    if (debugEnabled) {
                        S_LOGGER.debug("Url exception caught in https block of additionalAuthentication()");
                    }
                }
            }

            if (uri.toString().contains(HTTP) && StringUtils.isNotEmpty(http_proxy) && http_proxy != null) {
                try {
                    URI httpUri = new URI(http_proxy);
                    String host = httpUri.getHost();
                    int port = httpUri.getPort();
                    return Arrays.asList(new Proxy(Type.HTTP, InetSocketAddress.createUnresolved(host, port)));
                } catch (URISyntaxException e) {
                    if (debugEnabled) {
                        S_LOGGER.debug("Url exception caught in http block of additionalAuthentication()");
                    }
                }
            }

            // revert to the default behaviour
            return delegate == null ? Arrays.asList(Proxy.NO_PROXY) : delegate.select(uri);
        }

        @Override
        public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
            if (uri == null || sa == null || ioe == null) {
                throw new IllegalArgumentException("Arguments can't be null.");
            }
        }
    });

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance(SSL);
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (GeneralSecurityException e) {
        e.getLocalizedMessage();
    }
}

From source file:com.rapid.server.RapidServletContextListener.java

@Override
public void contextInitialized(ServletContextEvent event) {

    // request windows line breaks to make the files easier to edit (in particular the marshalled .xml files)
    System.setProperty("line.separator", "\r\n");

    // get a reference to the servlet context
    ServletContext servletContext = event.getServletContext();

    // set up logging
    try {// ww  w. j a  v a2  s . c o m

        // set the log path
        System.setProperty("logPath", servletContext.getRealPath("/") + "/WEB-INF/logs/Rapid.log");

        // get a logger
        _logger = Logger.getLogger(RapidHttpServlet.class);

        // set the logger and store in servletConext
        servletContext.setAttribute("logger", _logger);

        // log!
        _logger.info("Logger created");

    } catch (Exception e) {

        System.err.println("Error initilising logging : " + e.getMessage());

        e.printStackTrace();
    }

    try {

        // we're looking for a password and salt for the encryption
        char[] password = null;
        byte[] salt = null;
        // look for the rapid.txt file with the saved password and salt
        File secretsFile = new File(servletContext.getRealPath("/") + "/WEB-INF/security/encryption.txt");
        // if it exists
        if (secretsFile.exists()) {
            // get a file reader
            BufferedReader br = new BufferedReader(new FileReader(secretsFile));
            // read the first line
            String className = br.readLine();
            // read the next line
            String s = br.readLine();
            // close the reader
            br.close();

            try {
                // get the class 
                Class classClass = Class.forName(className);
                // get the interfaces
                Class[] classInterfaces = classClass.getInterfaces();
                // assume it doesn't have the interface we want
                boolean gotInterface = false;
                // check we got some
                if (classInterfaces != null) {
                    for (Class classInterface : classInterfaces) {
                        if (com.rapid.utils.Encryption.EncryptionProvider.class.equals(classInterface)) {
                            gotInterface = true;
                            break;
                        }
                    }
                }
                // check the class extends com.rapid.Action
                if (gotInterface) {
                    // get the constructors
                    Constructor[] classConstructors = classClass.getDeclaredConstructors();
                    // check we got some
                    if (classConstructors != null) {
                        // assume we don't get the parameterless one we need
                        Constructor constructor = null;
                        // loop them
                        for (Constructor classConstructor : classConstructors) {
                            // check parameters
                            if (classConstructor.getParameterTypes().length == 0) {
                                constructor = classConstructor;
                                break;
                            }
                        }
                        // check we got what we want
                        if (constructor == null) {
                            _logger.error(
                                    "Encyption not initialised : Class in security.txt class must have a parameterless constructor");
                        } else {
                            // construct the class
                            EncryptionProvider encryptionProvider = (EncryptionProvider) constructor
                                    .newInstance();
                            // get the password
                            password = encryptionProvider.getPassword();
                            // get the salt
                            salt = encryptionProvider.getSalt();
                            // log
                            _logger.info("Encyption initialised");
                        }
                    }
                } else {
                    _logger.error(
                            "Encyption not initialised : Class in security.txt class must extend com.rapid.utils.Encryption.EncryptionProvider");
                }
            } catch (Exception ex) {
                _logger.error("Encyption not initialised : " + ex.getMessage(), ex);
            }
        } else {
            _logger.info("Encyption not initialised");
        }

        // create the encypted xml adapter (if the file above is not found there no encryption will occur)
        RapidHttpServlet.setEncryptedXmlAdapter(new EncryptedXmlAdapter(password, salt));

        // initialise the schema factory (we'll reuse it in the various loaders)
        _schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        // initialise the list of classes we're going to want in the JAXB context (the loaders will start adding to it)
        _jaxbClasses = new ArrayList<Class>();

        _logger.info("Loading database drivers");

        // load the database drivers first
        loadDatabaseDrivers(servletContext);

        _logger.info("Loading connection adapters");

        // load the connection adapters 
        loadConnectionAdapters(servletContext);

        _logger.info("Loading security adapters");

        // load the security adapters 
        loadSecurityAdapters(servletContext);

        _logger.info("Loading form adapters");

        // load the form adapters
        loadFormAdapters(servletContext);

        _logger.info("Loading actions");

        // load the actions 
        loadActions(servletContext);

        _logger.info("Loading templates");

        // load templates
        loadThemes(servletContext);

        _logger.info("Loading controls");

        // load the controls 
        loadControls(servletContext);

        // add some classes manually
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.NameRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MinOccursRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MaxOccursRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MaxLengthRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MinLengthRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.EnumerationRestriction.class);
        _jaxbClasses.add(com.rapid.soa.Webservice.class);
        _jaxbClasses.add(com.rapid.soa.SQLWebservice.class);
        _jaxbClasses.add(com.rapid.soa.JavaWebservice.class);
        _jaxbClasses.add(com.rapid.core.Validation.class);
        _jaxbClasses.add(com.rapid.core.Action.class);
        _jaxbClasses.add(com.rapid.core.Event.class);
        _jaxbClasses.add(com.rapid.core.Style.class);
        _jaxbClasses.add(com.rapid.core.Control.class);
        _jaxbClasses.add(com.rapid.core.Page.class);
        _jaxbClasses.add(com.rapid.core.Application.class);
        _jaxbClasses.add(com.rapid.core.Device.class);
        _jaxbClasses.add(com.rapid.core.Device.Devices.class);

        // convert arraylist to array
        Class[] classes = _jaxbClasses.toArray(new Class[_jaxbClasses.size()]);
        // re-init the JAXB context to include our injectable classes               
        JAXBContext jaxbContext = JAXBContext.newInstance(classes);

        // this logs the JAXB classes
        _logger.trace("JAXB  content : " + jaxbContext.toString());

        // store the jaxb context in RapidHttpServlet
        RapidHttpServlet.setJAXBContext(jaxbContext);

        // load the devices
        Devices.load(servletContext);

        // load the applications!
        loadApplications(servletContext);

        // add some useful global objects 
        servletContext.setAttribute("xmlDateFormatter", new SimpleDateFormat("yyyy-MM-dd"));
        servletContext.setAttribute("xmlDateTimeFormatter", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"));

        String localDateFormat = servletContext.getInitParameter("localDateFormat");
        if (localDateFormat == null)
            localDateFormat = "dd/MM/yyyy";
        servletContext.setAttribute("localDateFormatter", new SimpleDateFormat(localDateFormat));

        String localDateTimeFormat = servletContext.getInitParameter("localDateTimeFormat");
        if (localDateTimeFormat == null)
            localDateTimeFormat = "dd/MM/yyyy HH:mm a";
        servletContext.setAttribute("localDateTimeFormatter", new SimpleDateFormat(localDateTimeFormat));

        boolean actionCache = Boolean.parseBoolean(servletContext.getInitParameter("actionCache"));
        if (actionCache)
            servletContext.setAttribute("actionCache", new ActionCache(servletContext));

        int pageAgeCheckInterval = MONITOR_CHECK_INTERVAL;
        try {
            String pageAgeCheckIntervalString = servletContext.getInitParameter("pageAgeCheckInterval");
            if (pageAgeCheckIntervalString != null)
                pageAgeCheckInterval = Integer.parseInt(pageAgeCheckIntervalString);
        } catch (Exception ex) {
            _logger.error("pageAgeCheckInterval is not an integer");
        }

        int pageMaxAge = MONITOR_MAX_AGE;
        try {
            String pageMaxAgeString = servletContext.getInitParameter("pageMaxAge");
            if (pageMaxAgeString != null)
                pageMaxAge = Integer.parseInt(pageMaxAgeString);
        } catch (Exception ex) {
            _logger.error("pageMaxAge is not an integer");
        }

        // start the monitor
        _monitor = new Monitor(servletContext, pageAgeCheckInterval, pageMaxAge);
        _monitor.start();

        // allow calling to https without checking certs (for now)
        SSLContext sc = SSLContext.getInstance("SSL");
        TrustManager[] trustAllCerts = new TrustManager[] { new Https.TrustAllCerts() };
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    } catch (Exception ex) {

        _logger.error("Error loading applications : " + ex.getMessage());

        ex.printStackTrace();
    }

}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl.java

@Override
public void initializeSSL() throws CMException {
    /*//from  w w w  .j  a va 2  s  . com
     * We use the lazy initialization of Credential Manager from inside the
     * Taverna's SSLSocketFactory (i.e. KeyManager's and TrustManager's
     * init() methods) when it is actually needed so do not initialize it
     * here. These init() methods will not be called unledd a SSL connection
     * is attempted somewhere from Taverna and it is inside them that we
     * actually call the initialize() method on Credential Manager (and not
     * from the Credential Manager's constructor - hence lazy).
     * 
     * Create Taverna's SSLSocketFactory and set the SSL socket factory from
     * HttpsURLConnectionS to use it
     */
    if (tavernaSSLSocketFactory == null)
        HttpsURLConnection.setDefaultSSLSocketFactory(createSSLSocketFactory());
}

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

/**
 * Checks if is connection alive./* ww  w. ja  v  a  2s.c  om*/
 *
 * @param protocol the protocol
 * @param host the host
 * @param port the port
 * @return true, if is connection alive
 */
public boolean isConnectionAlive(String protocol, String host, int port) {
    boolean isAlive = true;
    try {
        URL url = new URL(protocol, host, port, "");
        URLConnection connection = url.openConnection();
        if (protocol.equalsIgnoreCase("http")) {
            HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
            httpConnection.connect();
        } else {
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

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

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

            SSLContext sc = SSLContext.getInstance(SSL);
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
            https.connect();

        }

    } catch (Exception e) {
        isAlive = false;
    }

    return isAlive;
}

From source file:com.photon.phresco.framework.commons.FrameworkUtil.java

public static int getHttpsResponse(String url) throws PhrescoException {
    URL httpsUrl;//from w  w  w.ja v a  2s  . c om
    try {
        SSLContext ssl_ctx = SSLContext.getInstance("SSL");
        TrustManager[] trust_mgr = get_trust_mgr();
        ssl_ctx.init(null, trust_mgr, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(ssl_ctx.getSocketFactory());
        httpsUrl = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) httpsUrl.openConnection();
        con.setHostnameVerifier(new HostnameVerifier() {
            // Guard against "bad hostname" errors during handshake.   
            public boolean verify(String host, SSLSession sess) {
                return true;
            }
        });
        return con.getResponseCode();
    } catch (MalformedURLException e) {
        throw new PhrescoException(e);
    } catch (IOException e) {
        throw new PhrescoException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new PhrescoException(e);
    } catch (KeyManagementException e) {
        throw new PhrescoException(e);
    }
}

From source file:org.openymsg.network.Session.java

private void trustEveryone() {
    try {/*w  w w.j  ava 2s .c  o  m*/
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(final String hostname, final SSLSession session) {
                return true;
            }
        });
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, new X509TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(final X509Certificate[] chain, final String authType)
                    throws CertificateException {
            }

            @Override
            public void checkServerTrusted(final X509Certificate[] chain, final String authType)
                    throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        } }, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
    } catch (Exception e) { // should never happen
        e.printStackTrace();
    }
}

From source file:carnero.cgeo.original.libs.Base.java

public static void trustAllHosts() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

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

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

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

    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        Log.e(Settings.tag, "cgBase.trustAllHosts: " + e.toString());
    }
}