Example usage for org.apache.http.conn.ssl SSLSocketFactory SSLSocketFactory

List of usage examples for org.apache.http.conn.ssl SSLSocketFactory SSLSocketFactory

Introduction

In this page you can find the example usage for org.apache.http.conn.ssl SSLSocketFactory SSLSocketFactory.

Prototype

public SSLSocketFactory(final SSLContext sslContext) 

Source Link

Usage

From source file:org.forgerock.openig.http.HttpClient.java

/**
 * Returns a new SSL socket factory that does not perform hostname verification.
 *
 * @param keyManagerFactory/*from  w  w w.  ja v a 2s. co m*/
 *         Provides Keys/Certificates in case of SSL/TLS connections
 * @param trustManagerFactory
 *         Provides TrustManagers in case of SSL/TLS connections
 * @throws GeneralSecurityException
 *         if the SSL algorithm is unsupported or if an error occurs during SSL configuration
 */
private static SSLSocketFactory newSSLSocketFactory(final KeyManagerFactory keyManagerFactory,
        final TrustManagerFactory trustManagerFactory) throws GeneralSecurityException {
    SSLContext context = SSLContext.getInstance("TLS");
    context.init((keyManagerFactory == null) ? null : keyManagerFactory.getKeyManagers(),
            (trustManagerFactory == null) ? null : trustManagerFactory.getTrustManagers(), null);
    SSLSocketFactory factory = new SSLSocketFactory(context);
    factory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    return factory;
}

From source file:net.sourceforge.jwbf.mediawiki.live.LoginIT.java

private AbstractHttpClient getSSLFakeHttpClient() throws NoSuchAlgorithmException, KeyManagementException {
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
        @Override/*from w w w.ja  v a  2s  .  c om*/
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

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

    SSLSocketFactory sf = new SSLSocketFactory(sslContext);
    sf.setHostnameVerifier(new X509HostnameVerifier() {

        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }

        @Override
        public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
        }

        @Override
        public void verify(String host, X509Certificate cert) throws SSLException {
        }

        @Override
        public void verify(String host, SSLSocket ssl) throws IOException {
        }
    });
    Scheme httpsScheme = new Scheme("https", sf, 443);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(httpsScheme);

    HttpParams params = new BasicHttpParams();

    ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);

    DefaultHttpClient httpClient = new DefaultHttpClient(cm, params);
    return httpClient;
}

From source file:bear.plugins.java.JenkinsCache.java

public static File download(String jdkVersion, File jenkinsCache, File tempDestDir, String jenkinsUri,
        String user, String pass) {
    try {// w w  w  .j  a va  2s  .  co  m
        Optional<JDKFile> optional = load(jenkinsCache, jenkinsUri, jdkVersion);

        if (!optional.isPresent()) {
            throw new RuntimeException("could not find: " + jdkVersion);
        }

        String uri = optional.get().filepath;

        SSLContext sslContext = SSLContext.getInstance("TLSv1");

        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                System.out.println("getAcceptedIssuers =============");
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
                System.out.println("checkClientTrusted =============");
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
                System.out.println("checkServerTrusted =============");
            }
        } }, new SecureRandom());

        SSLSocketFactory sf = new SSLSocketFactory(sslContext);

        Scheme httpsScheme = new Scheme("https", 443, sf);
        SchemeRegistry schemeRegistry = new SchemeRegistry();

        Scheme httpScheme = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());

        schemeRegistry.register(httpsScheme);
        schemeRegistry.register(httpScheme);

        DefaultHttpClient httpClient = new DefaultHttpClient(
                new PoolingClientConnectionManager(schemeRegistry));

        CookieStore cookieStore = new BasicCookieStore();
        BasicClientCookie cookie = new BasicClientCookie("gpw_e24", ".");
        cookie.setDomain("oracle.com");
        cookie.setPath("/");
        cookie.setSecure(true);

        cookieStore.addCookie(cookie);

        httpClient.setCookieStore(cookieStore);

        HttpPost httppost = new HttpPost("https://login.oracle.com");

        httppost.setHeader("Authorization",
                "Basic " + new String(Base64.encodeBase64((user + ":" + pass).getBytes()), "UTF-8"));

        HttpResponse response = httpClient.execute(httppost);

        int code = response.getStatusLine().getStatusCode();

        if (code != 302) {
            System.out.println(IOUtils.toString(response.getEntity().getContent()));
            throw new RuntimeException("unable to auth: " + code);
        }

        // closes the single connection
        //                EntityUtils.consumeQuietly(response.getEntity());

        httppost = new HttpPost(uri);

        httppost.setHeader("Authorization",
                "Basic " + new String(Base64.encodeBase64((user + ":" + pass).getBytes()), "UTF-8"));

        response = httpClient.execute(httppost);

        code = response.getStatusLine().getStatusCode();

        if (code != 302) {
            System.out.println(IOUtils.toString(response.getEntity().getContent()));
            throw new RuntimeException("to download: " + uri);
        }

        File file = new File(tempDestDir, optional.get().name);
        HttpEntity entity = response.getEntity();

        final long length = entity.getContentLength();

        final CountingOutputStream os = new CountingOutputStream(new FileOutputStream(file));

        System.out.printf("Downloading %s to %s...%n", uri, file);

        Thread progressThread = new Thread(new Runnable() {
            double lastProgress;

            @Override
            public void run() {
                while (!Thread.currentThread().isInterrupted()) {
                    long copied = os.getCount();

                    double progress = copied * 100D / length;

                    if (progress != lastProgress) {
                        System.out.printf("\rProgress: %s%%", LangUtils.toConciseString(progress, 1));
                    }

                    lastProgress = progress;

                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        break;
                    }
                }
            }
        }, "progressThread");

        progressThread.start();

        ByteStreams.copy(entity.getContent(), os);

        progressThread.interrupt();

        System.out.println("Download complete.");

        return file;
    } catch (Exception e) {
        throw Exceptions.runtime(e);
    }
}

