Example usage for javax.net.ssl SSLContext setDefault

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

Introduction

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

Prototype

public static void setDefault(SSLContext context) 

Source Link

Document

Sets the default SSL context.

Usage

From source file:at.alladin.rmbt.client.RMBTClientRunner.java

/**
 * @param args//ww  w.j  av a  2  s.c  o m
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public static void main(final String[] args)
        throws IOException, InterruptedException, KeyManagementException, NoSuchAlgorithmException {
    final OptionParser parser = new OptionParser() {
        {
            acceptsAll(Arrays.asList("?", "help"), "show help");

            acceptsAll(Arrays.asList("h", "host"), "RMBT server IP or hostname (required)").withRequiredArg()
                    .ofType(String.class);

            acceptsAll(Arrays.asList("p", "port"), "RMBT server port (required)").withRequiredArg()
                    .ofType(Integer.class);

            acceptsAll(Arrays.asList("s", "ssl"), "use SSL/TLS");

            acceptsAll(Arrays.asList("ssl-no-verify"), "turn off SSL/TLS certificate validation");

            acceptsAll(Arrays.asList("t", "threads"), "number of threads (required when dev-mode)")
                    .withRequiredArg().ofType(Integer.class);

            acceptsAll(Arrays.asList("d", "duration"), "test duration in seconds (required when dev-mode)")
                    .withRequiredArg().ofType(Integer.class);

            acceptsAll(Arrays.asList("n", "ndt"), "run NDT after RMBT");

            acceptsAll(Arrays.asList("ndt-host"), "NDT host to use").withRequiredArg().ofType(String.class);

        }
    };

    System.out.println(String.format("=============== RMBTClient %s ===============",
            RevisionHelper.getVerboseRevision()));

    OptionSet options;
    try {
        options = parser.parse(args);
    } catch (final OptionException e) {
        System.out.println(
                String.format("error while parsing command line options: %s", e.getLocalizedMessage()));
        System.exit(1);
        return;
    }

    final String[] requiredArgs = { "h", "p" };

    if (options.has("ssl-no-verify"))
        SSLContext.setDefault(RMBTClient.getSSLContext(null, null));
    else
        SSLContext.setDefault(RMBTClient.getSSLContext("at/alladin/rmbt/crt/ca.pem",
                "at/alladin/rmbt/crt/controlserver.pem"));

    boolean reqArgMissing = false;
    if (!options.has("?"))
        for (final String arg : requiredArgs)
            if (!options.has(arg)) {
                reqArgMissing = true;
                System.out.println(String.format("ERROR: required argument '%s' is missing", arg));
            }
    if (options.has("?") || reqArgMissing) {
        System.out.println();
        parser.printHelpOn(System.out);
        System.exit(1);
        return;
    }

    final RMBTClient client;

    final String host = (String) options.valueOf("h");
    final int port = (Integer) options.valueOf("p");
    final boolean encryption = options.has("s") ? true : false;

    final ArrayList<String> geoInfo = null;

    final String uuid = "1cc2d6bb-2f07-4cb8-8fd6-fb5ffcf10cb0";

    final JSONObject additionalValues = new JSONObject();
    try {
        additionalValues.put("ndt", options.has("n"));
        additionalValues.put("plattform", "CLI");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    int numThreads = 0;
    int duration = 0;
    if (options.has("t"))
        numThreads = (Integer) options.valueOf("t");
    if (options.has("d"))
        duration = (Integer) options.valueOf("d");

    int numPings = 10;

    RMBTTestParameter overrideParams = null;
    if (numThreads > 0 || duration > 0)
        overrideParams = new RMBTTestParameter(null, 0, false, duration, numThreads, numPings);

    client = RMBTClient.getInstance(host, null, port, encryption, geoInfo, uuid, "DESKTOP",
            Config.RMBT_CLIENT_NAME, Config.RMBT_VERSION_NUMBER, overrideParams, null);

    if (client != null) {
        final TestResult result = client.runTest();

        if (result != null) {
            final JSONObject jsonResult = new JSONObject();
            try {
                jsonResult.put("network_type", "97");
                jsonResult.put("plattform", "CLI");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            client.sendResult(jsonResult);
        }

        client.shutdown();

        try {
            System.out.print("Starting QoS Test... ");
            TestSettings nnTestSettings = new TestSettings(client.getControlConnection().getStartTimeNs());
            QualityOfServiceTest nnTest = new QualityOfServiceTest(client, nnTestSettings);
            QoSResultCollector nnResult = nnTest.call();
            System.out.println("finished.");
            if (nnResult != null && nnTest.getStatus().equals(QoSTestEnum.QOS_FINISHED)) {
                System.out.print("Sending QoS results... ");
                client.sendQoSResult(nnResult);
                System.out.println("finished");
            } else {
                System.out.println("Error during QoS test.");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (client.getStatus() != TestStatus.END)
            System.out.println("ERROR: " + client.getErrorMsg());
        else {
            if (options.has("n")) {
                System.out.println("\n\nStarting NDT...");

                String ndtHost = null;
                if (options.has("ndt-host"))
                    ndtHost = (String) options.valueOf("ndt-host");

                final NDTRunner ndtRunner = new NDTRunner(ndtHost);
                ndtRunner.runNDT(NdtTests.NETWORK_WIRED, ndtRunner.new UiServices() {
                    @Override
                    public void appendString(String str, int viewId) {
                        super.appendString(str, viewId);
                        //                            if (viewId == MAIN_VIEW)
                        System.out.println(str);
                    }

                    @Override
                    public void sendResults() {
                        System.out.println("sending NDT results...");
                        client.getControlConnection().sendNDTResult(this, null);
                    }
                });

                System.out.println("NDT finished.");
            }
        }
    }

}

From source file:eu.eco2clouds.api.bonfire.client.rest.RestClient.java

private static void enableSSLUnsecureTrustStore() {
    try {//from   w  ww.  j a  va 2  s .  c  o  m
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        SSLContext.setDefault(ctx);
    } catch (NoSuchAlgorithmException exception) {
        System.out.println("ERROR TRYING TO DISSABLE JAVA SSL SECURITY");
        System.out.println("NO TLS ALGORITHM EXCEPTION");
        System.out.println("EXCEPTION" + exception.getMessage());
    } catch (KeyManagementException exception) {
        System.out.println("ERROR TRYING TO DISSABLE JAVA SSL SECURITY");
        System.out.println("KEY MANAGEMENT CREATION EXCEPTION");
        System.out.println("EXCEPTION" + exception.getMessage());
    }
}

From source file:org.orcid.examples.jopmts.impl.SSLConfig.java

public static void trustSelfSignedSSL() {
    try {//from w w  w.  j av a2  s.c  o  m
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {

            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLContext.setDefault(ctx);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:org.wso2.developerstudio.eclipse.esb.project.connector.store.ConnectorStore.java

/**
 * This will connect to connector store using provided URL and retrieve information for available connectors in the
 * requested page and return a ConnectorData object which can be used to fetch relevant information for a particular
 * connector./*  w  w w  . j a v a 2  s .  c  om*/
 * 
 * @param url
 * @return ConnectorData
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 * @throws IOException
 * @throws HttpException
 */
