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:microsoft.exchange.webservices.data.HttpClientWebRequest.java

/**
 * Prepare asynchronous connection.// www .  j  a v a 2  s.com
 *
 * @throws microsoft.exchange.webservices.data.EWSHttpException throws EWSHttpException
 */
public void prepareAsyncConnection() throws EWSHttpException {
    try {
        //ssl config
        HttpClientBuilder builder = HttpClients.custom();
        builder.setConnectionManager(this.httpClientConnMng);
        builder.setSchemePortResolver(new DefaultSchemePortResolver());

        EwsSSLProtocolSocketFactory factory = EwsSSLProtocolSocketFactory.build(trustManger);
        builder.setSSLSocketFactory(factory);
        builder.setSslcontext(factory.getContext());

        //create the cookie store
        if (cookieStore == null) {
            cookieStore = new BasicCookieStore();
        }
        builder.setDefaultCookieStore(cookieStore);

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY,
                new NTCredentials(getUserName(), getPassword(), "", getDomain()));
        builder.setDefaultCredentialsProvider(credsProvider);

        //fix socket config
        SocketConfig sc = SocketConfig.custom().setSoTimeout(getTimeout()).build();
        builder.setDefaultSocketConfig(sc);

        RequestConfig.Builder rcBuilder = RequestConfig.custom();
        rcBuilder.setConnectionRequestTimeout(getTimeout());
        rcBuilder.setConnectTimeout(getTimeout());
        rcBuilder.setSocketTimeout(getTimeout());

        // fix issue #144 + #160: if we used NTCredentials from above: these are NT credentials
        ArrayList<String> authPrefs = new ArrayList<String>();
        authPrefs.add(AuthSchemes.NTLM);
        rcBuilder.setTargetPreferredAuthSchemes(authPrefs);
        //

        builder.setDefaultRequestConfig(rcBuilder.build());

        //HttpClientParams.setRedirecting(client.getParams(), isAllowAutoRedirect()); by default it follows redirects
        //create the client and execute requests
        client = builder.build();
        httpPostReq = new HttpPost(getUrl().toString());
        response = client.execute(httpPostReq);
    } catch (IOException e) {
        client = null;
        httpPostReq = null;
        throw new EWSHttpException("Unable to open connection to " + this.getUrl());
    } catch (Exception e) {
        client = null;
        httpPostReq = null;
        e.printStackTrace();
        throw new EWSHttpException("SSL problem " + this.getUrl());
    }
}

From source file:org.neo4j.ogm.drivers.http.driver.HttpDriver.java

private synchronized CloseableHttpClient httpClient() {

    if (httpClient == null) { // most of the time this will be false, branch-prediction will be very fast and the lock released immediately

        try {//  w ww  . j  a v a2 s .com
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

            SSLContext sslContext = SSLContext.getDefault();

            if (configuration.getTrustStrategy() != null) {

                if (configuration.getTrustStrategy().equals("ACCEPT_UNSIGNED")) {
                    sslContext = new SSLContextBuilder().loadTrustMaterial(null, (arg0, arg1) -> true).build();

                    LOGGER.warn("Certificate validation has been disabled");
                }
            }

            // setup the default or custom ssl context
            httpClientBuilder.setSSLContext(sslContext);

            HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();

            SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                    hostnameVerifier);
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslSocketFactory).build();

            // allows multi-threaded use
            PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
                    socketFactoryRegistry);

            Integer connectionPoolSize = configuration.getConnectionPoolSize();

            connectionManager.setMaxTotal(connectionPoolSize);
            connectionManager.setDefaultMaxPerRoute(connectionPoolSize);

            httpClientBuilder.setConnectionManager(connectionManager);

            httpClient = httpClientBuilder.build();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    return httpClient;
}

From source file:com.github.dockerjava.jaxrs.connector.ApacheConnector.java

/**
 * Create the new Apache HTTP Client connector.
 *
 * @param config client configuration./*from   ww  w  .j a v  a  2s . c o  m*/
 */
