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

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

Introduction

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

Prototype

TrustStrategy

Source Link

Usage

From source file:org.eclipse.lyo.testsuite.server.trsutils.EasySSLClient.java

private SSLSocketFactory getEasySSLSocketFactory()
        throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
    TrustStrategy trustStrategy = new TrustStrategy() {
        @Override//from   www.j  ava  2  s  .com
        public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            return true; // Accept Self-Signed Certs
        }
    };

    SSLSocketFactory sslSocketFactory = null;

    //Bypass check for hostname verification
    sslSocketFactory = new SSLSocketFactory(trustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    return sslSocketFactory;
}

From source file:org.jboss.arquillian.ce.httpclient.HttpClientBuilder.java

public HttpClientBuilder untrustedConnectionClientBuilder() throws Exception {
    // setup a Trust Strategy that allows all certificates.
    ////from  w ww  .  j a  v  a2  s  .co m
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        public boolean isTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                throws java.security.cert.CertificateException {
            return true;
        }

    }).build();
    builder.setSslcontext(sslContext);

    // don't check Hostnames, either.
    //      -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken
    HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    // here's the special part:
    //      -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
    //      -- and create a Registry, to register it.
    //
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
            (X509HostnameVerifier) hostnameVerifier);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();

    // now, we create connection-manager using our Registry.
    //      -- allows multi-threaded use
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    builder.setConnectionManager(connMgr);

    // finally, build the HttpClient;
    //      -- done!
    return this;
}

From source file:sachin.spider.WebSpider.java

/**
 *
 * @param config/*  ww  w .j a v a  2s  .c o m*/
 * @param latch
 */
@SuppressWarnings("deprecation")
public void setValues(SpiderConfig config, CountDownLatch latch) {
    try {
        this.config = config;
        this.latch = latch;
        HttpClientBuilder builder = HttpClientBuilder.create();
        builder.setUserAgent(config.getUserAgentString());
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

            @Override
            public boolean isTrusted(java.security.cert.X509Certificate[] xcs, String string)
                    throws java.security.cert.CertificateException {
                return true;
            }
        }).build();
        builder.setSslcontext(sslContext);
        HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                hostnameVerifier);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory).build();
        cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        cm.setDefaultMaxPerRoute(config.getTotalSpiders() * 2);
        cm.setMaxTotal(config.getTotalSpiders() * 2);
        if (config.isAuthenticate()) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(config.getUsername(), config.getPassword()));
            httpclient = HttpClients.custom().setUserAgent(config.getUserAgentString())
                    .setDefaultCredentialsProvider(credentialsProvider).setConnectionManager(cm).build();

        } else {
            httpclient = HttpClients.custom().setConnectionManager(cm).setUserAgent(config.getUserAgentString())
                    .build();
        }
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
        Logger.getLogger(WebSpider.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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   w  w  w .  j  a v a  2  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:org.xdi.oxd.license.client.LicenseClientTest.java

public static HttpClient createHttpClientTrustAll()
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    //        System.setProperty("javax.net.debug", "SSL,handshake,trustmanager");

    //        SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy() {
    //            @Override
    //            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    //                return true;
    //            }
    //        }, new AllowAllHostnameVerifier());

    SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy() {
        @Override/*from w  ww  .  jav  a 2  s .  c o m*/
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    }, 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;
        }
    });

    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    registry.register(new Scheme("https", 443, sf));
    ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);
    return new DefaultHttpClient(ccm);
}

From source file:com.seajas.search.contender.http.ExclusiveConnectionManager.java

/**
 * Create a scheme registry which either trusts all certificates, or uses the HttpClient default.
 *
 * @param trustAllCertificates//from w  w  w  .  j  a  v  a 2  s. c  o  m
 * @return SchemeRegistry
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 * @throws KeyStoreException
 * @throws UnrecoverableKeyException
 */
private static SchemeRegistry createSchemeRegistry(final Boolean trustAllCertificates)
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    if (trustAllCertificates) {
        SchemeRegistry registry = new SchemeRegistry();

        if (logger.isInfoEnabled())
            logger.info("Trusting all certificates");

        X509HostnameVerifier hostnameVerifier = new X509HostnameVerifier() {
            @Override
            public void verify(String host, SSLSocket ssl) throws IOException {
                // Do nothing
            }

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

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

            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        };

        registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        registry.register(new Scheme("https", 443, new SSLSocketFactory(new TrustStrategy() {
            @Override
            public boolean isTrusted(final X509Certificate[] chain, final String authType)
                    throws CertificateException {
                return true;
            }
        }, hostnameVerifier)/* {
                            @Override
                            public Socket connectSocket(final Socket socket,
                            final InetSocketAddress remoteAddress,
                            final InetSocketAddress localAddress,
                            final HttpParams param) throws IOException, UnknownHostException, ConnectTimeoutException {
                            if (socket instanceof SSLSocket) {
                            try {
                            if (logger.isDebugEnabled()) {
                            String currentHost = null;
                                    
                            logger.debug("This JVM seems to potentially not support SNI - trying to fix");
                                    
                            try {
                            currentHost = (String) FieldUtils.getFieldValue(socket, "host");
                            } catch (IllegalAccessException e) {
                            logger.debug("Unable to access field 'host' from the underlaying SSLSocket");
                            }
                                    
                            logger.debug("Overriding default socket hostname of " + (currentHost != null ? currentHost : "(null)") + " with " + remoteAddress.getHostName());
                            }
                                    
                            PropertyUtils.setProperty(socket, "host", remoteAddress.getHostName());
                            } catch (NoSuchMethodException e) {
                            if (logger.isDebugEnabled())
                            logger.debug(e);
                            } catch (IllegalAccessException e) {
                            if (logger.isDebugEnabled())
                            logger.debug(e);
                            } catch (InvocationTargetException e) {
                            if (logger.isDebugEnabled())
                            logger.debug(e);
                            }
                            } else {
                            if (logger.isDebugEnabled())
                            logger.debug("This is not the JVM we're looking for - should support SNI");
                            }
                                    
                            return super.connectSocket(socket, remoteAddress, localAddress, param);
                            }
                            } */));

        return registry;
    } else
        return SchemeRegistryFactory.createDefault();
}

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");
        }// www .  java 2s . c  om
    }) {
        @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.jutge.joc.porra.controller.base.UpdateController.java

private String getUpdateJson() {
    try {// ww  w .ja  v  a  2  s  .co  m
        // battle-royale.jutge.org has an untrusted cert
        final TrustStrategy easyStrategy = new TrustStrategy() {
            @Override
            public boolean isTrusted(final X509Certificate[] certificate, final String authType)
                    throws CertificateException {
                return true;
            }
        };
        final SSLSocketFactory socketFactory = new SSLSocketFactory(easyStrategy,
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        final SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", 443, socketFactory));
        final ClientConnectionManager connectionManager = new PoolingClientConnectionManager(registry);
        // Get data
        final HttpClient httpClient = new DefaultHttpClient(connectionManager);
        final HttpGet get = new HttpGet(UPDATE_URL);
        final HttpResponse response = httpClient.execute(get);
        final HttpEntity entity = response.getEntity();
        final String responseBody = EntityUtils.toString(entity);
        return responseBody;
    } catch (Exception exception) {
        this.logger.error(exception.getMessage());
    }
    return null;
}