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:com.meltmedia.cadmium.cli.AbstractAuthorizedOnly.java

/**
 * Sets the Commons HttpComponents to accept all SSL Certificates.
 * //  w  w w  . j  a va 2s. co m
 * @throws Exception
 * @return An instance of HttpClient that will accept all.
 */
protected static HttpClient httpClient() throws Exception {
    return HttpClients.custom().setHostnameVerifier(new AllowAllHostnameVerifier())
            .setSslcontext(SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s)
                        throws CertificateException {
                    return true;
                }
            }).build()).build();
}

From source file:nl.esciencecenter.osmium.JobLauncherService.java

/**
 * Enable insecure SSL in http client like self signed certificates.
 *
 * @param httpClient http client with secure SSL enabled
 * @throws NoSuchAlgorithmException when a particular cryptographic algorithm is requested but is not available in the environment.
 * @throws KeyManagementException if key management fails
 * @throws KeyStoreException if key store fails
 * @throws UnrecoverableKeyException if key is unrecoverable
 *///from   www.  java 2 s.  c  o m
public void useInsecureSSL(HttpClient httpClient)
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    SSLSocketFactory socketFactory;
    socketFactory = new SSLSocketFactory(new TrustStrategy() {

        public boolean isTrusted(final X509Certificate[] chain, String authType) throws CertificateException {
            // Oh, I am easy...
            return true;
        }

    }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    SchemeRegistry registry = httpClient.getConnectionManager().getSchemeRegistry();
    registry.register(new Scheme("https", HTTPS_PORT, socketFactory));
}

From source file:org.mycontroller.restclient.core.RestHttpClient.java

private CloseableHttpClient getHttpClientTrustAll() {
    SSLContextBuilder builder = new SSLContextBuilder();
    try {/*from w w  w  . jav a2 s  .  c om*/
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        builder.loadTrustMaterial(keyStore, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] trustedCert, String nameConstraints)
                    throws CertificateException {
                return true;
            }
        });
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(),
                new AnyHostnameVerifier());
        return HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(customRequestConfig)
                .build();
    } catch (Exception ex) {
        _logger.error("Exception, ", ex);
        throw new RuntimeException("Unable to create trust ANY http client. Error: " + ex.getMessage());
    }
}

From source file:com.spectralogic.ds3client.NetworkClientImpl.java

private static CloseableHttpClient createDefaultClient(final ConnectionDetails connectionDetails) {
    final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setDefaultMaxPerRoute(MAX_CONNECTION_PER_ROUTE);
    connectionManager.setMaxTotal(MAX_CONNECTION_TOTAL);

    if (connectionDetails.isHttps() && !connectionDetails.isCertificateVerification()) {
        try {/*from  w  ww. j  a v  a2s  . c  om*/

            final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(final X509Certificate[] chain, final String authType)
                        throws CertificateException {
                    return true;
                }
            }).useTLS().build();

            final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                    new AllowAllHostnameVerifier());
            return HttpClients.custom().setConnectionManager(connectionManager).setSSLSocketFactory(sslsf)
                    .build();

        } catch (final NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
            throw new SSLSetupException(e);
        }
    } else {
        return HttpClients.custom().setConnectionManager(connectionManager).build();
    }
}

From source file:gov.nih.nci.nbia.StandaloneDMV1.java

