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:org.dasein.cloud.google.HttpsConnection.java

public static String getJSON(String iss, String p12File) throws Exception {
    System.out.println("ISS : " + iss);
    System.out.println("P12File : " + p12File);

    HttpClient client = new DefaultHttpClient();
    List formparams = new ArrayList();
    formparams.add(new BasicNameValuePair("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"));
    formparams.add(new BasicNameValuePair("assertion", GenerateToken.getToken(iss, p12File)));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");

    //      HttpClient client1 = new HttpClient();
    String url = "https://accounts.google.com/o/oauth2/token";
    //      System.out.println(url);
    //      PostMethod pm = new PostMethod(url); 
    //      pm.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    //      pm.addRequestHeader("Host", "accounts.google.com");
    ////      pm.addRequestHeader("Host", "accounts.google.com");
    //      pm.addParameter("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer");
    //      pm.addParameter("assertion", GenerateToken.getData());
    ////      System.out.println(C.getData());
    ////from   www  . j  a  v a 2s  . c o m
    //      int statusCode = client1.executeMethod(pm);

    HttpPost httppost = new HttpPost(url);
    httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
    httppost.setEntity(entity);
    HttpResponse httpResponse1 = client.execute(httppost);
    int s1 = httpResponse1.getStatusLine().getStatusCode();
    if (s1 == HttpStatus.SC_OK) {
        try {
            //   InputStream in = getResponseBody(pm);
            InputStream in = httpResponse1.getEntity().getContent();
            writeToFile(in, "D:\\google_out.txt");
            System.out.println(printFile("D:\\google_out.txt"));
        } catch (Exception e) {
            System.out.println("No response body !");
        }
    }

    JSONObject obj1 = new JSONObject(printFile("D:\\google_out.txt"));
    String access_token = obj1.getString("access_token");
    String token_type = obj1.getString("token_type");
    String expires_in = obj1.getString("expires_in");
    String resource = "instances";
    url = "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-east1-a/"
            + resource + "?access_token=" + access_token + "&token_type=Bearer&expires_in=3600";
    String str = "{"
            + "\"image\": \"https://www.googleapis.com/compute/v1beta14/projects/google/global/images/gcel-10-04-v20130104\","
            + "\"machineType\": \"https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/global/machineTypes/n1-standard-1\","
            + "\"name\": \"trial\","
            + "\"zone\": \"https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-east1-a/\","
            + "\"networkInterfaces\": [ {  \"network\": \"https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/networks/default\" } ],"
            + "\"disks\": [ { \"type\": \"EPHEMERAL\",  \"deleteOnTerminate\": true  } ], \"metadata\": { \"items\": [ ],  \"kind\": \"compute#metadata\" }}";
    System.out.println(str);
    JSONObject json = new JSONObject(str);
    System.out.println("POST Methods : " + url);
    StringEntity se = new StringEntity(str);
    JSONObject json1 = new JSONObject();
    json1.put("image",
            "https://www.googleapis.com/compute/v1beta14/projects/google/global/images/gcel-10-04-v20130104");
    json1.put("machineType",
            "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/global/machineTypes/n1-standard-1");
    json1.put("name", "trial");
    json1.put("zone",
            "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-east1-a/");
    //json1.put("image", "https://www.googleapis.com/compute/v1beta13/projects/google/images/ubuntu-10-04-v20120621");
    System.out.println(" JSON 1 : " + json.toString() + " \n JSON 2 : " + json1.toString());
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    nameValuePairs.add(new BasicNameValuePair("json", str));

    //              
    //               JSONObject jsonPayload = null;
    //               JSONObject obj = new JSONObject();
    //               
    //               try {
    //               obj.put("name", "vinotrial");
    //               obj.put("IPv4Range", "192.0.0.0/16");
    //               obj.put("description", "wrwer");
    //
    //               } catch (Exception e) {
    //                  
    //               }

    /*
    JSONObject jsonPayload = null;
    JSONObject obj = new JSONObject();
            
    try {
    obj.put("name", "testCreateStandardFirewall1734".toLowerCase());
    obj.put("description", "SSH allowed from anywhere");
    obj.put("network", "https://www.googleapis.com/compute/v1beta13/projects/enstratus.com:enstratus-dev/networks/default");
    JSONArray sranges = new JSONArray();
    JSONArray allowed = new JSONArray();
    JSONObject allowedtemp = new JSONObject();
    JSONArray ports = new JSONArray();
    allowedtemp.put("IPProtocol", "tcp");
    ports.put("22");
    allowedtemp.put("ports", ports);
    allowed.put(allowedtemp);
    //               
    //               JSONObject allowedtemp1 = new JSONObject();
    //               JSONArray ports1 = new JSONArray();
    //               allowedtemp1.put("IPProtocol", "udp");
    //               ports1.put("1-65535");
    //               allowedtemp1.put("ports", ports1);
    //               allowed.put(allowedtemp1);
    //               
    //               
    //               
    //               JSONObject allowedtemp2 = new JSONObject();
    //               
    //               allowedtemp2.put("IPProtocol", "icmp");
    //               
    //               allowed.put(allowedtemp2);
            
            
    sranges.put("0.0.0.0/0");
    obj.put("sourceRanges", sranges);
    obj.put("allowed", allowed);
    } catch (Exception e) {
             
    }
            
            
    */

    //UrlEncodedFormEntity entity1 = new UrlEncodedFormEntity(formparams1, "UTF-8");
    System.out.println("Creating an instance");
    HttpPost httppost1 = new HttpPost(url);
    httppost1.setHeader("Content-type", "application/json");
    //httppost1.addHeader("X-JavaScript-User-Agent", "trov");
    //httppost1.setEntity(se);
    //   httppost1.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    System.out.println("payload:" + json1.toString());
    System.out.println("url:" + url);
    StringEntity se1 = new StringEntity(json1.toString());
    se1.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    httppost1.setEntity(se1);
    //

    HttpClient base = new DefaultHttpClient();
    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);
    SSLSocketFactory ssf = new SSLSocketFactory(ctx);
    ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm = base.getConnectionManager();
    SchemeRegistry sr = ccm.getSchemeRegistry();
    sr.register(new Scheme("https", ssf, 443));
    HttpClient client1 = new DefaultHttpClient(ccm);

    //HttpClient client1 = new DefaultHttpClient();
    HttpResponse httpResponse2 = client1.execute(httppost1);
    int s2 = httpResponse2.getStatusLine().getStatusCode();
    if (s2 == HttpStatus.SC_OK) {
        try {
            //   InputStream in = getResponseBody(pm);
            InputStream in = httpResponse2.getEntity().getContent();
            writeToFile(in, "D:\\google_out.txt");
            System.out.println(printFile("D:\\google_out.txt"));
        } catch (Exception e) {
            System.out.println("No response body !");
        }
    } else {
        System.out.println("Instance creation failed with error status " + s2);
        InputStream in = httpResponse2.getEntity().getContent();
        writeToFile(in, "D:\\google_out.txt");
        System.out.println(printFile("D:\\google_out.txt"));
    }

    String[] Zone = { "europe-west1-a", "europe-west1-b", "us-central1-a", "us-central1-b", "us-central2-a",
            "us-east1-a" };
    for (String zone : Zone) {
        //             {
        HttpClient client3 = new DefaultHttpClient();
        resource = "instances";
        System.out.println("listing the instances !");
        //      url= "https://www.googleapis.com/compute/v1beta13/projects/google/kernels?access_token=" + access_token + "&token_type=Bearer&expires_in=3600" ;
        url = "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-central1-a/"
                + resource + "?access_token=" + access_token + "&token_type=Bearer&expires_in=3600";
        //   url = "https://www.googleapis.com/compute/v1beta13/projects/enstratus.com:enstratus-dev?access_token=" + access_token + "&token_type=Bearer&expires_in=3600" ;
        //         url = "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-east1-a/instances?access_token=" + access_token + "&token_type=Bearer&expires_in=3600" ;
        System.out.println("url : -----------" + url);

        JSONArray items = new JSONArray();

        HttpGet method = new HttpGet(url);

        HttpResponse httpResponse = client3.execute(method);
        int s = httpResponse.getStatusLine().getStatusCode();

        if (s == HttpStatus.SC_OK) {

            try {
                System.out.println("\nResponse from Server : ");
                //InputStream in = getResponseBody(gm);
                InputStream in = httpResponse.getEntity().getContent();
                writeToFile(in, "D:\\calendar_out.txt");
                String str1 = printFile("D:\\calendar_out.txt");
                System.out.println(str1);
                JSONObject jsonO = new JSONObject(str1);
                items = (JSONArray) jsonO.get("items");

                //   return printFile("D:\\calendar_out.txt");
            } catch (Exception e) {
                System.out.println("No response body !" + e.getLocalizedMessage());
            }

        } else
            System.out.println(httpResponse);

        for (int i = 0; i < items.length(); i++) {

            JSONObject item = (JSONObject) items.get(i);
            String name = null;
            if (item.has("name"))
                name = (String) item.get("name");
            //System.out.println("instance : " + name);

            if (!name.contains("default")) {
                System.out.println("Deleting the instance " + name);
                url = "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-central1-a/"
                        + resource + "/" + name + "?access_token=" + access_token
                        + "&token_type=Bearer&expires_in=3600";
                System.out.println("url : " + url);

                HttpDelete delMethod = new HttpDelete(url);
                HttpResponse httpResponse3 = client.execute(delMethod);
                int s3 = httpResponse3.getStatusLine().getStatusCode();
                if (s3 == HttpStatus.SC_OK) {

                    try {
                        System.out.println("\nResponse from Server : ");
                        //InputStream in = getResponseBody(gm);
                        InputStream in = httpResponse3.getEntity().getContent();
                        writeToFile(in, "D:\\calendar_out.txt");
                        System.out.println(printFile("D:\\calendar_out.txt"));
                        //   return printFile("D:\\calendar_out.txt");
                    } catch (Exception e) {
                        System.out.println("No response body !");

                    }

                } else {
                    System.out.println("Deleting failed with status : " + s3);
                    try {
                        InputStream in = httpResponse3.getEntity().getContent();
                        writeToFile(in, "D:\\calendar_out.txt");
                        System.out.println(printFile("D:\\calendar_out.txt"));
                    } catch (Exception e) {

                    }
                }
            }
        }

        //      https://www.googleapis.com/compute/v1beta13/projects/enstratus.com%3Aenstratus-dev/instances/trial
        //      GetMethod gm      = new GetMethod(url); 
        //      HttpMethodParams params = new HttpMethodParams();
        ////      params.setParameter("calendarId", "vidhyanallasamy%40gmail.com");
        //      gm.setParams(params);
        //
        //      statusCode = client1.executeMethod(gm);
        //      System.out.println("\nStatus Code : " + statusCode);
        //
        //      try {
        //         System.out.println("\nResponse from Server : ");
        //         InputStream in = getResponseBody(gm);
        //         writeToFile(in, "D:\\calendar_out.txt");
        //         System.out.println(printFile("D:\\calendar_out.txt"));
        //      } catch (Exception e) {
        //         System.out.println("No response body !");
        //      }\
    }
    return null;
}

