Example usage for javax.net.ssl SSLContext init

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

Introduction

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

Prototype

public final void init(KeyManager[] km, TrustManager[] tm, SecureRandom random) throws KeyManagementException 

Source Link

Document

Initializes this context.

Usage

From source file:ch.cyberduck.core.ssl.CustomTrustSSLProtocolSocketFactory.java

private SSLContext createEasySSLContext() {
    try {/*  w  w  w. j av a2 s  . c  o  m*/
        SSLContext context = SSLContext.getInstance("SSL");
        context.init(null, new TrustManager[] { trustManager }, null);
        return context;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return null;
    }
}

From source file:eu.europa.ec.markt.dss.validation.https.SimpleProtocolSocketFactory.java

private SSLContext createEasySSLContext() {
    try {/*from w  ww.  j  a  va  2s  .c  om*/
        SSLContext context = SSLContext.getInstance("SSL");
        context.init(null, new TrustManager[] { new OptimistTrustManager() }, null);
        return context;
    } catch (Exception e) {
        LOG.severe(e.getMessage());
        throw new HttpClientError(e.toString());
    }
}

From source file:org.everit.authentication.cas.ecm.tests.SecureHttpClient.java

/**
 * Constructor./*  w ww  . j a va2s. c o  m*/
 */
public SecureHttpClient(final String principal, final BundleContext bundleContext) throws Exception {
    this.principal = principal;

    httpClientContext = HttpClientContext.create();
    httpClientContext.setCookieStore(new BasicCookieStore());

    KeyStore trustStore = KeyStore.getInstance("jks");
    trustStore.load(bundleContext.getBundle().getResource("/jetty-keystore").openStream(),
            "changeit".toCharArray());

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);
    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, trustManagers, new SecureRandom());

    httpClient = HttpClientBuilder.create().setSslcontext(sslContext)
            .setRedirectStrategy(new DefaultRedirectStrategy()).build();
}

From source file:org.gluu.oxtrust.ldap.service.LinktrackService.java