ApacheConnector(Configuration config) {
    Object reqConfig = null;

    if (config != null) {
        final Object connectionManager = config.getProperties().get(ApacheClientProperties.CONNECTION_MANAGER);

        if (connectionManager != null) {
            if (!(connectionManager instanceof HttpClientConnectionManager)) {
                LOGGER.log(Level.WARNING, LocalizationMessages.IGNORING_VALUE_OF_PROPERTY(
                        ApacheClientProperties.CONNECTION_MANAGER, connectionManager.getClass().getName(),
                        HttpClientConnectionManager.class.getName()));
            }
        }

        reqConfig = config.getProperties().get(ApacheClientProperties.REQUEST_CONFIG);
        if (reqConfig != null) {
            if (!(reqConfig instanceof RequestConfig)) {
                LOGGER.log(Level.WARNING,
                        LocalizationMessages.IGNORING_VALUE_OF_PROPERTY(ApacheClientProperties.REQUEST_CONFIG,
                                reqConfig.getClass().getName(), RequestConfig.class.getName()));
                reqConfig = null;
            }
        }
    }

    final SSLContext sslContext = getSslContext(config);
    final HttpClientBuilder clientBuilder = HttpClientBuilder.create();

    clientBuilder.setConnectionManager(getConnectionManager(config, sslContext));
    clientBuilder.setSslcontext(sslContext);

    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();

    int connectTimeout = 0;
    int socketTimeout = 0;
    boolean ignoreCookies = false;
    if (config != null) {
        connectTimeout = ClientProperties.getValue(config.getProperties(), ClientProperties.CONNECT_TIMEOUT, 0);
        socketTimeout = ClientProperties.getValue(config.getProperties(), ClientProperties.READ_TIMEOUT, 0);
        ignoreCookies = PropertiesHelper.isProperty(config.getProperties(),
                ApacheClientProperties.DISABLE_COOKIES);

        final Object credentialsProvider = config.getProperty(ApacheClientProperties.CREDENTIALS_PROVIDER);
        if (credentialsProvider != null && (credentialsProvider instanceof CredentialsProvider)) {
            clientBuilder.setDefaultCredentialsProvider((CredentialsProvider) credentialsProvider);
        }

        Object proxyUri;
        proxyUri = config.getProperty(ClientProperties.PROXY_URI);
        if (proxyUri != null) {
            final URI u = getProxyUri(proxyUri);
            final HttpHost proxy = new HttpHost(u.getHost(), u.getPort(), u.getScheme());
            String userName;
            userName = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_USERNAME,
                    String.class);
            if (userName != null) {
                String password;
                password = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_PASSWORD,
                        String.class);

                if (password != null) {
                    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
                    credsProvider.setCredentials(new AuthScope(u.getHost(), u.getPort()),
                            new UsernamePasswordCredentials(userName, password));
                    clientBuilder.setDefaultCredentialsProvider(credsProvider);
                }
            }
            clientBuilder.setProxy(proxy);
        }

        final Boolean preemptiveBasicAuthProperty = (Boolean) config.getProperties()
                .get(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION);
        this.preemptiveBasicAuth = (preemptiveBasicAuthProperty != null) ? preemptiveBasicAuthProperty : false;
    } else {
        this.preemptiveBasicAuth = false;
    }

    if (reqConfig != null) {
        RequestConfig.Builder reqConfigBuilder = RequestConfig.copy((RequestConfig) reqConfig);
        if (connectTimeout > 0) {
            reqConfigBuilder.setConnectTimeout(connectTimeout);
        }
        if (socketTimeout > 0) {
            reqConfigBuilder.setSocketTimeout(socketTimeout);
        }
        if (ignoreCookies) {
            reqConfigBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES);
        }
        requestConfig = reqConfigBuilder.build();
    } else {
        requestConfigBuilder.setConnectTimeout(connectTimeout);
        requestConfigBuilder.setSocketTimeout(socketTimeout);
        if (ignoreCookies) {
            requestConfigBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES);
        }
        requestConfig = requestConfigBuilder.build();
    }

    if (requestConfig.getCookieSpec() == null
            || !requestConfig.getCookieSpec().equals(CookieSpecs.IGNORE_COOKIES)) {
        this.cookieStore = new BasicCookieStore();
        clientBuilder.setDefaultCookieStore(cookieStore);
    } else {
        this.cookieStore = null;
    }
    clientBuilder.setDefaultRequestConfig(requestConfig);
    this.client = clientBuilder.build();
}