From source file:hudson.cli.CLI.java

public static int _main(String[] _args) throws Exception {
    List<String> args = Arrays.asList(_args);
    PrivateKeyProvider provider = new PrivateKeyProvider();
    boolean sshAuthRequestedExplicitly = false;
    String httpProxy = null;//from   ww  w  . ja v  a  2s.c o  m

    String url = System.getenv("JENKINS_URL");

    if (url == null)
        url = System.getenv("HUDSON_URL");

    boolean tryLoadPKey = true;

    Mode mode = null;

    String user = null;
    String auth = null;

    String userIdEnv = System.getenv("JENKINS_USER_ID");
    String tokenEnv = System.getenv("JENKINS_API_TOKEN");

    boolean strictHostKey = false;

    while (!args.isEmpty()) {
        String head = args.get(0);
        if (head.equals("-version")) {
            System.out.println("Version: " + computeVersion());
            return 0;
        }
        if (head.equals("-http")) {
            if (mode != null) {
                printUsage("-http clashes with previously defined mode " + mode);
                return -1;
            }
            mode = Mode.HTTP;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-ssh")) {
            if (mode != null) {
                printUsage("-ssh clashes with previously defined mode " + mode);
                return -1;
            }
            mode = Mode.SSH;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-remoting")) {
            if (mode != null) {
                printUsage("-remoting clashes with previously defined mode " + mode);
                return -1;
            }
            mode = Mode.REMOTING;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-s") && args.size() >= 2) {
            url = args.get(1);
            args = args.subList(2, args.size());
            continue;
        }
        if (head.equals("-noCertificateCheck")) {
            LOGGER.info("Skipping HTTPS certificate checks altogether. Note that this is not secure at all.");
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new TrustManager[] { new NoCheckTrustManager() }, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
            // bypass host name check, too.
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-noKeyAuth")) {
            tryLoadPKey = false;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-i") && args.size() >= 2) {
            File f = new File(args.get(1));
            if (!f.exists()) {
                printUsage(Messages.CLI_NoSuchFileExists(f));
                return -1;
            }

            provider.readFrom(f);

            args = args.subList(2, args.size());
            sshAuthRequestedExplicitly = true;
            continue;
        }
        if (head.equals("-strictHostKey")) {
            strictHostKey = true;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-user") && args.size() >= 2) {
            user = args.get(1);
            args = args.subList(2, args.size());
            continue;
        }
        if (head.equals("-auth") && args.size() >= 2) {
            auth = args.get(1);
            args = args.subList(2, args.size());
            continue;
        }
        if (head.equals("-p") && args.size() >= 2) {
            httpProxy = args.get(1);
            args = args.subList(2, args.size());
            continue;
        }
        if (head.equals("-logger") && args.size() >= 2) {
            Level level = parse(args.get(1));
            for (Handler h : Logger.getLogger("").getHandlers()) {
                h.setLevel(level);
            }
            for (Logger logger : new Logger[] { LOGGER, FullDuplexHttpStream.LOGGER, PlainCLIProtocol.LOGGER,
                    Logger.getLogger("org.apache.sshd") }) { // perhaps also Channel
                logger.setLevel(level);
            }
            args = args.subList(2, args.size());
            continue;
        }
        break;
    }

    if (url == null) {
        printUsage(Messages.CLI_NoURL());
        return -1;
    }

    if (auth == null) {
        // -auth option not set
        if (StringUtils.isNotBlank(userIdEnv) && StringUtils.isNotBlank(tokenEnv)) {
            auth = StringUtils.defaultString(userIdEnv).concat(":").concat(StringUtils.defaultString(tokenEnv));
        } else if (StringUtils.isNotBlank(userIdEnv) || StringUtils.isNotBlank(tokenEnv)) {
            printUsage(Messages.CLI_BadAuth());
            return -1;
        } // Otherwise, none credentials were set

    }

    if (!url.endsWith("/")) {
        url += '/';
    }

    if (args.isEmpty())
        args = Arrays.asList("help"); // default to help

    if (tryLoadPKey && !provider.hasKeys())
        provider.readFromDefaultLocations();

    if (mode == null) {
        mode = Mode.HTTP;
    }

    LOGGER.log(FINE, "using connection mode {0}", mode);

    if (user != null && auth != null) {
        LOGGER.warning("-user and -auth are mutually exclusive");
    }

    if (mode == Mode.SSH) {
        if (user == null) {
            // TODO SshCliAuthenticator already autodetects the user based on public key; why cannot AsynchronousCommand.getCurrentUser do the same?
            LOGGER.warning("-user required when using -ssh");
            return -1;
        }
        return SSHCLI.sshConnection(url, user, args, provider, strictHostKey);
    }

    if (strictHostKey) {
        LOGGER.warning("-strictHostKey meaningful only with -ssh");
    }

    if (user != null) {
        LOGGER.warning("Warning: -user ignored unless using -ssh");
    }

    CLIConnectionFactory factory = new CLIConnectionFactory().url(url).httpsProxyTunnel(httpProxy);
    String userInfo = new URL(url).getUserInfo();
    if (userInfo != null) {
        factory = factory.basicAuth(userInfo);
    } else if (auth != null) {
        factory = factory.basicAuth(
                auth.startsWith("@") ? FileUtils.readFileToString(new File(auth.substring(1))).trim() : auth);
    }

    if (mode == Mode.HTTP) {
        return plainHttpConnection(url, args, factory);
    }

    CLI cli = factory.connect();
    try {
        if (provider.hasKeys()) {
            try {
                // TODO: server verification
                cli.authenticate(provider.getKeys());
            } catch (IllegalStateException e) {
                if (sshAuthRequestedExplicitly) {
                    LOGGER.warning("The server doesn't support public key authentication");
                    return -1;
                }
            } catch (UnsupportedOperationException e) {
                if (sshAuthRequestedExplicitly) {
                    LOGGER.warning("The server doesn't support public key authentication");
                    return -1;
                }
            } catch (GeneralSecurityException e) {
                if (sshAuthRequestedExplicitly) {
                    LOGGER.log(WARNING, null, e);
                    return -1;
                }
                LOGGER.warning("Failed to authenticate with your SSH keys. Proceeding as anonymous");
                LOGGER.log(FINE, null, e);
            }
        }

        // execute the command
        // Arrays.asList is not serializable --- see 6835580
        args = new ArrayList<String>(args);
        return cli.execute(args, System.in, System.out, System.err);
    } finally {
        cli.close();
    }
}