public static List<Connector> getConnectorInfo(String url, int page)
        throws NoSuchAlgorithmException, KeyManagementException, HttpException, IOException {
    HttpClient httpclient = new HttpClient();
    httpclient.getParams().setIntParameter(HTTP_SOCKET_TIMEOUT, TIMEOUT);
    SSLContext ctx;
    ctx = SSLContext.getInstance("TLS");
    ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
    SSLContext.setDefault(ctx);
    GetMethod get = new GetMethod(url + ASSETS + "?page=" + page);
    int statusCode = 0;
    statusCode = httpclient.executeMethod(get);
    if (statusCode == 200) {
        Reader reader = new InputStreamReader(get.getResponseBodyAsStream());
        Type collectionType = new TypeToken<List<Connector>>() {
        }.getType();
        List<Connector> lcs = (List<Connector>) new Gson().fromJson(reader, collectionType);
        return lcs;
    } else {
        return null;
    }
}

From source file:ezbake.crypto.utils.EzSSL.java

/**
 *
 * @param configuration/*from ww w.  j ava2  s. c  o m*/
 * @param service
 * @throws CertificateException
 * @throws UnrecoverableKeyException
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws KeyManagementException
 * @throws KeyStoreException
 */
public static void setDefaultSSLContext(final Properties configuration, String service)
        throws IOException, SSLContextException {
    synchronized (sslDefaultContextIsSet) {
        if (!sslDefaultContextIsSet) {
            SSLContext.setDefault(getSSLContext(configuration, service));
            sslDefaultContextIsSet = true;
        }
    }
}

