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.emc.storageos.driver.dellsc.scapi.rest.RestClient.java

/**
 * Instantiates a new Rest client.//from w w w. jav a  2  s .com
 *
 * @param host Host name or IP address of the Dell Storage Manager server.
 * @param port Port the DSM data collector is listening on.
 * @param user The DSM user name to use.
 * @param password The DSM password.
 */
public RestClient(String host, int port, String user, String password) {
    this.baseUrl = String.format("https://%s:%d/api/rest", host, port);

    try {
        // Set up auth handling
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(host, port),
                new UsernamePasswordCredentials(user, password));
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        HttpHost target = new HttpHost(host, port, "https");
        authCache.put(target, basicAuth);

        // Set up our context
        httpContext = HttpClientContext.create();
        httpContext.setCookieStore(new BasicCookieStore());
        httpContext.setAuthCache(authCache);

        // Create our HTTPS client
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        this.httpClient = HttpClients.custom().setHostnameVerifier(new AllowAllHostnameVerifier())
                .setDefaultCredentialsProvider(credsProvider).setSSLSocketFactory(sslSocketFactory).build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        // Hopefully default SSL handling is set up
        LOG.warn("Failed to configure HTTP handling, falling back to default handler.");
        LOG.debug("Config error: {}", e);
        this.httpClient = HttpClients.createDefault();
    }
}

From source file:io.github.cidisk.indexcrawler.fetcher.PageFetcher.java

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

    RequestConfig requestConfig = RequestConfig.custom().setExpectContinueEnabled(false)
            .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).setRedirectsEnabled(false)
            .setSocketTimeout(config.getSocketTimeout()).setConnectTimeout(config.getConnectionTimeout())
            .build();/*from  w  ww.  ja  v a 2s  .  c om*/

    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());

    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:com.crawler.app.fetcher.PageFetcher.java

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

    RequestConfig requestConfig = RequestConfig.custom().setExpectContinueEnabled(false)
            .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).setRedirectsEnabled(false)
            //.setRelativeRedirectsAllowed(true)
            .setSocketTimeout(config.getSocketTimeout()).setConnectTimeout(config.getConnectionTimeout())
            .build();/*from  www  .  ja v a 2  s .com*/

    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());

    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:crawler.PageFetcher.java

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

    RequestConfig requestConfig = RequestConfig.custom().setExpectContinueEnabled(false)
            .setCookieSpec(config.getCookiePolicy()).setRedirectsEnabled(false)
            .setSocketTimeout(config.getSocketTimeout()).setConnectTimeout(config.getConnectionTimeout())
            .build();//from  www .j a  v a 2 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 SniSSLConnectionSocketFactory(sslContext,
                    NoopHostnameVerifier.INSTANCE);
            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 SniPoolingHttpClientConnectionManager(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:de.comlineag.snc.webcrawler.fetcher.PageFetcher.java

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

    RequestConfig requestConfig = RequestConfig.custom().setExpectContinueEnabled(false)
            .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).setRedirectsEnabled(false)
            .setSocketTimeout(config.getSocketTimeout()).setConnectTimeout(config.getConnectionTimeout())
            .build();//from   w  ww . j  av  a 2  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.debug("Exception thrown while trying to register https:", 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());
    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);
    }
    clientBuilder.addInterceptorLast(new HttpResponseInterceptor() {
        @Override
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            Header contentEncoding = entity.getContentEncoding();
            if (contentEncoding != null) {
                HeaderElement[] codecs = contentEncoding.getElements();
                for (HeaderElement codec : codecs) {
                    if (codec.getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }
        }
    });

    httpClient = clientBuilder.build();

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

From source file:org.envirocar.wps.TrackToCSVProcess.java

protected HttpClient createClient() throws IOException {
    SSLSocketFactory sslsf;//from ww  w . ja  v  a2 s . c o m
    try {
        sslsf = new SSLSocketFactory(new TrustStrategy() {

            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                // XXX !!!
                return true;
            }

        }, new StrictHostnameVerifier());
    } catch (KeyManagementException e) {
        throw new IOException(e);
    } catch (UnrecoverableKeyException e) {
        throw new IOException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new IOException(e);
    } catch (KeyStoreException e) {
        throw new IOException(e);
    }
    Scheme httpsScheme2 = new Scheme("https", 443, sslsf);

    DefaultHttpClient client = new DefaultHttpClient();
    client.getConnectionManager().getSchemeRegistry().register(httpsScheme2);

    return client;
}

From source file:nl.esciencecenter.octopus.webservice.JobLauncherService.java

/**
 * Enable insecure SSL in http client like self signed certificates.
 *
 * @param httpClient//from   w ww . j  a v  a 2  s  .c om
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 * @throws KeyStoreException
 * @throws UnrecoverableKeyException
 */
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;
        }

    }, org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

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

From source file:org.jboss.as.test.integration.management.interfaces.HttpManagementInterface.java

private static HttpClient createHttpClient(String host, int port, String username, String password) {
    PoolingClientConnectionManager connectionPool = new PoolingClientConnectionManager();
    DefaultHttpClient httpClient = new DefaultHttpClient(connectionPool);
    SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    try {//from w  w  w .j a v a2 s . c o  m
        schemeRegistry.register(new Scheme("https", 443, new SSLSocketFactory(new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        }, new AllowAllHostnameVerifier())));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    httpClient.setHttpRequestRetryHandler(new StandardHttpRequestRetryHandler(5, true));
    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(host, port, MANAGEMENT_REALM, AuthPolicy.DIGEST),
            new UsernamePasswordCredentials(username, password));

    return httpClient;
}

From source file:com.zextras.zimbradrive.CreateTempAttachmentFileHttpHandler.java

private void doInternalPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    Account account = mBackendUtils.assertAccountFromAuthToken(httpServletRequest);
    ZimbraLog.addAccountNameToContext(account.getName());
    String path;/*from  ww  w  .  ja va  2 s  .  co  m*/
    BufferedReader reader = httpServletRequest.getReader();
    while ((path = reader.readLine()) != null) {
        HttpResponse fileRequestResponse = mCloudHttpRequestUtils.queryCloudServerService(account, path);

        int responseCode = fileRequestResponse.getStatusLine().getStatusCode();
        if (responseCode < HTTP_LOWEST_ERROR_STATUS) {
            HttpPost post = new HttpPost(mBackendUtils.getServerServiceUrl("/service/upload?fmt=extended,raw"));
            post.setHeader(CONTENT_DISPOSITION_HTTP_HEADER, "attachment; filename=\" "
                    + convertToUnicode(path.substring(path.lastIndexOf("/") + 1)) + " \"");
            post.setHeader("Cache-Control", "no-cache");
            post.setHeader("Cookie", httpServletRequest.getHeader("Cookie"));
            post.setHeader("X-Zimbra-Csrf-Token", httpServletRequest.getHeader("X-Zimbra-Csrf-Token"));
            post.setEntity(fileRequestResponse.getEntity());

            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s)
                        throws CertificateException {
                    return true;
                }
            });
            SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(builder.build());
            CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();

            HttpResponse response = client.execute(post);

            response.getEntity().writeTo(httpServletResponse.getOutputStream());
        } else {
            httpServletResponse.setStatus(responseCode);
            PrintWriter respWriter = httpServletResponse.getWriter();
            respWriter.println("Error");
            respWriter.close();
            break;
        }
    }
}