From source file:com.dell.asm.asmcore.asmmanager.util.discovery.DeviceTypeCheckUtil.java

/**
 * HTTP request extractor//from   w  w w . ja  v a  2s  .  c  om
 *
 * @param urlToRead device URL
 * @return device type string
 * @throws IOException
 */
public static String getHTML(String urlToRead) throws IOException {
    URL url;
    HttpURLConnection conn;
    BufferedReader rd = null;
    String line;
    StringBuffer result = new StringBuffer();

    try {
        url = new URL(urlToRead);
        conn = (HttpURLConnection) url.openConnection();
        if (conn instanceof HttpsURLConnection) {
            HttpsURLConnection sslConn = (HttpsURLConnection) conn;
            sslConn.setHostnameVerifier(hv);
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[] { tmNoCheck }, new SecureRandom());
            sslConn.setSSLSocketFactory(sslContext.getSocketFactory());
        }

        conn.setRequestMethod("GET");
        conn.setConnectTimeout(AsmManagerApp.CONNECT_TIMEOUT); // timeout value
        conn.setReadTimeout(AsmManagerApp.CONNECT_TIMEOUT);
        rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
    } catch (RuntimeException e) {
        throw new IOException("Could not connect to the url: " + e.getMessage());
    } catch (Exception e) {
        throw new IOException("Could not connect to the url: " + urlToRead);
    } finally {
        if (rd != null)
            rd.close();
    }
    return result.toString();
}

