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.craftercms.profile.impl.ProfileRestClientService.java

private DefaultHttpClient getHttpClient(int connectionTimeOut, int sockeTimeOut) {
    try {//ww w  . j  av a  2 s .c  o  m

        HttpParams httpParams = new BasicHttpParams();

        setParams(httpParams, connectionTimeOut, sockeTimeOut);

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

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", port, PlainSocketFactory.getSocketFactory()));
        registry.register(new Scheme("https", sslPort, sf));

        PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(registry);
        HttpHost localhost = new HttpHost(host, port);
        ccm.setMaxPerRoute(new HttpRoute(localhost), maxPerRoute);
        ccm.setMaxTotal(maxTotal);
        ccm.setDefaultMaxPerRoute(defaultMaxPerRoute);
        return new DefaultHttpClient(ccm, httpParams);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return new DefaultHttpClient();
    }
}

From source file:org.dasein.cloud.openstack.nova.os.AbstractMethod.java

protected @Nonnull HttpClient getClient() throws CloudException, InternalException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new InternalException("No context was defined for this request");
    }/*from w  w w.  j  av  a 2  s .  co  m*/
    String endpoint = ctx.getCloud().getEndpoint();

    if (endpoint == null) {
        throw new InternalException("No cloud endpoint was defined");
    }
    boolean ssl = endpoint.startsWith("https");

    HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    //noinspection deprecation
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setUserAgent(params, "");

    Properties p = ctx.getCustomProperties();

    if (p != null) {
        String proxyHost = p.getProperty("proxyHost");
        String proxyPort = p.getProperty("proxyPort");

        if (proxyHost != null) {
            int port = 0;

            if (proxyPort != null && proxyPort.length() > 0) {
                port = Integer.parseInt(proxyPort);
            }
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY,
                    new HttpHost(proxyHost, port, ssl ? "https" : "http"));
        }
    }
    DefaultHttpClient client = new DefaultHttpClient(params);

    if (provider.isInsecure()) {
        try {
            client.getConnectionManager().getSchemeRegistry()
                    .register(new Scheme("https", 443, new SSLSocketFactory(new TrustStrategy() {

                        public boolean isTrusted(X509Certificate[] x509Certificates, String s)
                                throws CertificateException {
                            return true;
                        }
                    }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)));
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
    return client;
}

From source file:org.fao.geonet.es.EsClient.java

@Override
public void afterPropertiesSet() throws Exception {
    if (StringUtils.isNotEmpty(serverUrl)) {
        JestClientFactory factory = new JestClientFactory();

        if (serverUrl.startsWith("https://")) {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                    return true;
                }//  w ww  .j  a va 2 s. co  m
            }).build();
            // skip hostname checks
            HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;

            SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                    hostnameVerifier);
            SchemeIOSessionStrategy httpsIOSessionStrategy = new SSLIOSessionStrategy(sslContext,
                    hostnameVerifier);
            factory.setHttpClientConfig(
                    new HttpClientConfig.Builder(this.serverUrl).defaultCredentials(username, password)
                            .multiThreaded(true).sslSocketFactory(sslSocketFactory) // this only affects sync calls
                            .httpsIOSessionStrategy(httpsIOSessionStrategy) // this only affects async calls
                            .readTimeout(-1).build());
        } else {
            factory.setHttpClientConfig(
                    new HttpClientConfig.Builder(this.serverUrl).multiThreaded(true).readTimeout(-1).build());
        }
        client = factory.getObject();
        //            Depends on java.lang.NoSuchFieldError: LUCENE_5_2_1
        //            client = new PreBuiltTransportClient(Settings.EMPTY)
        //                .addTransportAddress(new InetSocketTransportAddress(
        //                    InetAddress.getByName("127.0.0.1"), 9300));

        synchronized (EsClient.class) {
            instance = this;
        }
        activated = true;
    } else {
        Log.debug("geonetwork.index",
                String.format(
                        "No Elasticsearch URL defined '%s'. "
                                + "Check bean configuration. Statistics and dasboard will not be available.",
                        this.serverUrl));
    }
}

From source file:org.jenkinsci.plugins.stashNotifier.StashNotifier.java