private static List<String> connectAndReadFromURL(URL url, String fileName) {
    List<String> data = null;
    DefaultHttpClient httpClient = null;
    TrustStrategy easyStrategy = new TrustStrategy() {
        @Override/*w  ww.j  a  v a  2 s  .com*/
        public boolean isTrusted(X509Certificate[] certificate, String authType) throws CertificateException {
            return true;
        }
    };
    try {
        // SSLContext sslContext = SSLContext.getInstance("SSL");
        // set up a TrustManager that trusts everything
        // sslContext.init(null, new TrustManager[] { new
        // EasyX509TrustManager(null)}, null);

        SSLSocketFactory sslsf = new SSLSocketFactory(easyStrategy,
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme httpsScheme = new Scheme("https", 443, sslsf);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(httpsScheme);
        schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(schemeRegistry);

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 50000);
        HttpConnectionParams.setSoTimeout(httpParams, new Integer(12000));
        httpClient = new DefaultHttpClient(ccm, httpParams);
        httpClient.setRoutePlanner(new ProxySelectorRoutePlanner(schemeRegistry, ProxySelector.getDefault()));
        // // Additions by lrt for tcia -
        // // attempt to reduce errors going through a Coyote Point
        // Equalizer load balance switch
        httpClient.getParams().setParameter("http.socket.timeout", new Integer(12000));
        httpClient.getParams().setParameter("http.socket.receivebuffer", new Integer(16384));
        httpClient.getParams().setParameter("http.tcp.nodelay", true);
        httpClient.getParams().setParameter("http.connection.stalecheck", false);
        // // end lrt additions

        HttpPost httpPostMethod = new HttpPost(url.toString());

        List<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>();
        postParams.add(new BasicNameValuePair("serverjnlpfileloc", fileName));
        UrlEncodedFormEntity query = new UrlEncodedFormEntity(postParams);
        httpPostMethod.setEntity(query);
        HttpResponse response = httpClient.execute(httpPostMethod);
        // int responseCode = response.getStatusLine().getStatusCode();
        // System.out.println("Response code for requesting datda file: " +
        // responseCode);
        InputStream inputStream = response.getEntity().getContent();
        data = IOUtils.readLines(inputStream);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
    }
    return data;
}

From source file:org.openhab.io.caldav.internal.Util.java

public static Sardine getConnection(CalDavConfig config) {
    if (config.isDisableCertificateVerification()) {
        if (config.getUrl().startsWith(HTTP_URL_PREFIX)) {
            log.error("do not use '{}' if no ssl is used",
                    CalDavLoaderImpl.PROP_DISABLE_CERTIFICATE_VERIFICATION);
        }//from   ww  w. ja v  a2 s.  c o  m
        log.trace(
                "connecting to caldav '{}' with disabled certificate verification (url={}, username={}, password={})",
                config.getKey(), config.getUrl(), config.getUsername(), config.getPassword());
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create()
                .setHostnameVerifier(new AllowAllHostnameVerifier());
        try {
            httpClientBuilder
                    .setSslcontext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                        @Override
                        public boolean isTrusted(X509Certificate[] arg0, String arg1)
                                throws CertificateException {
                            return true;
                        }
                    }).build());
        } catch (KeyManagementException e) {
            log.error("error verifying certificate", e);
        } catch (NoSuchAlgorithmException e) {
            log.error("error verifying certificate", e);
        } catch (KeyStoreException e) {
            log.error("error verifying certificate", e);
        }
        if (StringUtils.isEmpty(config.getUsername()) && StringUtils.isEmpty(config.getPassword())) {
            log.trace("connecting without credentials for '{}'", config.getKey());
            return new SardineImpl(httpClientBuilder);
        } else {
            return new SardineImpl(httpClientBuilder, config.getUsername(), config.getPassword());
        }
    } else {
        log.trace("connecting to caldav '{}' (url={}, username={}, password={})", config.getKey(),
                config.getUrl(), config.getUsername(), config.getPassword());
        if (StringUtils.isEmpty(config.getUsername()) && StringUtils.isEmpty(config.getPassword())) {
            log.trace("connecting without credentials for '{}'", config.getKey());
            return new SardineImpl();
        } else {
            return new SardineImpl(config.getUsername(), config.getPassword());
        }
    }
}

From source file:com.rsa.redchallenge.standaloneapp.utils.RestInteractor.java

