Example usage for org.apache.http.impl.client HttpClientBuilder setSslcontext

List of usage examples for org.apache.http.impl.client HttpClientBuilder setSslcontext

Introduction

In this page you can find the example usage for org.apache.http.impl.client HttpClientBuilder setSslcontext.

Prototype

public final HttpClientBuilder setSslcontext(final SSLContext sslcontext) 

Source Link

Document

Assigns SSLContext instance.

Usage

From source file:co.tuzza.swipehq.transport.ManagedHttpTransport.java

private HttpClient getHttpClient() {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setUserAgent("SwipeHQClient " + SwipeHQClient.VERSION);
    httpClientBuilder.setConnectionManager(clientConnectionManager);
    httpClientBuilder.setDefaultRequestConfig(getRequestConfig());
    httpClientBuilder.setSSLContext(sslContext);

    return httpClientBuilder.build();

}

From source file:org.obm.push.spushnik.resources.Scenario.java

@VisibleForTesting
CloseableHttpClient chooseHttpClient(Credentials credentials, String serviceUrl) throws IOException {
    Preconditions.checkNotNull(credentials);
    Preconditions.checkNotNull(serviceUrl);
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setMaxConnTotal(5).setMaxConnPerRoute(5);
    if (serviceDoesNotNeedSSL(serviceUrl)) {
        return httpClientBuilder.build();
    }//from w ww  .  ja  v  a2  s .  c o  m
    if (serviceNeedsClientCertificate(credentials)) {
        try (InputStream pkcs12Stream = getPkcs12Stream(credentials)) {
            return httpClientBuilder
                    .setSslcontext(SSLContextFactory.create(pkcs12Stream, credentials.getPkcs12Password()))
                    .build();
        }
    }
    return httpClientBuilder.setSslcontext(SSLContextFactory.TRUST_ALL)
            .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
}

From source file:com.bosch.cr.examples.inventorybrowser.server.CustomProxyServlet.java

private synchronized CloseableHttpClient getHttpClient() {
    if (httpClient == null) {
        try {/*from   w  w w.  ja  v a2 s. c  o m*/
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

            // #### ONLY FOR TEST: Trust ANY certificate (self certified, any chain, ...)
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true)
                    .build();
            httpClientBuilder.setSSLContext(sslContext);

            // #### ONLY FOR TEST: Do NOT verify hostname
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
                    NoopHostnameVerifier.INSTANCE);

            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslConnectionSocketFactory).build();
            PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(
                    socketFactoryRegistry);
            httpClientBuilder.setConnectionManager(httpClientConnectionManager);

            if (getConfig().getProperty("http.proxyHost") != null) {
                httpClientBuilder.setProxy(new HttpHost(getConfig().getProperty("http.proxyHost"),
                        Integer.parseInt(getConfig().getProperty("http.proxyPort"))));
            }

            httpClient = httpClientBuilder.build();
        } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException ex) {
            throw new RuntimeException(ex);
        }
    }

    return httpClient;
}

From source file:com.bosch.cr.examples.inventorybrowser.server.ProxyServlet.java

private synchronized CloseableHttpClient getHttpClient() {
    if (httpClient == null) {
        try {//from   www  . ja  va  2s  .c o m
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

            // #### ONLY FOR TEST: Trust ANY certificate (self certified, any chain, ...)
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true)
                    .build();
            httpClientBuilder.setSSLContext(sslContext);

            // #### ONLY FOR TEST: Do NOT verify hostname
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
                    NoopHostnameVerifier.INSTANCE);

            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslConnectionSocketFactory).build();
            PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(
                    socketFactoryRegistry);
            httpClientBuilder.setConnectionManager(httpClientConnectionManager);

            if (props.getProperty("http.proxyHost") != null) {
                httpClientBuilder.setProxy(new HttpHost(props.getProperty("http.proxyHost"),
                        Integer.parseInt(props.getProperty("http.proxyPort"))));
            }

            httpClient = httpClientBuilder.build();
        } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException ex) {
            throw new RuntimeException(ex);
        }
    }

    return httpClient;
}

