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:Main.java

/**
 * Trust every server - dont check for any certificate
 *//*from   w  ww  .  ja va  2 s.  c o m*/
static void trustAllHosts() {
    // 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[] {};
        }

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

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

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
                throws CertificateException {
            // TODO Auto-generated method stub

        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
                throws CertificateException {
            // TODO Auto-generated method stub

        }
    } };

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

From source file:test.integ.be.fedict.trust.util.SSLTrustManager.java

public static synchronized void initialize() {

    LOG.debug("initialize");
    if (null == socketFactory) {

        initSocketFactory();//from   w  ww .ja  v  a  2s  . c  om
        HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);
    } else {
        if (false == socketFactory.equals(HttpsURLConnection.getDefaultSSLSocketFactory()))
            throw new RuntimeException("wrong SSL socket factory installed");
    }
}

From source file:org.springframework.cloud.contract.wiremock.WireMockSpring.java

public static WireMockConfiguration options() {
    if (!initialized) {
        if (ClassUtils.isPresent("org.apache.http.conn.ssl.NoopHostnameVerifier", null)) {
            HttpsURLConnection.setDefaultHostnameVerifier(NoopHostnameVerifier.INSTANCE);
            try {
                HttpsURLConnection.setDefaultSSLSocketFactory(SSLContexts.custom()
                        .loadTrustMaterial(null, TrustSelfSignedStrategy.INSTANCE).build().getSocketFactory());
            } catch (Exception e) {
                Assert.fail("Cannot install custom socket factory: [" + e.getMessage() + "]");
            }/*ww  w. ja v a2 s . c  o  m*/
        }
        initialized = true;
    }
    WireMockConfiguration config = new WireMockConfiguration();
    config.httpServerFactory(new SpringBootHttpServerFactory());
    return config;
}

From source file:net.fenyo.gnetwatch.CommandLine.java

/**
 * General entry point./*from w  w w  . ja  va2s.c  o m*/
 * @param args command line arguments.
 * @return void.
 * @throws IOException io exception.
 * @throws FileNotFoundException file not found.
 */
public static void main(final String[] args)
        throws IOException, FileNotFoundException, InterruptedException, AlgorithmException {
    Config config = null;
    Synchro synchro = null;
    Background background = null;
    GUI gui = null;
    Main main = null;
    SNMPManager snmp_manager = null;
    CaptureManager capture_mgr = null;

    if (args.length > 0) {
        if (args.length == 4 && args[0].equals("import") && args[1].equals("source")) {
            importGenericSrc(args);
            return;
        }
        log.error("invalid arguments");
        System.exit(1);
    }

    // Get configuration properties
    config = new Config();

    // Set debug level
    // debug level 1: simulate hundreds of ping per second to check the DB and hibernate abilities to handle lots of events
    config.setDebugLevel(0);

    // Read general logging rules
    GenericTools.initLogEngine(config);
    log.info(config.getString("log_engine_initialized"));
    log.info(config.getString("begin"));

    /*
    final MessageBox dialog = new MessageBox(new Shell(new org.eclipse.swt.widgets.Display()),
        SWT.ICON_QUESTION | SWT.YES | SWT.NO);
    // traduire
    dialog.setText("GNetWatch startup");
    dialog.setMessage("Database Selection:\ndo you want to erase the current database content ?");
    dialog.open();
    */

    // Initialize Object-Relational mapping
    synchro = new Synchro(config);

    // Do not check SSL certificates
    SSLContext ssl_context = null;
    try {
        ssl_context = SSLContext.getInstance("SSL");
        ssl_context.init(null, new TrustManager[] { new NoCheckTrustManager() }, new SecureRandom());
    } catch (final NoSuchAlgorithmException ex) {
        log.error("Exception", ex);
    } catch (final KeyManagementException ex) {
        log.error("Exception", ex);
    }
    HttpsURLConnection.setDefaultSSLSocketFactory(ssl_context.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public final boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });

    // Initialize background processes management
    background = new Background(config);
    background.createBackgroundThread();

    // Initialize packet capture on every interface
    capture_mgr = new CaptureManager(config);

    // Initialize main processes management
    main = new Main(config, capture_mgr);

    // Build SNMP Manager
    snmp_manager = new SNMPManager();

    // Build GUI
    gui = new GUI(config, background, main, snmp_manager, synchro);
    main.setGUI(gui);
    capture_mgr.setGUI(gui);
    gui.waitForCreation();

    // Initial configuration
    gui.createFromXML(gui.getConfig().getProperty("initialobjects"));

    // Move the GUI to the top of the drawing order
    gui.showGUI();

    // merge events at startup
    background.informQueue("merge-1", gui);

    // Wait for the GUI to terminate
    gui.join();
    // The GUI is now closed
    log.info(config.getString("end"));

    // Stop every application thread
    config.setEnd();
    gui.end();
    background.end();
    capture_mgr.unRegisterAllListeners();

    // stop synchronizing
    synchro.end();
}

