Example usage for org.apache.http.ssl SSLContextBuilder SSLContextBuilder

List of usage examples for org.apache.http.ssl SSLContextBuilder SSLContextBuilder

Introduction

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

Prototype

public SSLContextBuilder() 

Source Link

Usage

From source file:org.springframework.boot.web.servlet.server.AbstractServletWebServerFactoryTests.java

protected void testRestrictedSSLProtocolsAndCipherSuites(String[] protocols, String[] ciphers)
        throws Exception {
    AbstractServletWebServerFactory factory = getFactory();
    factory.setSsl(getSsl(null, "password", "src/test/resources/test.jks", null, protocols, ciphers));
    this.webServer = factory
            .getWebServer(new ServletRegistrationBean<>(new ExampleServlet(true, false), "/hello"));
    this.webServer.start();

    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
            new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());

    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
            httpClient);//from  w  w w. j  av  a 2 s  .c  o  m

    assertThat(getResponse(getLocalUrl("https", "/hello"), requestFactory)).contains("scheme=https");
}

From source file:org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfigurationTests.java

private void assertContent(String scheme, String url, int port, Object expected) throws Exception {

    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
            new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());
    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
            httpClient);//  w  w  w.ja v a  2s .  c o  m
    ClientHttpRequest request = requestFactory.createRequest(new URI(scheme + "://localhost:" + port + url),
            HttpMethod.GET);
    try {
        ClientHttpResponse response = request.execute();
        if (HttpStatus.NOT_FOUND.equals(response.getStatusCode())) {
            throw new FileNotFoundException();
        }
        try {
            String actual = StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8"));
            if (expected instanceof Matcher) {
                assertThat(actual).is(Matched.by((Matcher<?>) expected));
            } else {
                assertThat(actual).isEqualTo(expected);
            }
        } finally {
            response.close();
        }
    } catch (Exception ex) {
        if (expected == null) {
            if (SocketException.class.isInstance(ex) || FileNotFoundException.class.isInstance(ex)) {
                return;
            }
        }
        throw ex;
    }
}

From source file:org.apache.gobblin.service.modules.orchestration.AzkabanClient.java

/**
 * Create a {@link CloseableHttpClient} used to communicate with Azkaban server.
 * Derived class can configure different http client by overriding this method.
 *
 * @return A closeable http client.//  w  ww .j a v  a  2 s  .c  o  m
 */
protected CloseableHttpClient getClient() throws AzkabanClientException {
    try {
        // SSLSocketFactory using custom TrustStrategy that ignores warnings about untrusted certificates
        // Self sign SSL
        SSLContextBuilder sslcb = new SSLContextBuilder();
        sslcb.loadTrustMaterial(null, (TrustStrategy) new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcb.build());

        HttpClientBuilder builder = HttpClientBuilder.create();
        RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(10000)
                .setConnectTimeout(10000).setConnectionRequestTimeout(10000).build();

        builder.disableCookieManagement().useSystemProperties().setDefaultRequestConfig(requestConfig)
                .setConnectionManager(new BasicHttpClientConnectionManager()).setSSLSocketFactory(sslsf);

        return builder.build();
    } catch (Exception e) {
        throw new AzkabanClientException("HttpClient cannot be created", e);
    }
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.TestHopsworksRMAppSecurityActions.java

private Pair<String, String[]> loginAndGetJWT() throws Exception {
    CloseableHttpClient client = null;//from  w w  w .ja  v a 2s .co m
    try {
        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.loadTrustMaterial(new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        });
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(),
                NoopHostnameVerifier.INSTANCE);

        client = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();
        URL loginURL = new URL(new URL(HOPSWORKS_ENDPOINT), HOPSWORKS_LOGIN_PATH);
        HttpUriRequest login = RequestBuilder.post().setUri(loginURL.toURI())
                .addParameter("email", HOPSWORKS_USER).addParameter("password", HOPSWORKS_PASSWORD).build();
        CloseableHttpResponse response = client.execute(login);
        Assert.assertNotNull(response);
        Assert.assertEquals(200, response.getStatusLine().getStatusCode());
        Header[] authHeaders = response.getHeaders(HttpHeaders.AUTHORIZATION);

        String masterJWT = null;
        for (Header h : authHeaders) {
            Matcher matcher = HopsworksRMAppSecurityActions.JWT_PATTERN.matcher(h.getValue());
            if (matcher.matches()) {
                masterJWT = matcher.group(1);
            }
        }
        JsonParser jsonParser = new JsonParser();
        JsonObject json = jsonParser.parse(EntityUtils.toString(response.getEntity())).getAsJsonObject();
        JsonArray array = json.getAsJsonArray("renewTokens");
        String[] renewTokens = new String[array.size()];
        boolean renewalTokensFound = false;
        for (int i = 0; i < renewTokens.length; i++) {
            renewTokens[i] = array.get(i).getAsString();
            renewalTokensFound = true;
        }
        if (masterJWT != null && renewalTokensFound) {
            return new Pair<>(masterJWT, renewTokens);
        }

        throw new IOException("Could not get JWT from Hopsworks");
    } finally {
        if (client != null) {
            client.close();
        }
    }
}

