Example usage for javax.net.ssl SSLContext getInstance

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

Introduction

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

Prototype

public static SSLContext getInstance(String protocol) throws NoSuchAlgorithmException 

Source Link

Document

Returns a SSLContext object that implements the specified secure socket protocol.

Usage

From source file:com.villemos.ispace.httpcrawler.HttpAccessor.java

public int poll() throws Exception {

    /** Always ignore authentication protocol errors. */
    if (ignoreAuthenticationFailure) {
        SSLContext sslContext = SSLContext.getInstance("SSL");

        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new EasyX509TrustManager() }, new SecureRandom());

        SchemeRegistry schemeRegistry = new SchemeRegistry();

        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        Scheme httpsScheme = new Scheme("https", sf, 443);
        schemeRegistry.register(httpsScheme);

        SocketFactory sfa = new PlainSocketFactory();
        Scheme httpScheme = new Scheme("http", sfa, 80);
        schemeRegistry.register(httpScheme);

        HttpParams params = new BasicHttpParams();
        ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);

        client = new DefaultHttpClient(cm, params);
    } else {//  w  w w  .  j a  v a  2s  . co  m
        client = new DefaultHttpClient();
    }

    String proxyHost = getHttpCrawlerEndpoint().getProxyHost();
    Integer proxyPort = getHttpCrawlerEndpoint().getProxyPort();

    if (proxyHost != null && proxyPort != null) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    } else {
        ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
        client.setRoutePlanner(routePlanner);
    }

    /** The target location may demand authentication. We setup preemptive authentication. */
    if (getHttpCrawlerEndpoint().getAuthenticationUser() != null
            && getHttpCrawlerEndpoint().getAuthenticationPassword() != null) {
        client.getCredentialsProvider().setCredentials(
                new AuthScope(getHttpCrawlerEndpoint().getDomain(), getHttpCrawlerEndpoint().getPort()),
                new UsernamePasswordCredentials(getHttpCrawlerEndpoint().getAuthenticationUser(),
                        getHttpCrawlerEndpoint().getAuthenticationPassword()));
    }

    /** Set default cookie policy and store. Can be overridden for a specific method using for example;
     *    method.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); 
     */
    client.setCookieStore(cookieStore);
    client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

    String uriStr = getHttpCrawlerEndpoint().getProtocol() + "://" + getHttpCrawlerEndpoint().getDomain();
    if (getHttpCrawlerEndpoint().getPort() != 80) {
        uriStr += ":" + getHttpCrawlerEndpoint().getPort() + "" + getHttpCrawlerEndpoint().getPath();
    } else {
        uriStr += getHttpCrawlerEndpoint().getPath();
    }
    URI uri = new URI(uriStr);

    if (getHttpCrawlerEndpoint().getPort() != 80) {
        target = new HttpHost(getHttpCrawlerEndpoint().getDomain(), getHttpCrawlerEndpoint().getPort(),
                getHttpCrawlerEndpoint().getProtocol());
    } else {
        target = new HttpHost(getHttpCrawlerEndpoint().getDomain());
    }
    localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    /** Default boundary is the domain. */
    getHttpCrawlerEndpoint().getBoundaries()
            .add(getHttpCrawlerEndpoint().getProtocol() + "://" + getHttpCrawlerEndpoint().getDomain());

    HttpUriRequest method = createInitialRequest(uri);
    HttpResponse response = client.execute(target, method, localContext);

    if (response.getStatusLine().getStatusCode() == 200) {
        processSite(uri, response);
    } else if (response.getStatusLine().getStatusCode() == 302) {
        HttpHost target = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        HttpGet get = new HttpGet(target.toURI());
        // HttpGet get = new HttpGet("https://om.eo.esa.int/oem/kt/dashboard.php");

        /** Read the response fully, to clear it. */
        HttpEntity entity = response.getEntity();
        HttpClientConfigurer.readFully(entity.getContent());

        response = client.execute(target, get, localContext);
        processSite(uri, response);
        System.out.println("Final target: " + target);
    } else {
        HttpEntity entity = response.getEntity();
        InputStream instream = entity.getContent();
        System.out.println(HttpClientConfigurer.readFully(instream));
    }

    return 0;
}

From source file:com.camel.trainreserve.JDKHttpsClient.java

public static String doPost(String url, String cookieStr, String ctype, byte[] content, int connectTimeout,
        int readTimeout) throws Exception {
    HttpsURLConnection conn = null;
    OutputStream out = null;//from   w w  w  .j  a  va2s  . c  om
    String rsp = null;
    try {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
            //SSLContext.setDefault(ctx);
            conn = getConnection(new URL(url), METHOD_POST, ctype);
            conn.setSSLSocketFactory(ctx.getSocketFactory());

            conn.setRequestProperty("Cookie", cookieStr);
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            conn.setConnectTimeout(connectTimeout);
            conn.setReadTimeout(readTimeout);
        } catch (Exception e) {
            log.error("GET_CONNECTOIN_ERROR, URL = " + url, e);
            throw e;
        }
        try {
            out = conn.getOutputStream();
            out.write(content);
            rsp = getResponseAsString(conn);
        } catch (IOException e) {
            log.error("REQUEST_RESPONSE_ERROR, URL = " + url, e);
            throw e;
        }

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

    return rsp;
}