From source file:com.dell.asm.asmcore.asmmanager.util.discovery.DeviceTypeCheckUtil.java

/**
 * HTTP POST with basic auth//from   www.  java 2 s .c  o m
 *
 * @param urlToRead device URL
 * @return http response message
 * @throws IOException
 */
public static String httpPost(String urlToRead, String username, String password) throws IOException {
    URL url;
    HttpURLConnection conn;
    BufferedReader rd = null;
    String line;
    StringBuffer result = new StringBuffer();

    try {
        url = new URL(urlToRead);
        conn = (HttpURLConnection) url.openConnection();
        if (conn instanceof HttpsURLConnection) {
            HttpsURLConnection sslConn = (HttpsURLConnection) conn;
            sslConn.setHostnameVerifier(hv);
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[] { tmNoCheck }, new SecureRandom());
            sslConn.setSSLSocketFactory(sslContext.getSocketFactory());
        }
        conn.setDoOutput(true);
        conn.setConnectTimeout(AsmManagerApp.CONNECT_TIMEOUT); // timeout value
        conn.setReadTimeout(AsmManagerApp.CONNECT_TIMEOUT);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("x-dell-api-version", "2.0");
        conn.setRequestProperty("Authorization", encodeCredentials(username, password));
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setFixedLengthStreamingMode("{}".length());
        conn.getOutputStream().write("{}".getBytes(Charset.forName("UTF-8")));

        rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
    } catch (RuntimeException e) {
        throw new IOException("Could not connect to the url: " + e.getMessage());
    } catch (Exception e) {
        throw new IOException("Could not connect to the url: " + urlToRead);
    } finally {
        if (rd != null)
            rd.close();
    }
    return result.toString();
}