From source file:org.apache.nutch.indexwriter.elasticrest.ElasticRestIndexWriter.java

@Override
public void open(IndexWriterParams parameters) throws IOException {
    host = parameters.get(ElasticRestConstants.HOST);
    if (StringUtils.isBlank(host)) {
        String message = "Missing host. It should be set in index-writers.xml";
        message += "\n" + describe();
        LOG.error(message);/*from  ww  w .java2 s .co m*/
        throw new RuntimeException(message);
    }

    port = parameters.getInt(ElasticRestConstants.PORT, 9200);
    user = parameters.get(ElasticRestConstants.USER);
    password = parameters.get(ElasticRestConstants.PASSWORD);
    https = parameters.getBoolean(ElasticRestConstants.HTTPS, false);
    trustAllHostnames = parameters.getBoolean(ElasticRestConstants.HOSTNAME_TRUST, false);

    languages = parameters.getStrings(ElasticRestConstants.LANGUAGES);
    separator = parameters.get(ElasticRestConstants.SEPARATOR, DEFAULT_SEPARATOR);
    sink = parameters.get(ElasticRestConstants.SINK, DEFAULT_SINK);

    // trust ALL certificates
    SSLContext sslContext = null;
    try {
        sslContext = new SSLContextBuilder().loadTrustMaterial(new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        LOG.error("Failed to instantiate sslcontext object: \n{}", ExceptionUtils.getStackTrace(e));
        throw new SecurityException();
    }

    // skip hostname checks
    HostnameVerifier hostnameVerifier = null;
    if (trustAllHostnames) {
        hostnameVerifier = NoopHostnameVerifier.INSTANCE;
    } else {
        hostnameVerifier = new DefaultHostnameVerifier();
    }

    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);
    SchemeIOSessionStrategy httpsIOSessionStrategy = new SSLIOSessionStrategy(sslContext, hostnameVerifier);

    JestClientFactory jestClientFactory = new JestClientFactory();
    URL urlOfElasticsearchNode = new URL(https ? "https" : "http", host, port, "");

    if (host != null && port > 1) {
        HttpClientConfig.Builder builder = new HttpClientConfig.Builder(urlOfElasticsearchNode.toString())
                .multiThreaded(true).connTimeout(300000).readTimeout(300000);
        if (https) {
            if (user != null && password != null) {
                builder.defaultCredentials(user, password);
            }
            builder.defaultSchemeForDiscoveredNodes("https").sslSocketFactory(sslSocketFactory) // this only affects sync calls
                    .httpsIOSessionStrategy(httpsIOSessionStrategy); // this only affects async calls
        }
        jestClientFactory.setHttpClientConfig(builder.build());
    } else {
        throw new IllegalStateException(
                "No host or port specified. Please set the host and port in nutch-site.xml");
    }

    client = jestClientFactory.getObject();

    defaultIndex = parameters.get(ElasticRestConstants.INDEX, "nutch");
    defaultType = parameters.get(ElasticRestConstants.TYPE, "doc");

    maxBulkDocs = parameters.getInt(ElasticRestConstants.MAX_BULK_DOCS, DEFAULT_MAX_BULK_DOCS);
    maxBulkLength = parameters.getInt(ElasticRestConstants.MAX_BULK_LENGTH, DEFAULT_MAX_BULK_LENGTH);

    bulkBuilder = new Bulk.Builder().defaultIndex(defaultIndex).defaultType(defaultType);
}

