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 javax.net.ssl.SSLSocketFactory socketfactory,
        final X509HostnameVerifier hostnameVerifier) 

Source Link

Usage

From source file:org.jboss.as.test.http.util.HttpClientUtils.java

/**
 * Returns https ready client./*from ww w . jav a  2  s  . com*/
 *
 * @param base
 * @return
 */
public static HttpClient wrapHttpsClient(HttpClient base) {
    try {
        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, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:com.payu.sdk.helper.WebClientDevWrapper.java

/**
 * Wraps a default and secure httpClient
 *
 * @param base the original httpClient/*from w  w w .j a va 2  s. c om*/
 * @return the hhtpClient wrapped
 * @throws ConnectionException
 */
public static HttpClient wrapClient(HttpClient base) throws ConnectionException {
    try {
        SSLContext ctx = SSLContext.getInstance(Constants.SSL_PROVIDER);

        X509TrustManager tm = new X509TrustManager() {

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

            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
                    throws java.security.cert.CertificateException {
            }

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

        };

        ctx.init(null, new TrustManager[] { tm }, null);

        SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();

        sr.register(new Scheme("https", Constants.HTTPS_PORT, ssf));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        throw new ConnectionException("Invalid SSL connection", ex);
    }
}

From source file:org.talend.core.utils.StudioSSLContextProvider.java

public static boolean setSSLSystemProperty(boolean isPreference) {
    try {/*w  w  w . ja  v a2s . com*/
        buildContext();
        if (!isPreference && context == null) {
            return false;
        }
        changeProperty();
        Executor.unregisterScheme("https");
        SSLSocketFactory factory = new SSLSocketFactory(context,
                SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        Executor.registerScheme(new Scheme("https", 443, factory));
    } catch (Exception e) {
        if (isPreference) {
            changeProperty();
            Executor.unregisterScheme("https");
        }
        ExceptionHandler.process(new Exception("Please check the SSL settings in Preference>Talend>SSL", e));
        return false;
    }
    return true;
}

From source file:com.googlecode.noweco.webmail.httpclient.UnsecureHttpClientFactory.java

public DefaultHttpClient createUnsecureHttpClient(final HttpHost proxy) {
    DefaultHttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager());
    SchemeRegistry schemeRegistry = httpclient.getConnectionManager().getSchemeRegistry();
    schemeRegistry.unregister("https");
    try {//from   w  w w  .  j  a  v  a 2s  . c  o  m
        SSLContext instance = SSLContext.getInstance("TLS");
        TrustManager tm = UnsecureX509TrustManager.INSTANCE;
        instance.init(null, new TrustManager[] { tm }, null);
        schemeRegistry.register(new Scheme("https", 443,
                new SSLSocketFactory(instance, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)));
    } catch (Exception e) {
        throw new RuntimeException("TLS issue", e);
    }
    httpclient.removeResponseInterceptorByClass(ResponseProcessCookies.class);
    httpclient.addResponseInterceptor(new UnsecureResponseProcessCookies());
    HttpParams params = httpclient.getParams();
    if (proxy != null) {
        ConnRouteParams.setDefaultProxy(params, proxy);
    }
    HttpConnectionParams.setSoTimeout(params, 7000);
    return httpclient;
}

From source file:com.linkedin.pinot.monitor.util.HttpUtils.java

/**
 * {//from  ww  w .  j ava  2s.  c  om
 text: "",
 attachments: [{
 title: "",
 description: "??",
 url: "",
 color: "warning|info|primary|error|muted|success"
 }]
 displayUser: {
 name: "??",
 avatarUrl: "??"
 }
 }
 * @param text
 * @return
 */

public static void postMonitorData(String text) {
    SSLContext sslContext = null;
    HttpClient client = new DefaultHttpClient();
    try {
        sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                    throws java.security.cert.CertificateException {

            }

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

            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } }, new SecureRandom());
    } catch (Exception e) {
        e.printStackTrace();
    }

    SSLSocketFactory ssf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm = client.getConnectionManager();
    SchemeRegistry sr = ccm.getSchemeRegistry();
    sr.register(new Scheme("https", 443, ssf));

    HttpPost httpPost = new HttpPost("https://hooks.pubu.im/services/1d2d2rwn8wb6sx");

    Map<String, Object> map = new HashMap<String, Object>();
    Map<String, String> sender = new HashMap<String, String>();
    sender.put("name", "Monitor");
    map.put("displayUser", sender);
    List<String> list = new ArrayList<String>();
    map.put("attachments", list);

    try {
        map.put("text", text);
        InputStreamEntity httpentity = new InputStreamEntity(
                new ByteArrayInputStream(mapper.writeValueAsBytes(map)), mapper.writeValueAsBytes(map).length);
        httpPost.setEntity(httpentity);
        httpPost.addHeader("Content-Type", "application/json");
        HttpResponse response = client.execute(httpPost);
        String result = EntityUtils.toString(response.getEntity());
        System.out.println(result);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        //
    }

}

From source file:org.lorislab.armonitor.jira.client.JIRAClient.java

/**
 * Creates the JIRA client./*  w w w  . j av a 2  s  . co  m*/
 *
 * @param server the server URL.
 * @param username the username.
 * @param password the password.
 * @param auth the authentication flag.
 * @throws Exception if the method fails.
 */