private static DefaultHttpClient getHttpClient() {

    if (ApplicationConstant.SA_BASE_URL.contains("https")) {
        TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
            @Override/* w w w .j av a2s  .co  m*/
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return false;
            }
        };

        SSLSocketFactory sf = null;
        try {
            sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        } catch (NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException
                | KeyManagementException e) {
            e.printStackTrace();
        }

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", 443, sf));
        ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);

        return new DefaultHttpClient(ccm);
    } else {
        return new DefaultHttpClient();
    }
}

From source file:crawler.java.edu.uci.ics.crawler4j.fetcher.PageFetcher.java

public PageFetcher(CrawlConfig config) {
    super(config);

    RequestConfig requestConfig = RequestConfig.custom().setExpectContinueEnabled(false)
            .setCookieSpec(CookieSpecs.DEFAULT).setRedirectsEnabled(false)
            .setSocketTimeout(config.getSocketTimeout()).setConnectTimeout(config.getConnectionTimeout())
            .build();//from   w ww.  j av  a2 s . c  o m

    RegistryBuilder<ConnectionSocketFactory> connRegistryBuilder = RegistryBuilder.create();
    connRegistryBuilder.register("http", PlainConnectionSocketFactory.INSTANCE);
    if (config.isIncludeHttpsPages()) {
        try { // Fixing: https://code.google.com/p/crawler4j/issues/detail?id=174
            // By always trusting the ssl certificate
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(final X509Certificate[] chain, String authType) {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                    SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            connRegistryBuilder.register("https", sslsf);
        } catch (Exception e) {
            logger.warn("Exception thrown while trying to register https");
            logger.debug("Stacktrace", e);
        }
    }

    Registry<ConnectionSocketFactory> connRegistry = connRegistryBuilder.build();
    connectionManager = new PoolingHttpClientConnectionManager(connRegistry);
    connectionManager.setMaxTotal(config.getMaxTotalConnections());
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setDefaultRequestConfig(requestConfig);
    clientBuilder.setConnectionManager(connectionManager);
    clientBuilder.setUserAgent(config.getUserAgentString());
    clientBuilder.setDefaultHeaders(config.getDefaultHeaders());

    if (config.getProxyHost() != null) {
        if (config.getProxyUsername() != null) {
            BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(config.getProxyHost(), config.getProxyPort()),
                    new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()));
            clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }

        HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort());
        clientBuilder.setProxy(proxy);
        logger.debug("Working through Proxy: {}", proxy.getHostName());
    }

    httpClient = clientBuilder.build();
    if ((config.getAuthInfos() != null) && !config.getAuthInfos().isEmpty()) {
        doAuthetication(config.getAuthInfos());
    }

    if (connectionMonitorThread == null) {
        connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager);
    }
    connectionMonitorThread.start();
}

From source file:org.hawkular.client.RestFactory.java

public HttpClient getHttpClient() {
    SSLContextBuilder builder = new SSLContextBuilder();
    try {//from  w  w  w .jav a  2s . co m
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        builder.loadTrustMaterial(keyStore, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] trustedCert, String nameConstraints)
                    throws CertificateException {
                return true;
            }
        });
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        return httpclient;

    } catch (Exception ex) {
        _logger.error("Exception, ", ex);
        return null;
    }
}

From source file:com.spectralogic.ds3client.networking.NetworkClientImpl.java

private static CloseableHttpClient createInsecureSslHttpClient()
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
    final SSLContext sslContext = new SSLContextBuilder().useProtocol(INSECURE_SSL_PROTOCOL)
            .loadTrustMaterial(null, new TrustStrategy() {
                @Override//  ww w .ja  v a 2 s  . com
                public boolean isTrusted(final X509Certificate[] chain, final String authType)
                        throws CertificateException {
                    return true;
                }
            }).build();
    final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
            new NoopHostnameVerifier());

    final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
            .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslsf).build();
    final HttpClientConnectionManager connectionManager = createConnectionManager(socketFactoryRegistry);

    return HttpClients.custom().setConnectionManager(connectionManager).setSSLSocketFactory(sslsf).build();
}