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:jetbrains.teamcilty.github.api.impl.HttpClientWrapperImpl.java

public HttpClientWrapperImpl()
        throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    final String serverVersion = ServerVersionHolder.getVersion().getDisplayVersion();

    final HttpParams ps = new BasicHttpParams();

    DefaultHttpClient.setDefaultHttpParams(ps);
    final int timeout = TeamCityProperties.getInteger("teamcity.github.http.timeout", 300 * 1000);
    HttpConnectionParams.setConnectionTimeout(ps, timeout);
    HttpConnectionParams.setSoTimeout(ps, timeout);
    HttpProtocolParams.setUserAgent(ps, "JetBrains TeamCity " + serverVersion);

    final SchemeRegistry schemaRegistry = SchemeRegistryFactory.createDefault();
    final SSLSocketFactory sslSocketFactory = new SSLSocketFactory(new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return !TeamCityProperties.getBoolean("teamcity.github.verify.ssl.certificate");
        }/*from  ww  w  . j  av  a2  s  .c o  m*/
    });
    schemaRegistry.register(new Scheme("https", 443, sslSocketFactory));

    final DefaultHttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager(schemaRegistry),
            ps);

    setupProxy(httpclient);

    httpclient.setRoutePlanner(new ProxySelectorRoutePlanner(
            httpclient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()));
    httpclient.addRequestInterceptor(new RequestAcceptEncoding());
    httpclient.addResponseInterceptor(new ResponseContentEncoding());
    httpclient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, true));

    myClient = httpclient;
}

From source file:co.cask.cdap.gateway.router.NettyRouterHttpsTest.java

@Override
protected DefaultHttpClient getHTTPClient() throws Exception {
    SSLContext sslContext = SSLContext.getInstance("SSL");

    // set up a TrustManager that trusts everything
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
        @Override//from  w ww  .j av  a 2s.  c  o m
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                throws CertificateException {
            //
        }

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

    } }, new SecureRandom());

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

    // apache HttpClient version >4.2 should use BasicClientConnectionManager
    ClientConnectionManager cm = new BasicClientConnectionManager(schemeRegistry);
    return new DefaultHttpClient(cm);
}

From source file:com.ovea.facebook.client.DefaultFacebookClient.java

public DefaultFacebookClient(String client_id, String client_secret, String redirect_uri) {
    this.clientId = client_id;
    this.clientSecret = client_secret;
    this.redirectUri = redirect_uri;
    try {/*  w  w  w .j a  v a  2  s . com*/
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                    throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
                    throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } }, new SecureRandom());
        sslSocketFactory = new SSLSocketFactory(sslContext);
        //noinspection deprecation
        sslSocketFactory.setHostnameVerifier(new X509HostnameVerifier() {
            @Override
            public void verify(String host, SSLSocket ssl) throws IOException {
            }

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

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

            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });
    } catch (NoSuchAlgorithmException e) {
        throw new FacebookException(e.getMessage(), e);
    } catch (KeyManagementException e) {
        throw new FacebookException(e.getMessage(), e);
    }
}

From source file:at.diamonddogs.net.SSLHelper.java

/**
 * Register a keystore with SSL (APACHE)
 * /* w w  w.  ja  v  a  2s .  co  m*/
 * @param c
 *            a {@link Context}
 * @param resourceId
 *            the resource id of the keystore
 * @param password
 *            the password of the keystore
 * @return true on success, false otherwise
 */
public boolean initSSLFactoryApache(Context c, int resourceId, String password) {
    try {
        if (c == null || resourceId == -1 || password == null) {
            LOGGER.info("No keystore specified, using alltrust");
            makeAllTrustManagerForApache();
            return true;
        } else {
            KeyStore store = getKeyStore(c, resourceId, password);
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            SSL_FACTORY_APACHE = new SSLSocketFactory(store);
            schemeRegistry.register(new Scheme("https", SSL_FACTORY_APACHE, 443));
            sslState.trustAll = false;
            return true;
        }
    } catch (Throwable tr) {
        LOGGER.warn("Error initializing SSLFactoryApache, trusting all certs", tr);
        try {
            makeAllTrustManagerForApache();
            sslState.tr = tr;
            return true;
        } catch (Throwable tr1) {
            sslState.tr1 = tr1;
            sslState.sslOk = false;
            LOGGER.warn("Error trusting all certs, no ssl connection possible", tr);
        }
        return false;
    }
}

From source file:org.structr.android.restclient.StructrConnector.java

private static SSLSocketFactory createSslSocketFactory(Context context, int resourceId,
        String keyStorePassword) {

    try {/*www.j a  v a 2 s .  com*/
        KeyStore trusted = KeyStore.getInstance("BKS");
        InputStream in = context.getResources().openRawResource(resourceId);

        try {
            trusted.load(in, keyStorePassword.toCharArray());

        } finally {
            in.close();
        }

        return new SSLSocketFactory(trusted);

    } catch (Exception e) {
        throw new AssertionError(e);
    }
}

From source file:jetbrains.buildServer.commitPublisher.github.api.impl.HttpClientWrapperImpl.java

