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:hudson.plugins.sitemonitor.SiteMonitorRecorder.java

private HttpURLConnection getConnection(String urlString)
        throws MalformedURLException, IOException, NoSuchAlgorithmException, KeyManagementException {

    if (urlString.startsWith("https://")) {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        SSLContext.setDefault(ctx);

        HttpsURLConnection connection = (HttpsURLConnection) ProxyConfiguration.open(new URL(urlString));
        connection.setHostnameVerifier(new HostnameVerifier() {

            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }/*from ww  w. j  ava2  s  . c  om*/
        });
        return connection;

    } else if (urlString.contains("@")) {

        URL passedURL = new URL(urlString);
        String creds = urlString.substring(urlString.indexOf("//") + 2, urlString.indexOf("@"));
        String userName = creds.substring(0, creds.indexOf(":"));
        String passWord = creds.substring(creds.indexOf(":") + 1, creds.length());
        String userPassword = userName + ":" + passWord;
        // TODO cambiar implementacin de Base64
        String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes());
        // TODO soporta proxy?
        HttpURLConnection connection = (HttpURLConnection) passedURL.openConnection();
        connection.setRequestProperty("Authorization", "Basic " + encoding);
        return connection;

    } else {
        return (HttpURLConnection) ProxyConfiguration.open(new URL(urlString));
    }
}

From source file:org.apache.solr.cloud.TestMiniSolrCloudClusterSSL.java

@After
public void after() {
    HttpClientUtil.resetHttpClientBuilder(); // also resets SchemaRegistryProvider
    System.clearProperty(ZkStateReader.URL_SCHEME);
    SSLContext.setDefault(DEFAULT_SSL_CONTEXT);
}

From source file:io.coala.capability.online.FluentHCOnlineCapability.java

@Override
public void initialize() throws NoSuchAlgorithmException, KeyManagementException {
    synchronized (FluentHCOnlineCapability.class) {
        if (setup)
            return;

        if (!getBinder().inject(ConfiguringCapability.class).getProperty(TRUST_MANAGER_DISABLED_PROPERTY_KEY)
                .getBoolean(TRUST_MANAGER_DISABLED_PROPERTY_DEFAULT))
            return;

        final SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DummyTrustManager() }, new SecureRandom());
        SSLContext.setDefault(ctx);
        setup = true;/* w w  w  . j  ava  2  s  . c  o  m*/
    }
}

From source file:de.codecentric.jira.jenkins.plugin.servlet.OverviewServlet.java

public OverviewServlet(TemplateRenderer templateRenderer, JiraAuthenticationContext authenticationContext,
        PluginSettingsFactory settingsFactory, ApplicationProperties applicationProperties) {
    this.templateRenderer = templateRenderer;
    this.authenticationContext = authenticationContext;
    this.serverList = new ServerList(settingsFactory);
    this.client = new HttpClient(new MultiThreadedHttpConnectionManager());

    //test if jiraversion < 4.3
    IsPriorToJiraVersion isPrior = new IsPriorToJiraVersion(applicationProperties);
    isPrior.setmaxMajorVersion(4);/*from  w ww .  j av a  2  s.c o  m*/
    isPrior.setmaxMinorVersion(3);
    this.old = isPrior.shouldDisplay(null);

    client.getParams().setAuthenticationPreemptive(true);

    //set SSLContext to accept all certificates
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        SSLContext.setDefault(ctx);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    SecureProtocolSocketFactory secureProtocolSocketFactory = new SSLProtocolSocketFactory();

    Protocol.registerProtocol("https",
            new Protocol("https", (ProtocolSocketFactory) secureProtocolSocketFactory, 443));
}

From source file:de.codecentric.jira.jenkins.plugin.servlet.RecentBuildsServlet.java

public RecentBuildsServlet(TemplateRenderer templateRenderer, JiraAuthenticationContext authenticationContext,
        PluginSettingsFactory settingsFactory, ApplicationProperties applicationProperties) {
    this.templateRenderer = templateRenderer;
    this.authenticationContext = authenticationContext;
    this.client = new HttpClient(new MultiThreadedHttpConnectionManager());
    this.serverList = new ServerList(settingsFactory);

    //test if jiraversion < 4.3
    IsPriorToJiraVersion isPrior = new IsPriorToJiraVersion(applicationProperties);
    isPrior.setmaxMajorVersion(4);//from w w w.j  a v  a  2 s  . c o m
    isPrior.setmaxMinorVersion(3);
    this.old = isPrior.shouldDisplay(null);

    client.getParams().setAuthenticationPreemptive(true);

    //set SSLContext to accept all certificates
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        SSLContext.setDefault(ctx);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    SecureProtocolSocketFactory secureProtocolSocketFactory = new SSLProtocolSocketFactory();

    Protocol.registerProtocol("https",
            new Protocol("https", (ProtocolSocketFactory) secureProtocolSocketFactory, 443));

}

From source file:org.wso2.carbon.apimgt.integration.client.util.Utils.java