/**
 * Returns the HttpClient through which the REST call is made. Uses an
 * unsafe TrustStrategy in case the user specified a HTTPS URL and
 * set the ignoreUnverifiedSSLPeer flag.
 * //from  w  ww.  ja v a  2  s .co m
 * @param logger   the logger to log messages to
 * @return         the HttpClient
 */
private HttpClient getHttpClient(PrintStream logger) {
    HttpClient client = null;
    boolean ignoreUnverifiedSSL = ignoreUnverifiedSSLPeer;
    DescriptorImpl descriptor = getDescriptor();
    if (!ignoreUnverifiedSSL) {
        ignoreUnverifiedSSL = descriptor.isIgnoreUnverifiedSsl();
    }
    if (getStashServerBaseUrl().startsWith("https") && ignoreUnverifiedSSL) {
        // add unsafe trust manager to avoid thrown
        // SSLPeerUnverifiedException
        try {
            TrustStrategy easyStrategy = new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            };

            SSLSocketFactory sslSocketFactory = new SSLSocketFactory(easyStrategy);
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("https", 443, sslSocketFactory));
            ClientConnectionManager connectionManager = new SingleClientConnManager(schemeRegistry);
            client = new DefaultHttpClient(connectionManager);
        } catch (NoSuchAlgorithmException nsae) {
            logger.println("Couldn't establish SSL context:");
            nsae.printStackTrace(logger);
        } catch (KeyManagementException kme) {
            logger.println("Couldn't initialize SSL context:");
            kme.printStackTrace(logger);
        } catch (KeyStoreException kse) {
            logger.println("Couldn't initialize SSL context:");
            kse.printStackTrace(logger);
        } catch (UnrecoverableKeyException uke) {
            logger.println("Couldn't initialize SSL context:");
            uke.printStackTrace(logger);
        } finally {
            if (client == null) {
                logger.println("Trying with safe trust manager, instead!");
                client = new DefaultHttpClient();
            }
        }
    } else {
        client = new DefaultHttpClient();
    }

    ProxyConfiguration proxy = Jenkins.getInstance().proxy;
    if (proxy != null && !proxy.name.isEmpty() && !proxy.name.startsWith("http")) {
        SchemeRegistry schemeRegistry = client.getConnectionManager().getSchemeRegistry();
        schemeRegistry.register(new Scheme("http", proxy.port, new PlainSocketFactory()));
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxy.name, proxy.port));
    }

    return client;
}

From source file:org.sonatype.nexus.plugins.webhook.WebHookNotifier.java

/**
 * Instantiate a new {@link HttpClient} instance, configured to accept all SSL certificates, and use proxy settings
 * from Nexus.// w  ww .  j ava 2s  .  c  o  m
 * 
 * @return an {@link HttpClient} instance - won't be null
 */
private HttpClient instantiateHttpClient() {
    DefaultHttpClient httpClient = new DefaultHttpClient();

    // configure user-agent
    HttpProtocolParams.setUserAgent(httpClient.getParams(), "Nexus WebHook Plugin");

    // configure SSL
    SSLSocketFactory socketFactory = null;
    try {
        socketFactory = new SSLSocketFactory(new TrustStrategy() {

            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (KeyManagementException e) {
        throw new RuntimeException(e);
    } catch (UnrecoverableKeyException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (KeyStoreException e) {
        throw new RuntimeException(e);
    }
    httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));

    // configure proxy
    if (proxySettings != null && proxySettings.isEnabled()) {
        HttpHost proxy = new HttpHost(proxySettings.getHostname(), proxySettings.getPort());
        if (UsernamePasswordRemoteAuthenticationSettings.class
                .isInstance(proxySettings.getProxyAuthentication())) {
            UsernamePasswordRemoteAuthenticationSettings proxyAuthentication = (UsernamePasswordRemoteAuthenticationSettings) proxySettings
                    .getProxyAuthentication();
            httpClient.getCredentialsProvider().setCredentials(
                    new AuthScope(proxySettings.getHostname(), proxySettings.getPort()),
                    new UsernamePasswordCredentials(proxyAuthentication.getUsername(),
                            proxyAuthentication.getPassword()));
        }
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    return httpClient;
}