public HttpClientWrapperImpl()
        throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    final String serverVersion = ServerVersionHolder.getVersion().getDisplayVersion();

    final HttpParams ps = new BasicHttpParams();

    DefaultHttpClient.setDefaultHttpParams(ps);
    final int timeout = TeamCityProperties.getInteger("teamcity.github.http.timeout", 300 * 1000);
    HttpConnectionParams.setConnectionTimeout(ps, timeout);
    HttpConnectionParams.setSoTimeout(ps, timeout);
    HttpProtocolParams.setUserAgent(ps, "JetBrains TeamCity " + serverVersion);

    final SchemeRegistry schemaRegistry = SchemeRegistryFactory.createDefault();
    final SSLSocketFactory sslSocketFactory = new SSLSocketFactory(new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return !TeamCityProperties.getBoolean("teamcity.github.verify.ssl.certificate");
        }/*w  ww  .  j  a v  a  2 s. c  o  m*/
    }) {
        @Override
        public Socket connectSocket(int connectTimeout, Socket socket, HttpHost host,
                InetSocketAddress remoteAddress, InetSocketAddress localAddress, HttpContext context)
                throws IOException {
            if (socket instanceof SSLSocket) {
                try {
                    PropertyUtils.setProperty(socket, "host", host.getHostName());
                } catch (Exception ex) {
                    LOG.warn(String.format(
                            "A host name is not passed to SSL connection for the purpose of supporting SNI due to the following exception: %s",
                            ex.toString()));
                }
            }
            return super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context);
        }
    };
    schemaRegistry.register(new Scheme("https", 443, sslSocketFactory));

    final DefaultHttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager(schemaRegistry),
            ps);

    setupProxy(httpclient);

    httpclient.setRoutePlanner(new ProxySelectorRoutePlanner(
            httpclient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()));
    httpclient.addRequestInterceptor(new RequestAcceptEncoding());
    httpclient.addResponseInterceptor(new ResponseContentEncoding());
    httpclient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, true));

    myClient = httpclient;
}

From source file:org.globus.crux.security.ClientTest.java

/**
 * Test a client using valid credentials
 * //ww w  .  j a  v  a  2  s  . c o  m
 * @throws Exception
 *             if this happens, the test fails.
 */
@Test
public void testValid() throws Exception {
    SSLConfigurator config = getConfig("classpath:/mykeystore.properties");
    SSLSocketFactory fac = new SSLSocketFactory(config.getSSLContext());
    fac.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    DefaultHttpClient httpclient = new DefaultHttpClient();
    Scheme scheme = new Scheme("https", fac, getPort());
    httpclient.getConnectionManager().getSchemeRegistry().register(scheme);
    HttpGet httpget = new HttpGet("https://localhost/");
    System.out.println("executing request" + httpget.getRequestLine());

    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    System.out.println("----------------------------------------");
    System.out.println(response.getStatusLine());
    if (entity != null) {
        System.out.println("Response content length: " + entity.getContentLength());
    }
    if (entity != null) {
        entity.consumeContent();
    }

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system stores
    httpclient.getConnectionManager().shutdown();
}

From source file:org.openiot.gsn.http.rest.PushRemoteWrapper.java

public boolean initialize() {

    try {//from  www .  j  a  v  a2s  .c o m
        initParams = new RemoteWrapperParamParser(getActiveAddressBean(), true);
        uid = Math.random();

        postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair(PushDelivery.NOTIFICATION_ID_KEY, Double.toString(uid)));
        postParameters.add(
                new BasicNameValuePair(PushDelivery.LOCAL_CONTACT_POINT, initParams.getLocalContactPoint()));
        // Init the http client
        if (initParams.isSSLRequired()) {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(new FileInputStream(new File("conf/servertestkeystore")),
                    Main.getContainerConfig().getSSLKeyStorePassword().toCharArray());
            SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
            socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            int sslPort = Main.getContainerConfig().getSSLPort() > 0 ? Main.getContainerConfig().getSSLPort()
                    : ContainerConfig.DEFAULT_SSL_PORT;
            Scheme sch = new Scheme("https", socketFactory, sslPort);
            httpclient.getConnectionManager().getSchemeRegistry().register(sch);
        }
        Scheme plainsch = new Scheme("http", PlainSocketFactory.getSocketFactory(),
                Main.getContainerConfig().getContainerPort());
        httpclient.getConnectionManager().getSchemeRegistry().register(plainsch);
        //
        lastReceivedTimestamp = initParams.getStartTime();
        structure = registerAndGetStructure();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        NotificationRegistry.getInstance().removeNotification(uid);
        return false;
    }

    return true;
}

From source file:org.gw2InfoViewer.factories.HttpsConnectionFactory.java

public static HttpClient getHttpsClient(Certificate[] sslCertificate) {
    DefaultHttpClient httpClient;//from w  w w  .  j a  va2s.c o  m

    httpClient = new DefaultHttpClient();
    try {
        TrustManagerFactory tf = TrustManagerFactory.getInstance("X509");
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null);
        for (int i = 0; i < sslCertificate.length; i++) {
            ks.setCertificateEntry("StartCom" + i, sslCertificate[i]);
        }

        tf.init(ks);
        TrustManager[] tm = tf.getTrustManagers();

        SSLContext sslCon = SSLContext.getInstance("SSL");
        sslCon.init(null, tm, new SecureRandom());
        SSLSocketFactory socketFactory = new SSLSocketFactory(ks);
        Scheme sch = new Scheme("https", 443, socketFactory);

        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException
            | KeyManagementException | UnrecoverableKeyException ex) {
        Logger.getLogger(HttpsConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);
    }

    return httpClient;
}