private static SSLSocketFactory initSSLConnection(KeyStore keyStore, String keyStorePassword,
        KeyStore trustStore)//  w ww  .j a v a 2s. c  o m
        throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, KeyManagementException {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE);
    keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE);
    trustManagerFactory.init(trustStore);

    // Create and initialize SSLContext for HTTPS communication
    SSLContext sslContext = SSLContext.getInstance(SSLV3);
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    SSLContext.setDefault(sslContext);
    return sslContext.getSocketFactory();
}

From source file:org.wso2.iot.firealarm.access.api.AccessTokenClient.java

public AccessTokenInfo getAccessToken(String username, String password, String appInstanceId)
        throws AccessTokenException {
    SSLContext ctx;//from  w  w w  . j ava 2  s .c o  m
    String response = "";
    try {
        ctx = SSLContext.getInstance("TLS");

        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        SSLContext.setDefault(ctx);

        URL url = new URL(tokenURL);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
        //System.out.println(conn.getResponseCode());
        conn.disconnect();

        HttpClient httpClient = new HttpClient();

        PostMethod postMethod = new PostMethod(tokenURL);
        postMethod.addParameter(new NameValuePair("grant_type", grantType));
        postMethod.addParameter(new NameValuePair("username", username));
        postMethod.addParameter(new NameValuePair("password", password));
        postMethod.addParameter(new NameValuePair("scope", scope + appInstanceId));

        postMethod.addRequestHeader("Authorization", "Basic " + appToken);
        postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        httpClient.executeMethod(postMethod);

        response = postMethod.getResponseBodyAsString();
        log.info(response);
        JSONObject jsonObject = new JSONObject(response);

        AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
        accessTokenInfo.setAccess_token(jsonObject.getString("access_token"));
        accessTokenInfo.setRefresh_token(jsonObject.getString("refresh_token"));
        accessTokenInfo.setExpires_in(jsonObject.getInt("expires_in"));
        accessTokenInfo.setToken_type(jsonObject.getString("token_type"));

        return accessTokenInfo;

    } catch (NoSuchAlgorithmException | KeyManagementException | IOException | JSONException e) {
        log.error(e.getMessage());
        throw new AccessTokenException("Configuration Error for Access Token Generation");
    } catch (NullPointerException e) {

        return null;
    }

}

From source file:com.qpark.eip.core.spring.security.https.HttpsRequester.java

@PostConstruct
public void init() throws Exception {
    if (this.trustManager == null) {
        // HTTP AUTH
        if (this.httpAuthUser != null && this.httpAuthUser.length() > 0) {
            this.httpAuthBase64 = new String(Base64.encode(new StringBuffer(256).append(this.httpAuthUser)
                    .append(":").append(this.httpAuthPwd == null ? "" : this.httpAuthPwd).toString()
                    .getBytes("UTF-8")), "UTF-8");
        }/*from   w w  w  . j a  va 2s . c o  m*/
        // Keystore handler trust manager
        Resource keystore = null;
        if (this.keystoreSource == null) {
            Assert.isNull(this.keystoreSource);
        } else {
            if (this.keystoreSource.startsWith("classpath:")) {
                keystore = new ClassPathResource(this.keystoreSource);
            } else {
                keystore = new FileSystemResource(this.keystoreSource);
            }
        }
        if (keystore == null) {
            Assert.isNull(keystore);
        }
        this.trustManager = new EipX509TrustManager();
        this.trustManager.setKeystore(keystore);
        this.trustManager.setKeystorePassword(new String(this.keystorePwd));
        this.trustManager.init();
    }
    // SSL Context
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(null, new TrustManager[] { this.trustManager }, null);
    SSLContext.setDefault(ctx);
}

From source file:com.sitewhere.groovy.device.communication.rest.RestHelper.java

/**
 * Create SSL context that allows bad certificates.
 * /*from ww w.  j  av  a 2s .  c om*/
 * @return
 */
protected SSLContext createContext() {
    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) {
        }
    } };

    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        SSLContext.setDefault(sc);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return sc;

    } catch (Exception e) {
    }
    return null;
}

From source file:org.pentaho.runtime.test.network.impl.GatewayConnectivityTestImpl.java