From source file:org.brunocvcunha.taskerbox.core.http.TaskerboxHttpBox.java

/**
 * Build a new HTTP Client for the given parameters
 *
 * @param params//  ww  w  .jav  a  2 s.c  o m
 * @return
 */
public DefaultHttpClient buildNewHttpClient(HttpParams params) {
    PoolingClientConnectionManager cxMgr = new PoolingClientConnectionManager(
            SchemeRegistryFactory.createDefault());
    cxMgr.setMaxTotal(100);
    cxMgr.setDefaultMaxPerRoute(20);

    DefaultHttpClient httpClient = new DefaultHttpClient(cxMgr, params);
    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
            "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36");
    // httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY,
    // CookiePolicy.BROWSER_COMPATIBILITY);
    if (this.useNtlm) {
        httpClient.getAuthSchemes().register("NTLM", new NTLMSchemeFactory());
        httpClient.getAuthSchemes().register("BASIC", new BasicSchemeFactory());
        httpClient.getAuthSchemes().register("DIGEST", new DigestSchemeFactory());
        httpClient.getAuthSchemes().register("SPNEGO", new SPNegoSchemeFactory());
        httpClient.getAuthSchemes().register("KERBEROS", new KerberosSchemeFactory());
    }

    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, getTrustingManager(), new java.security.SecureRandom());
        SSLSocketFactory socketFactory = new SSLSocketFactory(sc);
        Scheme sch = new Scheme("https", 443, socketFactory);
        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    if (this.useProxy) {
        if (this.proxySocks) {

            log.info("Using proxy socks " + this.socksHost + ":" + this.socksPort);

            System.setProperty("socksProxyHost", this.socksHost);
            System.setProperty("socksProxyPort", String.valueOf(this.socksPort));

        } else {
            HttpHost proxy = new HttpHost(this.proxyHost, this.proxyPort);
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

            if (this.authProxy) {

                List<String> authPreferences = new ArrayList<>();

                if (this.ntlmProxy) {

                    NTCredentials creds = new NTCredentials(this.proxyUser, this.proxyPassword,
                            this.proxyWorkstation, this.proxyDomain);
                    httpClient.getCredentialsProvider()
                            .setCredentials(new AuthScope(this.proxyHost, this.proxyPort), creds);
                    // httpClient.getCredentialsProvider().setCredentials(
                    // AuthScope.ANY, creds);

                    authPreferences.add(AuthPolicy.NTLM);
                } else {
                    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(this.proxyUser,
                            this.proxyPassword);
                    httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

                    authPreferences.add(AuthPolicy.BASIC);
                }

                httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authPreferences);
            }
        }

    }

    return httpClient;
}

From source file:android.core.SSLPerformanceTest.java

private void getVerisignDotCom(OpenSSLContextImpl sslContext) throws IOException {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry//from  w w  w. j a  va2  s.  co  m
            .register(new Scheme("https", new SSLSocketFactory(sslContext.engineGetSocketFactory()), 443));

    ClientConnectionManager manager = new SingleClientConnManager(null, schemeRegistry);

    new DefaultHttpClient(manager, null).execute(new HttpGet("https://www.verisign.com"),
            new ResponseHandler<Object>() {
                public Object handleResponse(HttpResponse response)
                        throws ClientProtocolException, IOException {
                    return null;
                }
            });
}