From source file:org.ow2.proactive.http.CommonHttpClientBuilder.java

public CloseableHttpClient build() {
    org.apache.http.impl.client.HttpClientBuilder internalHttpClientBuilder = createInternalHttpClientBuilder();

    if (useSystemProperties) {
        internalHttpClientBuilder.useSystemProperties();
    }//  ww  w.  ja  va  2  s.c  o m

    if (overrideAllowAnyHostname != null) {
        if (overrideAllowAnyHostname) {
            acceptAnyHostname = true;
        } else {
            acceptAnyHostname = false;
        }
    }

    if (overrideAllowAnyCertificate != null) {
        if (overrideAllowAnyCertificate) {
            acceptAnyCertificate = true;
        } else {
            acceptAnyCertificate = false;
        }
    }

    if (acceptAnyCertificate) {
        internalHttpClientBuilder.setSslcontext(createSslContext());
    }

    if (acceptAnyHostname) {
        internalHttpClientBuilder.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    }

    if (maxConnections > 0) {
        internalHttpClientBuilder.setMaxConnPerRoute(maxConnections);
        internalHttpClientBuilder.setMaxConnTotal(maxConnections);
    }

    if (requestConfig != null) {
        internalHttpClientBuilder.setDefaultRequestConfig(requestConfig);
    }

    if (!useContentCompression) {
        internalHttpClientBuilder.disableContentCompression();
    }

    return internalHttpClientBuilder.build();
}

From source file:sachin.spider.WebSpider.java

/**
 *
 * @param config/* w  w w.  j a v a 2s . c  om*/
 * @param latch
 */
@SuppressWarnings("deprecation")
public void setValues(SpiderConfig config, CountDownLatch latch) {
    try {
        this.config = config;
        this.latch = latch;
        HttpClientBuilder builder = HttpClientBuilder.create();
        builder.setUserAgent(config.getUserAgentString());
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

            @Override
            public boolean isTrusted(java.security.cert.X509Certificate[] xcs, String string)
                    throws java.security.cert.CertificateException {
                return true;
            }
        }).build();
        builder.setSslcontext(sslContext);
        HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                hostnameVerifier);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory).build();
        cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        cm.setDefaultMaxPerRoute(config.getTotalSpiders() * 2);
        cm.setMaxTotal(config.getTotalSpiders() * 2);
        if (config.isAuthenticate()) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(config.getUsername(), config.getPassword()));
            httpclient = HttpClients.custom().setUserAgent(config.getUserAgentString())
                    .setDefaultCredentialsProvider(credentialsProvider).setConnectionManager(cm).build();

        } else {
            httpclient = HttpClients.custom().setConnectionManager(cm).setUserAgent(config.getUserAgentString())
                    .build();
        }
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
        Logger.getLogger(WebSpider.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.apache.geode.rest.internal.web.GeodeRestClient.java

public HttpResponse doRequest(HttpRequestBase request, String username, String password) throws Exception {
    HttpHost targetHost = new HttpHost(bindAddress, restPort, protocol);

    HttpClientBuilder clientBuilder = HttpClients.custom();
    HttpClientContext clientContext = HttpClientContext.create();

    // configures the clientBuilder and clientContext
    if (username != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(username, password));
        clientBuilder.setDefaultCredentialsProvider(credsProvider);
    }/* w  ww. j  a  v a  2  s .  c  o m*/

    if (useHttps) {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        clientBuilder.setSSLContext(ctx);
        clientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier());
    }

    return clientBuilder.build().execute(targetHost, request, clientContext);
}

From source file:com.norconex.collector.http.client.impl.GenericHttpClientFactory.java