public String newLink(@NotEmpty String login, @NotEmpty String password, @NotEmpty String link) {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }//w w w .j av  a 2s . c  om

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

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

    // 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 (Exception e) {
    }
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(String.format(CREATE_LINK_URL_PATTERN, login, password, link));
    HttpResponse response;
    try {
        response = httpclient.execute(httpget);
    } catch (Exception e) {
        log.error(String.format("Exception happened during linktrack link "
                + "creation with username: %s, password: %s," + " link: %s.", login, password, link), e);
        return null;
    }

    String trackedLink = null;
    if (response.getStatusLine().getStatusCode() == 201) {
        try {
            trackedLink = IOUtils.toString(response.getEntity().getContent());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return trackedLink;
}

From source file:com.ibm.iotf.client.AbstractClient.java

/**
 * @param organization  Organization ID (Either "quickstart" or the registered organization ID)
 * @param domain      Domain of the Watson IoT Platform, for example internetofthings.ibmcloud.com
 * @param deviceType   Device Type/*w w  w  .  j a v  a2 s  .  co m*/
 * @param deviceId      Device ID
 * @param eventName      Name of the Event
 * @param device       Boolean value indicating whether the request is originated from device or application
 * @param authKey      Authentication Method
 * @param authToken      Authentication Token to securely post this event (Can be null or empty if its quickstart)
 * @param payload      The message to be published
 * @return int         HTTP code indicating the status of the HTTP request
 * @throws Exception   throws exception when http post fails
 */
protected static int publishEventsThroughHttps(String organization, String domain, String deviceType,
        String deviceId, String eventName, boolean device, String authKey, String authToken, Object payload)
        throws Exception {

    final String METHOD = "publishEventsThroughHttps";

    validateNull("Organization ID", organization);
    validateNull("Domain", domain);
    validateNull("Device Type", deviceType);
    validateNull("Device ID", deviceId);
    validateNull("Event Name", eventName);
    if (QUICK_START.equalsIgnoreCase(organization) == false) {
        validateNull("Authentication Method", authKey);
        validateNull("Authentication Token", authToken);
    }

    StringBuilder sb = new StringBuilder();

    // Form the URL
    if (QUICK_START.equalsIgnoreCase(organization)) {
        sb.append("http://");
    } else {
        sb.append("https://");
    }
    sb.append(organization).append(".messaging.internetofthings.ibmcloud.com/api/v0002");

    if (device == true) {
        sb.append("/device");
    } else {
        sb.append("/application");
    }
    sb.append("/types/").append(deviceType).append("/devices/").append(deviceId).append("/events/")
            .append(eventName);

    LoggerUtility.fine(CLASS_NAME, METHOD, "ReST URL::" + sb.toString());
    BufferedReader br = null;

    // Create the payload message in Json format
    JsonObject message = (JsonObject) gson.toJsonTree(payload);
    StringEntity input = new StringEntity(message.toString(), StandardCharsets.UTF_8);

    // Create the Http post request
    HttpPost post = new HttpPost(sb.toString());
    post.setEntity(input);
    post.addHeader("Content-Type", "application/json");
    post.addHeader("Accept", "application/json");

    if (QUICK_START.equalsIgnoreCase(organization) == false) {
        byte[] encoding = Base64.encodeBase64(new String(authKey + ":" + authToken).getBytes());
        String encodedString = new String(encoding);
        post.addHeader("Authorization", "Basic " + encodedString);
    }

    try {

        SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(null, null, null);

        HttpClient client = HttpClientBuilder.create().setSSLContext(sslContext).build();

        HttpResponse response = client.execute(post);

        int httpCode = response.getStatusLine().getStatusCode();
        if (httpCode >= 200 && httpCode < 300) {
            return httpCode;
        }

        /**
         * Looks like some error so log the header and response
         */
        System.out.println("Looks like some error, so log the header and response");
        StringBuilder log = new StringBuilder("HTTP Code: " + httpCode);
        log.append("\nURL: ").append(sb.toString()).append("\nHeader:\n");
        Header[] headers = response.getAllHeaders();
        for (int i = 0; i < headers.length; i++) {
            log.append(headers[i].getName()).append(' ').append(headers[i].getValue()).append('\n');
        }
        log.append("\nResponse \n");
        br = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
        log.append(br.readLine());
        LoggerUtility.severe(CLASS_NAME, METHOD, log.toString());

        return httpCode;
    } catch (IOException e) {
        LoggerUtility.severe(CLASS_NAME, METHOD, e.getMessage());
        throw e;
    } finally {
        if (br != null) {
            br.close();
        }
    }
}

From source file:com.collabnet.svnedge.net.SslProtocolSocketFactory.java

private SslProtocolSocketFactory() {
    try {/*from w  w w.j ava  2  s . c om*/
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { new TrustAllTrustManager() }, null);
        this.socketFactory = sslContext.getSocketFactory();
    } catch (Exception e) {
        log(0, "Could not initialize SSL context", e);
    }
}

From source file:org.ksoap2.transport.ServiceConnectionSE.java

public ServiceConnectionSE(String url) throws IOException {
    // /*w  ww  .  j a v a 2  s . c  o m*/
    try {
        SSLContext sContext = SSLContext.getInstance("SSL");
        sContext.init(null, trustAllCerts, new java.security.SecureRandom());

        HttpsURLConnection.setDefaultSSLSocketFactory(sContext.getSocketFactory());
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    connection = (HttpsURLConnection) new URL(url).openConnection();
    ((HttpsURLConnection) connection).setHostnameVerifier(new AllowAllHostnameVerifier());
    connection.setUseCaches(false);
    connection.setDoOutput(true);
    connection.setDoInput(true);
}

From source file:client.lib.Client.java

public Client() throws NoSuchAlgorithmException, KeyManagementException {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            X509Certificate[] myTrustedAnchors = new X509Certificate[0];
            return myTrustedAnchors;
        }// w  w w.j av a2  s .  co m

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

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

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

    // Create an ssl socket factory with our all-trusting manager
    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

    http2Client = new OkHttpClient();
    http2Client.setSslSocketFactory(sslSocketFactory);
    http2Client.setHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });

    httpClient = http2Client.clone();

    httpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1));
    http2Client.setProtocols(Arrays.asList(Protocol.HTTP_2));
}

From source file:com.zaubersoftware.mule.module.jenkins.api.impl.HttpJenkinsService.java

protected void addSslConfiguration() throws NoSuchAlgorithmException, KeyManagementException {
    final SSLContext ctx = SSLContext.getInstance("SSL");

    ctx.init(null, null, null);
}