From source file:edu.vt.middleware.ldap.ssl.AbstractSSLContextInitializer.java

/** {@inheritDoc} */
public SSLContext initSSLContext(final String protocol) throws GeneralSecurityException {
    final SSLContext ctx = SSLContext.getInstance(protocol);
    ctx.init(this.getKeyManagers(), this.getTrustManagers(), null);
    return ctx;//from w  ww .j a v  a2 s  .  c  om
}

From source file:org.apache.falcon.resource.channel.SecureHTTPChannel.java

@Override
protected Client getClient() throws Exception {
    Properties properties = StartupProperties.get();
    String keyStoreFile = properties.getProperty("keystore.file", "conf/prism.keystore");
    String password = properties.getProperty("keystore.password", "falcon-prism-passwd");
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(
            new KeyManager[] { KeyManagerUtils.createClientKeyManager(new File(keyStoreFile), password) },
            new TrustManager[] { TrustManagerUtils.getValidateServerCertificateTrustManager() },
            new SecureRandom());
    DefaultClientConfig config = new DefaultClientConfig();
    config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
            new HTTPSProperties(new AllowAllHostnameVerifier(), sslContext));
    LOG.info("Configuring client with " + new File(keyStoreFile).getAbsolutePath());
    return Client.create(config);
}

From source file:org.apache.reef.runtime.hdinsight.client.sslhacks.UnsafeClientConstructor.java