@Override
public HttpClient createHTTPClient(String userAgent) {
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setSslcontext(createSSLContext());
    builder.setSchemePortResolver(createSchemePortResolver());
    builder.setDefaultRequestConfig(createRequestConfig());
    builder.setProxy(createProxy());/*from   w  w w  .j  a v  a  2s.c om*/
    builder.setDefaultCredentialsProvider(createCredentialsProvider());
    builder.setDefaultConnectionConfig(createConnectionConfig());
    builder.setUserAgent(userAgent);
    builder.setMaxConnTotal(maxConnections);
    //builder.setMaxConnPerRoute(maxConnPerRoute)
    buildCustomHttpClient(builder);

    //TODO Put in place a more permanent solution to the following
    //Fix GitHub #17 start
    RedirectStrategy strategy = createRedirectStrategy();
    if (strategy == null) {
        strategy = LaxRedirectStrategy.INSTANCE;
    }
    builder.setRedirectStrategy(new TargetURLRedirectStrategy(strategy));
    //Fix end

    HttpClient httpClient = builder.build();
    if (AUTH_METHOD_FORM.equalsIgnoreCase(authMethod)) {
        authenticateUsingForm(httpClient);
    }
    return httpClient;
}

From source file:com.ibm.ws.lars.rest.RepositoryContext.java

@Override
protected void before() throws InvalidJsonAssetException, IOException, KeyManagementException,
        NoSuchAlgorithmException, KeyStoreException {

    targetHost = new HttpHost(hostname, portNumber, protocol);

    /* Create the HTTPClient that we use to make all HTTP calls */
    HttpClientBuilder b = HttpClientBuilder.create();

    // Trust all certificates
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        @Override//from w  w  w .  ja v a2  s. c  om
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();
    b.setSslcontext(sslContext);

    // By default, it will verify the hostname in the certificate, which should be localhost
    // and therefore should match. If we start running these tests against a LARS server on
    // a different host then we may need disable hostname verification.

    context = HttpClientContext.create();

    httpClient = b.build();

    /*
     * Create the HTTPClientContext with the appropriate credentials. We'll use this whenever we
     * make an HTTP call.
     */
    if (user != null && password != null) {
        credentials = new UsernamePasswordCredentials(user, password);

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                credentials);

        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);

        context.setCredentialsProvider(credsProvider);
        context.setAuthCache(authCache);
    }

    /* Clean the repository but only if the client asked us to. */
    if (cleanRepository) {
        cleanRepo();
    }
}

From source file:org.glassfish.jersey.apache.connector.ApacheConnector.java

/**
 * Create the new Apache HTTP Client connector.
 *
 * @param client JAX-RS client instance for which the connector is being created.
 * @param config client configuration./*from   w  w w .  j a  v  a2s . co m*/
 */