From source file:org.wso2.cdm.agent.proxy.ServerApiAccess.java

public static HttpClient getCertifiedHttpClient() {
    try {//from   w  ww. jav a  2s  .  c  o  m
        HttpClient client = null;
        if (CommonUtilities.SERVER_PROTOCOL.equalsIgnoreCase("https://")) {
            KeyStore localTrustStore = KeyStore.getInstance("BKS");
            InputStream in = IdentityProxy.getInstance().getContext().getResources()
                    .openRawResource(R.raw.emm_truststore);
            localTrustStore.load(in, CommonUtilities.TRUSTSTORE_PASSWORD.toCharArray());

            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            SSLSocketFactory sslSocketFactory = new SSLSocketFactory(localTrustStore);
            sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
            HttpParams params = new BasicHttpParams();
            ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);

            client = new DefaultHttpClient(cm, params);

        } else {
            client = new DefaultHttpClient();
        }
        return client;
    } catch (Exception e) {
        Log.d(TAG, e.toString());
        return null;
    }
}

From source file:org.eclipse.lyo.testsuite.server.util.OSLCUtils.java

static public void setupLazySSLSupport(HttpClient httpClient) {
    ClientConnectionManager connManager = httpClient.getConnectionManager();
    SchemeRegistry schemeRegistry = connManager.getSchemeRegistry();
    schemeRegistry.unregister("https");
    /** Create a trust manager that does not validate certificate chains */
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            /** Ignore Method Call */
        }//from  www. java2s .co  m

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            /** Ignore Method Call */
        }

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    } };

    SSLContext sc = null;
    try {
        sc = SSLContext.getInstance("SSL"); //$NON-NLS-1$
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
    } catch (NoSuchAlgorithmException e) {
        /* Fail Silently */
    } catch (KeyManagementException e) {
        /* Fail Silently */
    }

    SSLSocketFactory sf = new SSLSocketFactory(sc);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme https = new Scheme("https", sf, 443);

    schemeRegistry.register(https);
}

From source file:com.linkedin.drelephant.clients.azkaban.AzkabanWorkflowClient.java

/**
 * Makes REST API Call for given url parameters and returns the json object
 *
 * @param urlParameters/*from   w  ww  .  j ava  2  s. c  o  m*/
 * @return Json Object in the response body
 */
private JSONObject fetchJson(List<NameValuePair> urlParameters, String azkabanUrl) {
    HttpPost httpPost = new HttpPost(azkabanUrl);
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    httpPost.setHeader("Accept", "*/*");
    httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

    HttpClient httpClient = new DefaultHttpClient();
    JSONObject jsonObj = null;
    try {
        SSLSocketFactory socketFactory = new SSLSocketFactory(new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        });

        Scheme scheme = new Scheme("https", 443, socketFactory);
        httpClient.getConnectionManager().getSchemeRegistry().register(scheme);
        HttpResponse response = httpClient.execute(httpPost);

        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new RuntimeException(response.getStatusLine().toString() + "\nStatus code: "
                    + response.getStatusLine().getStatusCode());
        }

        String result = parseContent(response.getEntity().getContent());
        try {
            jsonObj = new JSONObject(result);
            if (jsonObj.has("error")) {
                throw new RuntimeException(jsonObj.get("error").toString());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
    return jsonObj;
}

From source file:org.soyatec.windowsazure.internal.util.ssl.SslUtil.java

/**
 * Get the SSLSocketFactory by given SSLContext
 * //from   ww  w. jav  a 2  s  .  c o m
 * @param context
 *            the SSLContext object
 * @return the SSLSocketFactory object
 */
public static SSLSocketFactory getSSLSocketFactory(SSLContext context) {
    SSLSocketFactory factory = new SSLSocketFactory(context);
    factory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    return factory;
}

From source file:password.pwm.http.client.PwmHttpClient.java

private static ClientConnectionManager makeConnectionManager(TrustManager trustManager)
        throws NoSuchAlgorithmException, KeyManagementException {
    final SSLContext sslContext = SSLContext.getInstance("SSL");

    sslContext.init(null, new TrustManager[] { trustManager }, new SecureRandom());

    final SSLSocketFactory sf = new SSLSocketFactory(sslContext);
    final HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    sf.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
    final Scheme httpsScheme = new Scheme("https", 443, sf);
    final SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(httpsScheme);

    return new SingleClientConnManager(schemeRegistry);
}