From source file:org.obiba.mica.core.service.AgateRestService.java

/**
 * Do not check anything from the remote host (Agate server is trusted).
 *
 * @return/*from   w  ww. j av a 2s. c om*/
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
private SSLConnectionSocketFactory getSocketFactory() throws NoSuchAlgorithmException, KeyManagementException {
    // Accepts any SSL certificate
    TrustManager tm = new X509TrustManager() {

        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {

        }

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {

        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[] { tm }, null);

    return new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
}

From source file:ucar.httpservices.CustomSSLProtocolSocketFactory.java

private SSLContext stdauthentication() throws Exception {
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, new TrustManager[] { new CustomX509TrustManager(null) }, null);
    return context;
}

From source file:iristk.speech.nuancecloud.NuanceCloudRecognizerListener.java

@SuppressWarnings("deprecation")
private static HttpClient getHttpClient() throws NoSuchAlgorithmException, KeyManagementException {
    // Standard HTTP parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUseExpectContinue(params, false);
    // Initialize the HTTP client
    HttpClient httpclient = new DefaultHttpClient(params);

    // Initialize/setup SSL
    TrustManager easyTrustManager = new X509TrustManager() {
        @Override/*from   ww  w  .  j av  a  2s  .  c o m*/
        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws java.security.cert.CertificateException {
        }

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

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

    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme sch = new Scheme("https", sf, 443);
    httpclient.getConnectionManager().getSchemeRegistry().register(sch);

    // Return the initialized instance of our httpclient
    return httpclient;
}

From source file:de.hybris.platform.marketplaceintegration.utils.impl.MarketplaceintegrationHttpUtilImpl.java

private void trustAllSSLCerts() throws NoSuchAlgorithmException, KeyManagementException {
    final TrustManager[] trustAllCerts = { new X509TrustManager() {
        @Override/*from   w  w w . ja  v a2s . c o  m*/
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

        @Override
        public void checkServerTrusted(final X509Certificate[] certs, final String authType) {
            //
        }
    } };
    final SSLContext sc = SSLContext.getInstance("SSL");
    final HostnameVerifier hv = new HostnameVerifier() {
        @Override
        public boolean verify(final String arg0, final SSLSession arg1) {
            return true;
        }
    };
    sc.init(null, trustAllCerts, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(hv);
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.SNIHttpClientConnection.java

private SSLContext getSSLContext() {
    if (ctx == null) {
        try {/*from  ww  w  . j a  v a2 s. c o m*/
            ctx = SSLContext.getInstance("TLS"); //$NON-NLS-1$
            ctx.init(null, null, null);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(HttpApacheText.get().unexpectedSSLContextException, e);
        } catch (KeyManagementException e) {
            throw new IllegalStateException(HttpApacheText.get().unexpectedSSLContextException, e);
        }
    }
    return ctx;
}

From source file:info.guardianproject.netcipher.NetCipher.java

/**
 * Get a {@link TlsOnlySocketFactory} from NetCipher, and specify whether
 * it should use a more compatible, but less strong, suite of ciphers.
 *
 * @see HttpsURLConnection#setDefaultSSLSocketFactory(SSLSocketFactory)
 *//*from   w ww .  j  a  v a 2  s .co  m*/
public static TlsOnlySocketFactory getTlsOnlySocketFactory(boolean compatible) {
    SSLContext sslcontext;
    try {
        sslcontext = SSLContext.getInstance("TLSv1");
        sslcontext.init(null, null, null);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException(e);
    } catch (KeyManagementException e) {
        throw new IllegalArgumentException(e);
    }
    return new TlsOnlySocketFactory(sslcontext.getSocketFactory(), compatible);
}

From source file:org.edeoliveira.oauth2.dropwizard.oauth2.auth.RestClientBuilder.java

private SSLContext getSSLContext() {
    TrustManager trustManagers[] = null;
    KeyManager keyManagers[] = null;

    try {/* ww  w. j  a  v a2 s  . c  o  m*/
        if (trustStore != null)
            trustManagers = new TrustManager[] {
                    new MyX509TrustManager(trustStore, trustStorePassword.toCharArray()) };
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    try {
        if (keyStore != null)
            keyManagers = new KeyManager[] { new MyX509KeyManager(keyStore, keyStorePassword.toCharArray()) };
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    SSLContext ctx = null;
    try {
        ctx = SSLContext.getInstance("SSL");
        ctx.init(keyManagers, trustManagers, null);
    } catch (java.security.GeneralSecurityException ex) {
        log.error("Error setting SSL configuration", ex);
    }
    return ctx;
}