Example usage for org.apache.http.conn.ssl SSLContexts custom

List of usage examples for org.apache.http.conn.ssl SSLContexts custom

Introduction

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

Prototype

public static SSLContextBuilder custom() 

Source Link

Document

Creates custom SSL context.

Usage

From source file:com.emc.storageos.driver.dellsc.scapi.rest.RestClient.java

/**
 * Instantiates a new Rest client./*from   w  w  w.j  a v a2 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:org.apache.hadoop.gateway.service.test.ServiceTestResource.java

@GET
@Produces({ APPLICATION_XML, APPLICATION_JSON })
public ServiceTestWrapper serviceTest(@QueryParam("username") String username,
        @QueryParam("password") String password) {
    List<ServiceTest> tests = new ArrayList<>();
    List<String> messages = new ArrayList<>();
    String authString;//w ww .j  a va  2  s. c o m
    GatewayConfig config = (GatewayConfig) request.getServletContext()
            .getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE);
    SSLContext ctx = null;
    CloseableHttpClient client;
    String id = getTopologyName();

    Topology topology = getTopology(id);

    //    Create Authorization String
    if (username != null && password != null) {
        authString = "Basic " + Base64.encodeAsString((username + ":" + password).getBytes());
    } else if (request.getHeader("Authorization") != null) {
        authString = request.getHeader("Authorization");
    } else {
        authString = null;
    }

    //    Attempt to build SSL context for HTTP client.
    try {
        ctx = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
    } catch (Exception e) {
        messages.add(e.getMessage());
    }

    //    Initialize the HTTP client
    if (ctx == null) {
        client = HttpClients.createDefault();
    } else {
        client = HttpClients.custom().setSslcontext(ctx).build();
    }

    if (topology != null) {
        for (Service s : topology.getServices()) {
            List<String> urls = getServiceTestURLs(config, s.getRole(), topology);

            //          Make sure we handle a case where no URLs are found.
            if (urls.size() <= 0) {
                ServiceTest test = new ServiceTest(s);
                test.setMessage("This service did not contain any test URLs");
            }

            for (String url : urls) {
                HttpGet req = new HttpGet();
                ServiceTest test = new ServiceTest(s, url);

                if (authString != null) {
                    req.setHeader("Authorization", authString);
                } else {
                    messages.add("No credentials provided. Expect HTTP 401 responses.");
                }

                try {
                    req.setURI(new URIBuilder(url).build());
                    CloseableHttpResponse res = client.execute(req);
                    String contentLength = "Content-Length:" + res.getEntity().getContentLength();
                    String contentType = (res.getEntity().getContentType() != null)
                            ? res.getEntity().getContentType().toString()
                            : "No-contenttype";
                    test.setResponseContent(contentLength + "," + contentType);
                    test.setHttpCode(res.getStatusLine().getStatusCode());
                    res.close();

                } catch (IOException e) {
                    messages.add("Exception: " + e.getMessage());
                    test.setMessage(e.getMessage());
                } catch (URISyntaxException e) {
                    test.setMessage(e.getMessage());
                } catch (Exception e) {
                    messages.add(e.getMessage());
                    test.setMessage(e.getMessage());
                } finally {
                    req.releaseConnection();
                    tests.add(test);
                }
            }
        }
    } else {
        messages.add("Topology " + id + " not found");
    }

    try {
        client.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    ServiceTestWrapper stw = new ServiceTestWrapper();
    stw.setTests(tests);
    stw.setMessages(messages);

    return stw;
}

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();//w w w.ja  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 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();//ww w.  java  2s.  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:com.shekhargulati.reactivex.rxokhttp.SslCertificates.java

private SslCertificates(final Builder builder) throws SslCertificateException {
    if ((builder.caCertPath == null) || (builder.clientCertPath == null) || (builder.clientKeyPath == null)) {
        throw new SslCertificateException(
                "caCertPath, clientCertPath, and clientKeyPath must all be specified");
    }/*w  w  w .j  ava  2 s .  co m*/

    try {
        final CertificateFactory cf = CertificateFactory.getInstance("X.509");
        final Certificate caCert = cf.generateCertificate(Files.newInputStream(builder.caCertPath));
        final Certificate clientCert = cf.generateCertificate(Files.newInputStream(builder.clientCertPath));

        final PEMKeyPair clientKeyPair = (PEMKeyPair) new PEMParser(
                Files.newBufferedReader(builder.clientKeyPath, Charset.defaultCharset())).readObject();

        final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(
                clientKeyPair.getPrivateKeyInfo().getEncoded());
        final KeyFactory kf = KeyFactory.getInstance("RSA");
        final PrivateKey clientKey = kf.generatePrivate(spec);

        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null);

        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, KEY_STORE_PASSWORD);
        keyStore.setCertificateEntry("client", clientCert);
        keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWORD, new Certificate[] { clientCert });

        this.sslContext = SSLContexts.custom().loadTrustMaterial(trustStore)
                .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD).useTLS().build();
    } catch (java.security.cert.CertificateException | IOException | NoSuchAlgorithmException
            | InvalidKeySpecException | KeyStoreException | UnrecoverableKeyException
            | KeyManagementException e) {
        throw new SslCertificateException(e);
    }
}