From source file:com.bosch.cr.integration.hello_world_ui.ProxyServlet.java

/**
 * Create http client/*from   ww w  . j  a  va 2  s  .co  m*/
 */
private synchronized CloseableHttpClient getHttpClient() {
    if (httpClient == null) {
        try {
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

            // #### ONLY FOR TEST: Trust ANY certificate (self certified, any chain, ...)
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true)
                    .build();
            httpClientBuilder.setSSLContext(sslContext);

            // #### ONLY FOR TEST: Do NOT verify hostname
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
                    NoopHostnameVerifier.INSTANCE);

            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslConnectionSocketFactory).build();
            PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(
                    socketFactoryRegistry);
            httpClientBuilder.setConnectionManager(httpClientConnectionManager);

            if (props.getProperty("http.proxyHost") != null) {
                httpClientBuilder.setProxy(new HttpHost(props.getProperty("http.proxyHost"),
                        Integer.parseInt(props.getProperty("http.proxyPort"))));
            }

            if (props.getProperty("http.proxyUser") != null) {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(targetHost), new UsernamePasswordCredentials(
                        props.getProperty("http.proxyUser"), props.getProperty("http.proxyPwd")));
                httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
            }

            httpClient = httpClientBuilder.build();
        } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException ex) {
            throw new RuntimeException(ex);
        }
    }

    return httpClient;
}

From source file:com.bosch.cr.examples.jwt.CustomProxyServlet.java

private synchronized CloseableHttpClient getHttpClient() {
    if (httpClient == null) {
        try {// w  w w .  j  av a  2s  . c  o m
            final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

            // #### ONLY FOR TEST: Trust ANY certificate (self certified, any chain, ...)
            final SSLContext sslContext = new SSLContextBuilder()
                    .loadTrustMaterial(null, (chain, authType) -> true).build();
            httpClientBuilder.setSSLContext(sslContext);

            // #### ONLY FOR TEST: Do NOT verify hostname
            final SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                    sslContext, NoopHostnameVerifier.INSTANCE);

            final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslConnectionSocketFactory).build();
            final PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(
                    socketFactoryRegistry);
            httpClientBuilder.setConnectionManager(httpClientConnectionManager);

            final boolean proxyEnabled = configurationProperties
                    .getPropertyAsBoolean(ConfigurationProperty.PROXY_ENABLED);
            if (proxyEnabled) {
                final String proxyHost = configurationProperties
                        .getPropertyAsString(ConfigurationProperty.PROXY_HOST);
                final int proxyPort = configurationProperties
                        .getPropertyAsInt(ConfigurationProperty.PROXY_PORT);
                final HttpHost proxy = new HttpHost(proxyHost, proxyPort);
                httpClientBuilder.setProxy(proxy);
            }

            httpClient = httpClientBuilder.build();
        } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException ex) {
            throw new RuntimeException(ex);
        }
    }

    return httpClient;
}

From source file:org.metaeffekt.dcc.controller.execution.RemoteExecutor.java