From source file:com.voa.weixin.utils.HttpUtils.java

/**
 * httpspost?/*  w w w  . j a  va  2 s .c  om*/
 * 
 * @param url
 * @param param
 * @return
 * @throws Exception
 */
private static String doHttps(String url, String param, String method) throws Exception {
    HttpsURLConnection conn = null;
    OutputStream out = null;
    String rsp = null;
    byte[] content = param.getBytes("utf-8");
    try {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
            SSLContext.setDefault(ctx);

            conn = getConnection(new URL(url), method, ctype);
            conn.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            conn.setConnectTimeout(60000);
            conn.setReadTimeout(60000);
        } catch (Exception e) {
            throw e;
        }
        try {
            out = conn.getOutputStream();
            if (StringUtils.isNotBlank(param))
                out.write(content);
            rsp = getResponseAsString(conn);
        } catch (IOException e) {
            throw e;
        }

    } finally {
        if (out != null) {
            out.close();
        }
        if (conn != null) {
            conn.disconnect();
        }
    }

    return rsp;
}

From source file:org.wso2.carbon.identity.authenticator.PushAuthentication.java

/**
 * Set the client certificate to Default SSL Context
 *
 * @param certificateFile File containing certificate (PKCS12 format)
 * @param certPassword    Password of certificate
 * @throws Exception//from ww w  .ja v  a  2s.c  om
 */
public static SSLContext setHttpsClientCert(String certificateFile, String certPassword) throws Exception {
    if (certificateFile == null || !new File(certificateFile).exists()) {
        return null;
    }
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(InweboConstants.SUNFORMAT);
    KeyStore keyStore = KeyStore.getInstance(InweboConstants.PKCSFORMAT);

    InputStream keyInput = new FileInputStream(certificateFile);
    keyStore.load(keyInput, certPassword.toCharArray());

    keyInput.close();
    keyManagerFactory.init(keyStore, certPassword.toCharArray());

    SSLContext context = SSLContext.getInstance(InweboConstants.TLSFORMAT);
    context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
    SSLContext.setDefault(context);
    return context;
}

From source file:org.opennms.core.camel.CustomHttpClientConfigurer.java

@Override
public void configureHttpClient(final HttpClient client) {
    try {/* ww w . j ava  2s  .  c o  m*/
        final SSLContext ctx = SSLContext.getInstance("SSL");
        ctx.init(EMPTY_KEYMANAGER_ARRAY, new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        SSLContext.setDefault(ctx);

        final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(getUsername(),
                getPassword());
        client.getState().setCredentials(AuthScope.ANY, credentials);
        client.getParams().setAuthenticationPreemptive(true);
        LOG.debug("Configuring HTTP client with modified trust manager, username={}, password=xxxxxxxx",
                getUsername());
    } catch (final Exception e) {
        throw new CustomConfigurerException(e);
    }
}

From source file:comsat.sample.tomcat.SampleTomcatTwoConnectorsApplicationTests.java

@BeforeClass
public static void setUp() {
    try {// ww  w  .j  ava 2  s . c o m
        // setup ssl context to ignore certificate errors
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
                    throws java.security.cert.CertificateException {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
                    throws java.security.cert.CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLContext.setDefault(ctx);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:org.apache.camel.component.solr.JettySolrFactory.java

private static void installAllTrustingClientSsl()
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());

    // // Create a trust manager that does not validate certificate chains
    final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override/*from  w  w w.  j  a va2  s  .  co m*/
        public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
        }

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

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    } };
    final SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
    SSLContext.setDefault(sslContext);

    // // Install the all-trusting trust manager
    // final SSLContext sslContext = SSLContext.getInstance( "SSL" );
    // sslContext.init( null, trustAllCerts, new
    // java.security.SecureRandom() );
    // // Create an ssl socket factory with our all-trusting manager
    // final SSLSocketFactory sslSocketFactory =
    // sslContext.getSocketFactory();
    // HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
}