From source file:com.lolay.android.security.OpenX509TrustManager.java

public static void openTrust() {
    LolayLog.w(TAG, "openTrust", "THIS IS AN OPEN TRUST MANAGER FOR DEBUGGING ONLY!");
    try {//  ww  w. ja  va2 s .  com
        SSLContext context = SSLContext.getInstance("SSL");
        context.init(null, new TrustManager[] { new OpenX509TrustManager() }, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (Exception e) {
        LolayLog.e(TAG, "openTrust", "Could not open the trust", e);
    }
}

From source file:tk.egsf.ddns.JSON_helper.java

public static String getJsonUrl(String URL, String Auth) {
    String ret = "";

    String https_url = URL;
    URL url;//  w w w  . jav  a2  s  .c om
    try {

        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

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

            @Override
            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());

        url = new URL(https_url);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

        con.setRequestProperty("Authorization", Auth);

        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String input;
        while ((input = br.readLine()) != null) {
            ret += input;
        }
        br.close();

        System.out.println(ret);

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ConnectException e) {
        Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, "Exgotou o tempo de resposta");
        System.out.println("");
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyManagementException ex) {
        Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException e) {
        e.printStackTrace();

    }

    return ret;
}

From source file:org.wso2.developerstudio.eclipse.platform.ui.utils.SSLUtils.java

/**
 * Initialize the ssl context with the custom trust manager 
 *   1. setup https access to the created ssl context
 *   2. setup hostname verifier/*from  w w  w  . j ava 2s .  c om*/
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public static void init() throws NoSuchAlgorithmException, KeyManagementException {
    if (sslCtx == null) {
        sslCtx = SSLContext.getInstance("SSL");
        sslCtx.init(null, new TrustManager[] { getCustomTrustManager() }, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sslCtx.getSocketFactory());
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    }
}

From source file:org.glite.slcs.SLCSBaseClient.java

static protected void registerSSLTrustStore(SLCSClientConfiguration configuration) throws SLCSException {
    String truststorePath = getDefaultHttpClientTrustStoreFile(configuration);
    try {//  www  .j a  va2 s  . c o m
        ExtendedProtocolSocketFactory epsf = new ExtendedProtocolSocketFactory(truststorePath);
        Protocol https = new Protocol("https", (ProtocolSocketFactory) epsf, 443);
        Protocol.registerProtocol("https", https);
        // BUG FIX: register the truststore as default SSLSocketFactory
        // to download the metadata from https (QuoVadis CAs not in all default cacerts)
        LOG.info(
                "register ExtendedProtocolSocketFactory(" + truststorePath + ") as default SSL socket factory");
        SSLContext sc = epsf.getSSLContext();
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        LOG.error(e);
        throw new SLCSException("Failed to create ExtendedProtocolSocketFactory", e);
    }

}

From source file:cn.cuizuoli.appranking.http.client.TrustClientHttpRequestFactory.java

@Override
protected HttpURLConnection openConnection(URL url, Proxy proxy) throws IOException {
    if (StringUtils.equals(url.getProtocol(), "https")) {
        HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
        HttpsURLConnection urlConnection = (HttpsURLConnection) (proxy != null ? url.openConnection(proxy)
                : url.openConnection());
        urlConnection.setHostnameVerifier(DO_NOT_VERIFY);
        return urlConnection;
    } else {/*  ww  w. j ava2  s.c  o  m*/
        HttpURLConnection urlConnection = (HttpURLConnection) (proxy != null ? url.openConnection(proxy)
                : url.openConnection());
        return urlConnection;
    }
}

From source file:com.bytelightning.opensource.pokerface.HelloWorldScriptTest.java

@BeforeClass
public static void setUpBeforeClass() throws Exception {
    PrevSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
    PrevHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();

    proxy = new PokerFace();
    XMLConfiguration conf = new XMLConfiguration();
    conf.load(ProxySpecificTest.class.getResource("/HelloWorldTestConfig.xml"));
    proxy.config(conf);/*from   www . ja  va2  s . c om*/
    boolean started = proxy.start();
    Assert.assertTrue("Successful proxy start", started);

    SSLContext sc = SSLContext.getInstance("TLS");
    TrustManager[] trustAllCertificates = { new X509TrustAllManager() };
    sc.init(null, trustAllCertificates, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true; // Just allow them all.
        }
    });

}