From source file:org.apache.syncope.installer.utilities.HttpUtils.java

private static CloseableHttpClient createHttpsClient() {
    CloseableHttpClient chc = null;// w  ww . j  a va2 s. co m
    try {
        final SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        chc = HttpClients.custom().setSSLSocketFactory(
                new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE)).build();
    } catch (Exception ex) {
        // ignore
    }

    return chc;
}

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  w w  .  ja  v  a 2  s.  c o 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.flowable.http.bpmn.impl.HttpActivityBehaviorImpl.java

public HttpActivityBehaviorImpl() {
    HttpClientConfig config = CommandContextUtil.getProcessEngineConfiguration().getHttpClientConfig();
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    // https settings
    if (config.isDisableCertVerify()) {
        try {/*  w  w w .j  a  va  2  s .c o  m*/
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            httpClientBuilder.setSSLSocketFactory(
                    new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
                        @Override
                        public boolean verify(String s, SSLSession sslSession) {
                            return true;
                        }
                    }));

        } catch (Exception e) {
            LOGGER.error("Could not configure HTTP client SSL self signed strategy", e);
        }
    }

    // request retry settings
    int retryCount = 0;
    if (config.getRequestRetryLimit() > 0) {
        retryCount = config.getRequestRetryLimit();
    }
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(retryCount, false));

    this.httpActivityExecutor = new HttpActivityExecutor(httpClientBuilder, new ProcessErrorPropagator());
}

From source file:org.flowable.http.cmmn.impl.CmmnHttpActivityBehaviorImpl.java

public CmmnHttpActivityBehaviorImpl() {
    org.flowable.cmmn.engine.HttpClientConfig config = CommandContextUtil.getCmmnEngineConfiguration()
            .getHttpClientConfig();/*from ww w.j  av a2s.c  o m*/
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    // https settings
    if (config.isDisableCertVerify()) {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            httpClientBuilder.setSSLSocketFactory(
                    new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
                        @Override
                        public boolean verify(String s, SSLSession sslSession) {
                            return true;
                        }
                    }));

        } catch (Exception e) {
            LOGGER.error("Could not configure HTTP client SSL self signed strategy", e);
        }
    }

    // request retry settings
    int retryCount = 0;
    if (config.getRequestRetryLimit() > 0) {
        retryCount = config.getRequestRetryLimit();
    }
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(retryCount, false));

    this.httpActivityExecutor = new HttpActivityExecutor(httpClientBuilder, new NopErrorPropagator());
}

From source file:org.flowable.http.impl.HttpActivityBehaviorImpl.java

public HttpActivityBehaviorImpl() {
    HttpClientConfig config = CommandContextUtil.getProcessEngineConfiguration().getHttpClientConfig();
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    // https settings
    if (config.isDisableCertVerify()) {
        try {//from   w w  w  . jav  a 2s .  co  m
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            httpClientBuilder.setSSLSocketFactory(
                    new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
                        public boolean verify(String s, SSLSession sslSession) {
                            return true;
                        }
                    }));

        } catch (Exception e) {
            LOGGER.error("Could not configure HTTP client SSL self signed strategy", e);
        }
    }

    // request retry settings
    int retryCount = 0;
    if (config.getRequestRetryLimit() > 0) {
        retryCount = config.getRequestRetryLimit();
    }
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(retryCount, false));

    // Build http client
    client = httpClientBuilder.build();
    LOGGER.info("HTTP client is initialized");

    // Shutdown hook to close the http client
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            if (client != null) {
                try {
                    client.close();
                    LOGGER.info("HTTP client is closed");
                } catch (Throwable e) {
                    LOGGER.error("Could not close http client", e);
                }
            }
        }
    });
}