public JIRAClient(String server, String username, char[] password, boolean auth) throws Exception {
    this.server = server;

    HttpClient httpClient = new DefaultHttpClient();
    if (server.startsWith(HTTPS)) {
        SSLSocketFactory sslSocketFactory = new SSLSocketFactory(new TrustSelfSignedStrategy(),
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        httpClient.getConnectionManager().getSchemeRegistry()
                .register(new Scheme(HTTPS, 443, sslSocketFactory));
    }
    if (auth) {
        this.executor = new JiraApacheHttpClient4Executor(username, password, httpClient);
    }
}

From source file:com.almende.eve.transport.http.ApacheHttpClient.java

/**
 * Instantiates a new apache http client.
 *
 *//* w w  w.  j a  va  2s  .co m*/
private ApacheHttpClient() {

    // Allow self-signed SSL certificates:
    final TrustStrategy trustStrategy = new TrustSelfSignedStrategy();
    final X509HostnameVerifier hostnameVerifier = new AllowAllHostnameVerifier();
    final SchemeRegistry schemeRegistry = SchemeRegistryFactory.createDefault();

    SSLSocketFactory sslSf;
    try {
        sslSf = new SSLSocketFactory(trustStrategy, hostnameVerifier);
        final Scheme https = new Scheme("https", 443, sslSf);
        schemeRegistry.register(https);
    } catch (Exception e) {
        LOG.warning("Couldn't init SSL socket, https not supported!");
    }

    // Work with PoolingClientConnectionManager
    final ClientConnectionManager connection = new PoolingClientConnectionManager(schemeRegistry);

    // Provide eviction thread to clear out stale threads.
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                while (true) {
                    synchronized (this) {
                        wait(5000);
                        connection.closeExpiredConnections();
                        connection.closeIdleConnections(30, TimeUnit.SECONDS);
                    }
                }
            } catch (final InterruptedException ex) {
            }
        }
    }).start();

    // generate httpclient
    httpClient = new DefaultHttpClient(connection);

    // Set cookie policy and persistent cookieStore
    try {
        httpClient.setCookieStore(new MyCookieStore());
    } catch (final Exception e) {
        LOG.log(Level.WARNING, "Failed to initialize persistent cookieStore!", e);
    }
    final HttpParams params = httpClient.getParams();

    params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
    params.setParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
    params.setParameter(CoreConnectionPNames.TCP_NODELAY, true);
    httpClient.setParams(params);
}

From source file:org.n52.supervisor.checks.json.JsonServiceCheck.java

protected HttpClient createClient() throws Exception {
    DefaultHttpClient result = new DefaultHttpClient();
    SchemeRegistry sr = result.getConnectionManager().getSchemeRegistry();

    SSLSocketFactory sslsf = new SSLSocketFactory(new TrustStrategy() {

        @Override/*from ww w  . j a  va  2  s  .c  o  m*/
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }, new AllowAllHostnameVerifier());

    Scheme httpsScheme2 = new Scheme("https", 443, sslsf);
    sr.register(httpsScheme2);

    return result;
}

From source file:com.betfair.testing.utils.cougar.manager.HttpPageManager.java

public int getPage(HttpPageBean bean) {

    // Get bean properties
    String requestedProtocol = bean.getProtocol();
    String requestedHost = bean.getHost();
    int requestedPort = bean.getPort();
    String requestedLink = bean.getLink();
    String username = bean.getAuthusername();
    String password = bean.getAuthpassword();

    final SSLSocketFactory sf = new SSLSocketFactory(createEasySSLContext(),
            SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme https = new Scheme("https", 9999, sf);

    // Set up httpClient to use given auth details and protocol
    DefaultHttpClient client = new DefaultHttpClient();
    client.getConnectionManager().getSchemeRegistry().register(https);
    client.getCredentialsProvider().setCredentials(new AuthScope("localhost", AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(username, password));

    int status = -1;

    InputStream inputStream = null;
    // Make the request
    try {/*from   w ww . j  a  v a 2  s .  c om*/
        final HttpGet httpget = new HttpGet(
                URIUtils.createURI(requestedProtocol, requestedHost, requestedPort, requestedLink, null, null));
        final HttpResponse httpResponse = client.execute(httpget);
        inputStream = httpResponse.getEntity().getContent();
        status = httpResponse.getStatusLine().getStatusCode();

        if (status == HttpStatus.SC_OK) {
            bean.setPageLoaded(true);

            byte[] buffer = new byte[(int) httpResponse.getEntity().getContentLength()];
            int read;
            int count = 0;
            while ((read = inputStream.read()) != -1) {
                buffer[count] = (byte) read;
                count++;
            }
            bean.setPageText(new String(buffer, "UTF-8"));
            bean.setBuffer(buffer);
        }
    } catch (IOException e1) {
        return -1;
    } catch (URISyntaxException e) {
        return -1;
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }

    return status;
}

From source file:com.allstate.client.ssl.SSLUtils.java

public static SSLSocketFactory getMergedSocketFactory(Security securityOne, Security securityTwo)
        throws GeneralSecurityException {
    X509KeyManager keyManagerOne = getKeyManager(securityOne.getKeyStore(), securityOne.getKeyStorePassword());
    X509KeyManager keyManagerTwo = getKeyManager(securityTwo.getKeyStore(), securityTwo.getKeyStorePassword());

    X509TrustManager trustManager = getMultiTrustManager(getTrustManager(securityOne.getTrustStore()),
            getTrustManager(securityTwo.getTrustStore()));

    SSLContext context = SSLContext.getInstance(securityOne.getSslContextProtocol());
    boolean strictHostVerification = securityOne.isStrictHostVerification()
            && securityTwo.isStrictHostVerification();

    context.init(new KeyManager[] { keyManagerOne, keyManagerTwo }, new TrustManager[] { trustManager },
            new SecureRandom());
    X509HostnameVerifier verifier = strictHostVerification ? SSLSocketFactory.STRICT_HOSTNAME_VERIFIER
            : SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    return new SSLSocketFactory(context, verifier);
}