From source file:org.apache.airavata.datacat.agent.dispatcher.MetadataDispatcher.java

private MetadataDispatcher() throws Exception {
    KeyStore keyStore = KeyStore.getInstance("JKS");
    KeyStore trustStore = KeyStore.getInstance("JKS");
    // set up security context
    if (new File("../security/" + AgentProperties.getInstance().getProperty(Constants.KEYSTORE_FILE, ""))
            .exists()) {/*from   www.  j a  va  2  s . co m*/
        keyStore.load(
                new FileInputStream(new File("../security/"
                        + AgentProperties.getInstance().getProperty(Constants.KEYSTORE_FILE, ""))),
                AgentProperties.getInstance().getProperty(Constants.KEYSTORE_PWD, "").toCharArray());
    } else {
        ;
        keyStore.load(
                ClassLoader.getSystemResourceAsStream(
                        "security/" + AgentProperties.getInstance().getProperty(Constants.KEYSTORE_FILE, "")),
                AgentProperties.getInstance().getProperty(Constants.KEYSTORE_PWD, "").toCharArray());
    }
    if (new File("../security/" + AgentProperties.getInstance().getProperty(Constants.TRUSTSTORE_FILE, ""))
            .exists()) {
        keyStore.load(
                new FileInputStream(new File("../security/"
                        + AgentProperties.getInstance().getProperty(Constants.TRUSTSTORE_FILE, ""))),
                AgentProperties.getInstance().getProperty(Constants.TRUSTSTORE_PWD, "").toCharArray());
    } else {
        keyStore.load(
                ClassLoader.getSystemResourceAsStream(
                        "security/" + AgentProperties.getInstance().getProperty(Constants.TRUSTSTORE_FILE, "")),
                AgentProperties.getInstance().getProperty(Constants.TRUSTSTORE_PWD, "").toCharArray());
    }
    SSLContext sslContext = SSLContexts.custom()
            .loadKeyMaterial(keyStore,
                    AgentProperties.getInstance().getProperty(Constants.KEYSTORE_PWD, "").toCharArray())
            .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();

    sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" }, null,
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    rabbitMQPublisher = new RabbitMQPublisher();
}

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 w w . jav  a  2s  .  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:com.shekhargulati.reactivex.docker.client.ssl.DockerCertificates.java

private DockerCertificates(final Builder builder) throws DockerCertificateException {
    if ((builder.caCertPath == null) || (builder.clientCertPath == null) || (builder.clientKeyPath == null)) {
        throw new DockerCertificateException(
                "caCertPath, clientCertPath, and clientKeyPath must all be specified");
    }//from w w  w  .  jav a  2  s.  c  o m

    try {
        final CertificateFactory cf = CertificateFactory.getInstance("X.509");
        final Certificate caCert = cf.generateCertificate(Files.newInputStream(builder.caCertPath));
        final Certificate clientCert = cf.generateCertificate(Files.newInputStream(builder.clientCertPath));

        final PEMKeyPair clientKeyPair = (PEMKeyPair) new PEMParser(
                Files.newBufferedReader(builder.clientKeyPath, Charset.defaultCharset())).readObject();

        final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(
                clientKeyPair.getPrivateKeyInfo().getEncoded());
        final KeyFactory kf = KeyFactory.getInstance("RSA");
        final PrivateKey clientKey = kf.generatePrivate(spec);

        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null);

        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, KEY_STORE_PASSWORD);
        keyStore.setCertificateEntry("client", clientCert);
        keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWORD, new Certificate[] { clientCert });

        this.sslContext = SSLContexts.custom().loadTrustMaterial(trustStore)
                .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD).useTLS().build();
    } catch (CertificateException | IOException | NoSuchAlgorithmException | InvalidKeySpecException
            | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) {
        throw new DockerCertificateException(e);
    }
}

From source file:org.metaeffekt.dcc.shell.RemoteAgentTest.java

private HttpClient newHttpClient() throws GeneralSecurityException, IOException {
    final char[] password = "DYKK8T8m9nKqBRPZ".toCharArray();

    final KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(getClass().getResourceAsStream("/dcc-shell.keystore"), password);

    final KeyStore trustStore = KeyStore.getInstance("JKS");
    trustStore.load(getClass().getResourceAsStream("/dcc-shell.truststore"), password);

    final SSLContextBuilder sslContextBuilder = SSLContexts.custom();
    sslContextBuilder.loadKeyMaterial(keyStore, password);
    sslContextBuilder.loadTrustMaterial(trustStore);

    final HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setSslcontext(sslContextBuilder.build());
    builder.setHostnameVerifier(new AllowAllHostnameVerifier());

    final HttpClient client = builder.build();
    return client;
}