private SSLContext getSSLContext() throws KeyManagementException, NoSuchAlgorithmException {
    final SSLContext sc = SSLContext.getInstance("TLS");
    sc.init(new KeyManager[0], new TrustManager[] { new UnsafeTrustManager() }, new SecureRandom());
    return sc;/*  w ww  .j a  va  2 s  .c om*/
}

From source file:org.addhen.smssync.net.ssl.TrustedSocketFactory.java

public TrustedSocketFactory(String host, boolean secure)
        throws NoSuchAlgorithmException, KeyManagementException {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[] { TrustManagerFactory.get(host, secure) }, new SecureRandom());
    mSocketFactory = sslContext.getSocketFactory();
    mSchemeSocketFactory = org.apache.http.conn.ssl.SSLSocketFactory.getSocketFactory();
    mSchemeSocketFactory//w  w w . ja  v  a  2s . c om
            .setHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
}

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

@Override
public SSLSocketFactory getObject() throws Exception {
    try {/*from  w  ww  . ja v a 2  s.co m*/
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new SecureRandom());
        return sc.getSocketFactory();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.obiba.mica.config.ssl.SslContextFactoryImpl.java

@Override
public SSLContext createSslContext() {
    KeyStoreManager keystore = prepareServerKeystore();
    try {/*from   ww w. j av  a 2 s  . co m*/
        SSLContext ctx = SSLContext.getInstance("TLSv1.2");
        ctx.init(new KeyManager[] { new X509ExtendedKeyManagerImpl(keystore) }, null, null);
        return ctx;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}