ApacheConnector(final Client client, final Configuration config) {
    final Object connectionManager = config.getProperties().get(ApacheClientProperties.CONNECTION_MANAGER);
    if (connectionManager != null) {
        if (!(connectionManager instanceof HttpClientConnectionManager)) {
            LOGGER.log(Level.WARNING,
                    LocalizationMessages.IGNORING_VALUE_OF_PROPERTY(ApacheClientProperties.CONNECTION_MANAGER,
                            connectionManager.getClass().getName(),
                            HttpClientConnectionManager.class.getName()));
        }
    }

    Object reqConfig = config.getProperties().get(ApacheClientProperties.REQUEST_CONFIG);
    if (reqConfig != null) {
        if (!(reqConfig instanceof RequestConfig)) {
            LOGGER.log(Level.WARNING,
                    LocalizationMessages.IGNORING_VALUE_OF_PROPERTY(ApacheClientProperties.REQUEST_CONFIG,
                            reqConfig.getClass().getName(), RequestConfig.class.getName()));
            reqConfig = null;
        }
    }

    final SSLContext sslContext = client.getSslContext();
    final HttpClientBuilder clientBuilder = HttpClientBuilder.create();

    clientBuilder.setConnectionManager(getConnectionManager(client, config, sslContext));
    clientBuilder.setConnectionManagerShared(PropertiesHelper.getValue(config.getProperties(),
            ApacheClientProperties.CONNECTION_MANAGER_SHARED, false, null));
    clientBuilder.setSslcontext(sslContext);

    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();

    final Object credentialsProvider = config.getProperty(ApacheClientProperties.CREDENTIALS_PROVIDER);
    if (credentialsProvider != null && (credentialsProvider instanceof CredentialsProvider)) {
        clientBuilder.setDefaultCredentialsProvider((CredentialsProvider) credentialsProvider);
    }

    final Object retryHandler = config.getProperties().get(ApacheClientProperties.RETRY_HANDLER);
    if (retryHandler != null && (retryHandler instanceof HttpRequestRetryHandler)) {
        clientBuilder.setRetryHandler((HttpRequestRetryHandler) retryHandler);
    }

    final Object proxyUri;
    proxyUri = config.getProperty(ClientProperties.PROXY_URI);
    if (proxyUri != null) {
        final URI u = getProxyUri(proxyUri);
        final HttpHost proxy = new HttpHost(u.getHost(), u.getPort(), u.getScheme());
        final String userName;
        userName = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_USERNAME,
                String.class);
        if (userName != null) {
            final String password;
            password = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_PASSWORD,
                    String.class);

            if (password != null) {
                final CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(u.getHost(), u.getPort()),
                        new UsernamePasswordCredentials(userName, password));
                clientBuilder.setDefaultCredentialsProvider(credsProvider);
            }
        }
        clientBuilder.setProxy(proxy);
    }

    final Boolean preemptiveBasicAuthProperty = (Boolean) config.getProperties()
            .get(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION);
    this.preemptiveBasicAuth = (preemptiveBasicAuthProperty != null) ? preemptiveBasicAuthProperty : false;

    final boolean ignoreCookies = PropertiesHelper.isProperty(config.getProperties(),
            ApacheClientProperties.DISABLE_COOKIES);

    if (reqConfig != null) {
        final RequestConfig.Builder reqConfigBuilder = RequestConfig.copy((RequestConfig) reqConfig);
        if (ignoreCookies) {
            reqConfigBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES);
        }
        requestConfig = reqConfigBuilder.build();
    } else {
        if (ignoreCookies) {
            requestConfigBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES);
        }
        requestConfig = requestConfigBuilder.build();
    }

    if (requestConfig.getCookieSpec() == null
            || !requestConfig.getCookieSpec().equals(CookieSpecs.IGNORE_COOKIES)) {
        this.cookieStore = new BasicCookieStore();
        clientBuilder.setDefaultCookieStore(cookieStore);
    } else {
        this.cookieStore = null;
    }
    clientBuilder.setDefaultRequestConfig(requestConfig);
    this.client = clientBuilder.build();
}

From source file:com.rabbitmq.http.client.Client.java

private HttpComponentsClientHttpRequestFactory getRequestFactory(final URL url, final String username,
        final String password, final SSLConnectionSocketFactory sslConnectionSocketFactory,
        final SSLContext sslContext) throws MalformedURLException {
    String theUser = username;/*from www.  j  a v a 2 s .  co  m*/
    String thePassword = password;
    String userInfo = url.getUserInfo();
    if (userInfo != null && theUser == null) {
        String[] userParts = userInfo.split(":");
        if (userParts.length > 0) {
            theUser = userParts[0];
        }
        if (userParts.length > 1) {
            thePassword = userParts[1];
        }
    }
    final HttpClientBuilder bldr = HttpClientBuilder.create()
            .setDefaultCredentialsProvider(getCredentialsProvider(url, theUser, thePassword));
    bldr.setDefaultHeaders(Arrays.asList(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json")));
    if (sslConnectionSocketFactory != null) {
        bldr.setSSLSocketFactory(sslConnectionSocketFactory);
    }
    if (sslContext != null) {
        bldr.setSslcontext(sslContext);
    }

    HttpClient httpClient = bldr.build();

    // RabbitMQ HTTP API currently does not support challenge/response for PUT methods.
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicScheme = new BasicScheme();
    authCache.put(new HttpHost(rootUri.getHost(), rootUri.getPort(), rootUri.getScheme()), basicScheme);
    final HttpClientContext ctx = HttpClientContext.create();
    ctx.setAuthCache(authCache);
    return new HttpComponentsClientHttpRequestFactory(httpClient) {
        @Override
        protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
            return ctx;
        }
    };
}