private CloseableHttpClient instantiateHttpClientWithTimeout() throws IOException, GeneralSecurityException {
    final KeyStore keyStore = loadKeyStore(sslConfiguration.getKeyStoreLocation(),
            sslConfiguration.getKeyStorePassword());

    final KeyStore trustStore = loadKeyStore(sslConfiguration.getTrustStoreLocation(),
            sslConfiguration.getTrustStorePassword());

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

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

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

From source file:net.wasdev.gameon.concierge.PlayerClient.java

/**
 * Obtain apiKey for player id./*from w w  w  .  j a  v  a2 s  .co m*/
 *
 * @param playerId
 *            The player id
 * @return The apiKey for the player
 */
public String getApiKey(String playerId) throws IOException {
    String jwt = getClientJwtForId(playerId);

    HttpClient client = null;
    if ("development".equals(System.getenv("CONCIERGE_PLAYER_MODE"))) {
        System.out.println("Using development mode player connection. (DefaultSSL,NoHostNameValidation)");
        try {
            HttpClientBuilder b = HttpClientBuilder.create();

            //use the default ssl context, we have a trust store configured for player cert.
            SSLContext sslContext = SSLContext.getDefault();

            //use a very trusting truststore.. (not needed..)
            //SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();

            b.setSSLContext(sslContext);

            //disable hostname validation, because we'll need to access the cert via a different hostname.
            b.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);

            client = b.build();
        } catch (Exception e) {
            throw new IOException(e);
        }
    } else {
        client = HttpClientBuilder.create().build();
    }
    HttpGet hg = new HttpGet(playerLocation + "/" + playerId + "?jwt=" + jwt);

    System.out.println("Building web target " + hg.getURI().toString());

    try {
        // Make GET request using the specified target, get result as a
        // string containing JSON
        HttpResponse r = client.execute(hg);
        String result = new BasicResponseHandler().handleResponse(r);

        // Parse the JSON response, and retrieve the apiKey field value.
        ObjectMapper om = new ObjectMapper();
        JsonNode jn = om.readValue(result, JsonNode.class);

        return jn.get("apiKey").textValue();
    } catch (HttpResponseException hre) {
        System.out.println(
                "Error communicating with player service: " + hre.getStatusCode() + " " + hre.getMessage());
        throw hre;
    } catch (ResponseProcessingException rpe) {
        System.out.println("Error processing response " + rpe.getResponse().toString());
        throw new IOException(rpe);
    } catch (ProcessingException | WebApplicationException ex) {
        //bad stuff.
        System.out.println("Hmm.. " + ex.getMessage());
        throw new IOException(ex);
    } catch (IOException io) {
        System.out.println("Utoh.. " + io.getMessage());
        throw new IOException(io);
    }

}

From source file:com.bosch.iot.things.example.historian.Controller.java

private synchronized CloseableHttpClient getHttpClient() {
    if (theHttpClient == null) {

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

        // #### ONLY FOR TEST: Trust ANY certificate (self certified, any chain, ...)
        try {//w w w .  ja v  a  2 s  .co  m
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true)
                    .build();
            httpClientBuilder.setSSLContext(sslContext);

            // #### ONLY FOR TEST: Do NOT verify hostname
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
                    NoopHostnameVerifier.INSTANCE);

            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslConnectionSocketFactory).build();
            PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(
                    socketFactoryRegistry);
            httpClientBuilder.setConnectionManager(httpClientConnectionManager);
        } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException ex) {
            java.util.logging.Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        }

        Properties config = getConfig();
        if (config.getProperty("http.proxyHost") != null) {
            httpClientBuilder.setProxy(new HttpHost(config.getProperty("http.proxyHost"),
                    Integer.parseInt(config.getProperty("http.proxyPort"))));
        }
        if (config.getProperty("http.proxyUser") != null) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(
                    new AuthScope(HttpHost.create(getConfig().getProperty("thingsServiceEndpointUrl"))),
                    new UsernamePasswordCredentials(config.getProperty("http.proxyUser"),
                            config.getProperty("http.proxyPwd")));
            httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
        }

        theHttpClient = httpClientBuilder.build();
    }
    return theHttpClient;
}

From source file:com.microsoft.alm.plugin.context.ServerContext.java

public synchronized HttpClient getHttpClient() {
    checkDisposed();//from  w  w  w  . j  a  v  a 2  s .co  m
    if (httpClient == null && authenticationInfo != null) {
        final Credentials credentials = AuthHelper.getCredentials(type, authenticationInfo);
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, credentials);
        final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

        if (isSSLEnabledOnPrem(Type.TFS, authenticationInfo.getServerUri())) {
            final SslConfigurator sslConfigurator = getSslConfigurator();
            final SSLContext sslContext = sslConfigurator.createSSLContext();

            httpClientBuilder.setSslcontext(sslContext);
        }

        httpClient = httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider).build();
    }
    return httpClient;
}