@Override
public RuntimeTestResultEntry runTest() {

    if (StringUtils.isBlank(hostname)) {
        return new RuntimeTestResultEntryImpl(severityOfFalures,
                messageGetter.getMessage(CONNECT_TEST_HOST_BLANK_DESC),
                messageGetter.getMessage(CONNECT_TEST_HOST_BLANK_MESSAGE));
    } else {/*from  ww w  . j a  v a  2 s .  c  o  m*/

        try {
            Integer portInt = Integer.parseInt(port);
            // Ignore ssl certificate issues if KETTLE_KNOX_IGNORE_SSL = true
            if (variables.getBooleanValueOfVariable("${KETTLE_KNOX_IGNORE_SSL}", false)) {
                SSLContext ctx = getTlsContext();
                initContextWithTrustAll(ctx);
                SSLContext.setDefault(ctx);
            }
            String userString = "";
            HttpClientContext context = null;
            HttpGet method = new HttpGet(uri.toString());
            HttpClient httpClient;

            if (StringUtils.isNotBlank(user)) {
                userString = user;
                httpClient = getHttpClient(user, password);
                context = HttpClientUtil.createPreemptiveBasicAuthentication(uri.getHost(), portInt, user,
                        password);
            } else {
                httpClient = getHttpClient();
            }

            HttpResponse httpResponse = context != null ? httpClient.execute(method, context)
                    : httpClient.execute(method);
            Integer returnCode = httpResponse.getStatusLine().getStatusCode();

            switch (returnCode) {
            case 200: {
                return new RuntimeTestResultEntryImpl(RuntimeTestEntrySeverity.INFO,
                        messageGetter.getMessage(GATEWAY_CONNECT_TEST_CONNECT_SUCCESS_DESC),
                        messageGetter.getMessage(GATEWAY_CONNECT_TEST_CONNECT_SUCCESS_MESSAGE, uri.toString()));
            }
            case 404: {
                return new RuntimeTestResultEntryImpl(severityOfFalures,
                        messageGetter.getMessage(GATEWAY_CONNECT_TEST_SERVICE_NOT_FOUND_DESC), messageGetter
                                .getMessage(GATEWAY_CONNECT_TEST_SERVICE_NOT_FOUND_MESSAGE, uri.toString()));
            }
            case 403: {
                return new RuntimeTestResultEntryImpl(severityOfFalures,
                        messageGetter.getMessage(GATEWAY_CONNECT_TEST_FORBIDDEN_DESC), messageGetter.getMessage(
                                GATEWAY_CONNECT_TEST_FORBIDDEN_MESSAGE, uri.toString(), userString));
            }
            case 401: {
                return new RuntimeTestResultEntryImpl(severityOfFalures,
                        messageGetter.getMessage(GATEWAY_CONNECT_TEST_UNAUTHORIZED_DESC),
                        messageGetter.getMessage(GATEWAY_CONNECT_TEST_UNAUTHORIZED_MESSAGE, uri.toString(),
                                userString));
            }
            default: {
                return new RuntimeTestResultEntryImpl(RuntimeTestEntrySeverity.WARNING,
                        messageGetter.getMessage(GATEWAY_CONNECT_TEST_CONNECT_UNKNOWN_RETURN_CODE_DESC),
                        messageGetter.getMessage(GATEWAY_CONNECT_TEST_CONNECT_UNKNOWN_RETURN_CODE_MESSAGE,
                                userString, returnCode.toString(), uri.toString()));
            }
            }
        } catch (NoSuchAlgorithmException e) {
            return new RuntimeTestResultEntryImpl(RuntimeTestEntrySeverity.FATAL,
                    messageGetter.getMessage(GATEWAY_CONNECT_TLSCONTEXT_DESC),
                    messageGetter.getMessage(GATEWAY_CONNECT_TLSCONTEXT_MESSAGE), e);
        } catch (SSLException e) {
            return new RuntimeTestResultEntryImpl(severityOfFalures,
                    messageGetter.getMessage(GATEWAY_CONNECT_SSLEXCEPTION_DESC), messageGetter.getMessage(
                            GATEWAY_CONNECT_SSLEXCEPTION_MESSAGE, uri.toString(), e.getMessage()),
                    e);
        } catch (UnknownHostException e) {
            return new RuntimeTestResultEntryImpl(severityOfFalures,
                    messageGetter.getMessage(CONNECT_TEST_UNKNOWN_HOSTNAME_DESC),
                    messageGetter.getMessage(CONNECT_TEST_UNKNOWN_HOSTNAME_MESSAGE, uri.getHost()), e);
        } catch (KeyManagementException e) {
            return new RuntimeTestResultEntryImpl(RuntimeTestEntrySeverity.FATAL,
                    messageGetter.getMessage(GATEWAY_CONNECT_TLSCONTEXTINIT_DESC),
                    messageGetter.getMessage(GATEWAY_CONNECT_TLSCONTEXTINIT_MESSAGE), e);
        } catch (IOException e) {
            return new RuntimeTestResultEntryImpl(severityOfFalures,
                    messageGetter.getMessage(GATEWAY_CONNECT_EXECUTION_FAILED_DESC),
                    messageGetter.getMessage(GATEWAY_CONNECT_EXECUTION_FAILED_MESSAGE, uri.toString()), e);
        } catch (NumberFormatException e) {
            return new RuntimeTestResultEntryImpl(RuntimeTestEntrySeverity.FATAL,
                    messageGetter.getMessage(CONNECT_TEST_PORT_NUMBER_FORMAT_DESC),
                    messageGetter.getMessage(CONNECT_TEST_PORT_NUMBER_FORMAT_MESSAGE, port), e);
        }
    }
}