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

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

Introduction

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

Prototype

public CloseableHttpClient build() 

Source Link

Usage

From source file:io.cloudslang.content.httpclient.ScoreHttpClient.java

public HttpComponents buildHttpComponents(HttpClientInputs httpClientInputs) {
    buildDefaultServices();//from  w  ww.j  av  a  2 s . c o m

    URI uri = uriBuilder.setUrl(httpClientInputs.getUrl()).setQueryParams(httpClientInputs.getQueryParams())
            .setQueryParamsAreURLEncoded(httpClientInputs.getQueryParamsAreURLEncoded())
            .setQueryParamsAreFormEncoded(httpClientInputs.getQueryParamsAreFormEncoded()).buildURI();

    ContentType theContentType = contentTypeBuilder.setContentType(httpClientInputs.getContentType())
            .setRequestCharacterSet(httpClientInputs.getRequestCharacterSet()).buildContentType();

    HttpEntity httpEntity = httpEntityBuilder.setFormParams(httpClientInputs.getFormParams())
            .setFormParamsAreURLEncoded(httpClientInputs.getFormParamsAreURLEncoded())
            .setBody(httpClientInputs.getBody()).setFilePath(httpClientInputs.getSourceFile())
            .setContentType(theContentType)
            .setMultipartValuesAreURLEncoded(httpClientInputs.getMultipartValuesAreURLEncoded())
            .setMultipartBodies(httpClientInputs.getMultipartBodies())
            .setMultipartFiles(httpClientInputs.getMultipartFiles())
            .setMultipartBodiesContentType(httpClientInputs.getMultipartBodiesContentType())
            .setMultipartFilesContentType(httpClientInputs.getMultipartFilesContentType())
            .setChunkedRequestEntity(httpClientInputs.getChunkedRequestEntity()).buildEntity();

    HttpRequestBase httpRequestBase = requestBuilder.setMethod(httpClientInputs.getMethod()).setUri(uri)
            .setEntity(httpEntity).build();

    List<Header> theHeaders = headersBuilder.setHeaders(httpClientInputs.getHeaders())
            .setContentType(theContentType)
            .setEntityContentType(httpEntity != null ? httpEntity.getContentType() : null).buildHeaders();

    RequestConfig requestConfig = requestConfigBuilder
            .setConnectionTimeout(httpClientInputs.getConnectTimeout())
            .setSocketTimeout(httpClientInputs.getSocketTimeout())
            .setFollowRedirects(httpClientInputs.getFollowRedirects())
            .setProxyHost(httpClientInputs.getProxyHost()).setProxyPort(httpClientInputs.getProxyPort())
            .buildRequestConfig();
    httpRequestBase.setConfig(requestConfig);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    AuthTypes authTypes = new AuthTypes(httpClientInputs.getAuthType());

    CredentialsProvider credentialsProvider = credentialsProviderBuilder.setAuthTypes(authTypes)
            .setUsername(httpClientInputs.getUsername()).setPassword(httpClientInputs.getPassword())
            .setHost(uri.getHost()).setPort(String.valueOf(uri.getPort()))
            .setProxyUsername(httpClientInputs.getProxyUsername())
            .setProxyPassword(httpClientInputs.getProxyPassword()).setProxyHost(httpClientInputs.getProxyHost())
            .setProxyPort(httpClientInputs.getProxyPort()).buildCredentialsProvider();
    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);

    Lookup<AuthSchemeProvider> authSchemeLookup = authSchemeProviderLookupBuilder.setAuthTypes(authTypes)
            .setHost(uri.getHost()).setHeaders(theHeaders)
            .setSkipPortAtKerberosDatabaseLookup(httpClientInputs.getKerberosSkipPortCheck())
            .setKerberosConfigFile(httpClientInputs.getKerberosConfFile())
            .setKerberosLoginConfigFile(httpClientInputs.getKerberosLoginConfFile())
            .setUsername(httpClientInputs.getUsername()).setPassword(httpClientInputs.getPassword())
            .buildAuthSchemeProviderLookup();
    httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeLookup);

    httpRequestBase.setHeaders(theHeaders.toArray(new Header[theHeaders.size()]));

    CookieStore cookieStore = cookieStoreBuilder.setUseCookies(httpClientInputs.getUseCookies())
            .setCookieStoreSessionObject(httpClientInputs.getCookieStoreSessionObject()).buildCookieStore();
    if (cookieStore != null) {
        httpClientBuilder.setDefaultCookieStore(cookieStore);
    }

    SSLConnectionSocketFactory sslConnectionSocketFactory = sslConnectionSocketFactoryBuilder
            .setTrustAllRoots(httpClientInputs.getTrustAllRoots()).setKeystore(httpClientInputs.getKeystore())
            .setKeystorePassword(httpClientInputs.getKeystorePassword())
            .setTrustKeystore(httpClientInputs.getTrustKeystore())
            .setTrustPassword(httpClientInputs.getTrustPassword())
            .setX509HostnameVerifier(httpClientInputs.getX509HostnameVerifier()).build();

    String connectionKey = ConnectionManagerBuilder.buildConnectionManagerMapKey(
            httpClientInputs.getTrustAllRoots(), httpClientInputs.getX509HostnameVerifier(),
            httpClientInputs.getKeystore(), httpClientInputs.getTrustKeystore());
    PoolingHttpClientConnectionManager connManager = poolingHttpClientConnectionManagerBuilder
            .setConnectionManagerMapKey(connectionKey)
            .setConnectionPoolHolder(httpClientInputs.getConnectionPoolSessionObject())
            .setSslsf(sslConnectionSocketFactory)
            .setDefaultMaxPerRoute(httpClientInputs.getConnectionsMaxPerRoute())
            .setTotalMax(httpClientInputs.getConnectionsMaxTotal()).buildConnectionManager();

    httpClientBuilder.setConnectionManager(connManager);

    if (StringUtils.isEmpty(httpClientInputs.getKeepAlive())
            || Boolean.parseBoolean(httpClientInputs.getKeepAlive())) {
        httpClientBuilder.setConnectionReuseStrategy(DefaultConnectionReuseStrategy.INSTANCE);
    } else {
        httpClientBuilder.setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE);
    }

    CloseableHttpClient closeableHttpClient = httpClientBuilder.build();

    HttpClientContext context = contextBuilder.setAuthSchemeLookup(authSchemeLookup).setAuthTypes(authTypes)
            .setCredentialsProvider(credentialsProvider).setUri(uri)
            .setPreemptiveAuth(httpClientInputs.getPreemptiveAuth()).build();

    HttpComponents result = new HttpComponents();
    result.setCloseableHttpClient(closeableHttpClient);
    result.setHttpRequestBase(httpRequestBase);
    result.setHttpClientContext(context);
    result.setUri(uri);
    result.setConnManager(connManager);
    result.setCookieStore(cookieStore);
    result.setHttpClientBuilder(httpClientBuilder);
    return result;
}

From source file:com.igormaznitsa.mvngolang.AbstractGolangMojo.java

@Nonnull
private synchronized HttpClient getHttpClient(@Nullable final ProxySettings proxy) {
    if (this.httpClient == null) {
        final HttpClientBuilder builder = HttpClients.custom();

        if (proxy != null) {
            if (proxy.hasCredentials()) {
                final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(new AuthScope(proxy.host, proxy.port),
                        new UsernamePasswordCredentials(proxy.username, proxy.password));
                builder.setDefaultCredentialsProvider(credentialsProvider);
                getLog().debug(/* www .j a  v a2s. c  o m*/
                        String.format("Credentials provider has been created for proxy (username : %s): %s",
                                proxy.username, proxy.toString()));
            }

            final String[] ignoreForAddresses = proxy.nonProxyHosts == null ? new String[0]
                    : proxy.nonProxyHosts.split("\\|");
            if (ignoreForAddresses.length > 0) {
                final WildCardMatcher[] matchers = new WildCardMatcher[ignoreForAddresses.length];
                for (int i = 0; i < ignoreForAddresses.length; i++) {
                    matchers[i] = new WildCardMatcher(ignoreForAddresses[i]);
                }

                final HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(
                        new HttpHost(proxy.host, proxy.port, proxy.protocol)) {
                    @Override
                    @Nonnull
                    public HttpRoute determineRoute(@Nonnull final HttpHost host,
                            @Nonnull final HttpRequest request, @Nonnull final HttpContext context)
                            throws HttpException {
                        final String hostName = host.getHostName();
                        for (final WildCardMatcher m : matchers) {
                            if (m.match(hostName)) {
                                getLog().debug("Ignoring proxy for host : " + hostName);
                                return new HttpRoute(host);
                            }
                        }
                        return super.determineRoute(host, request, context);
                    }
                };
                builder.setRoutePlanner(routePlanner);
                getLog().debug(
                        "Route planner tuned to ignore proxy for addresses : " + Arrays.toString(matchers));
            }
        }

        builder.setUserAgent("mvn-golang-wrapper-agent/1.0");
        this.httpClient = builder.build();

    }
    return this.httpClient;
}

From source file:org.openscore.content.httpclient.ScoreHttpClient.java

public HttpComponents buildHttpComponents(HttpClientInputs httpClientInputs) {
    buildDefaultServices();//ww  w. j  av a 2 s  . c  o  m

    URI uri = uriBuilder.setUrl(httpClientInputs.getUrl()).setQueryParams(httpClientInputs.getQueryParams())
            .setQueryParamsAreURLEncoded(httpClientInputs.getQueryParamsAreURLEncoded()).buildURI();

    ContentType theContentType = contentTypeBuilder.setContentType(httpClientInputs.getContentType())
            .setRequestCharacterSet(httpClientInputs.getRequestCharacterSet()).buildContentType();

    HttpEntity httpEntity = httpEntityBuilder.setFormParams(httpClientInputs.getFormParams())
            .setFormParamsAreURLEncoded(httpClientInputs.getFormParamsAreURLEncoded())
            .setBody(httpClientInputs.getBody()).setFilePath(httpClientInputs.getSourceFile())
            .setContentType(theContentType)
            .setMultipartValuesAreURLEncoded(httpClientInputs.getMultipartValuesAreURLEncoded())
            .setMultipartBodies(httpClientInputs.getMultipartBodies())
            .setMultipartFiles(httpClientInputs.getMultipartFiles())
            .setMultipartBodiesContentType(httpClientInputs.getMultipartBodiesContentType())
            .setMultipartFilesContentType(httpClientInputs.getMultipartFilesContentType())
            .setChunkedRequestEntity(httpClientInputs.getChunkedRequestEntity()).buildEntity();

    HttpRequestBase httpRequestBase = requestBuilder.setMethod(httpClientInputs.getMethod()).setUri(uri)
            .setEntity(httpEntity).build();

    List<Header> theHeaders = headersBuilder.setHeaders(httpClientInputs.getHeaders())
            .setContentType(theContentType)
            .setEntityContentType(httpEntity != null ? httpEntity.getContentType() : null).buildHeaders();

    RequestConfig requestConfig = requestConfigBuilder
            .setConnectionTimeout(httpClientInputs.getConnectTimeout())
            .setSocketTimeout(httpClientInputs.getSocketTimeout())
            .setFollowRedirects(httpClientInputs.getFollowRedirects())
            .setProxyHost(httpClientInputs.getProxyHost()).setProxyPort(httpClientInputs.getProxyPort())
            .buildRequestConfig();
    httpRequestBase.setConfig(requestConfig);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    AuthTypes authTypes = new AuthTypes(httpClientInputs.getAuthType());

    CredentialsProvider credentialsProvider = credentialsProviderBuilder.setAuthTypes(authTypes)
            .setUsername(httpClientInputs.getUsername()).setPassword(httpClientInputs.getPassword())
            .setHost(uri.getHost()).setPort(String.valueOf(uri.getPort()))
            .setProxyUsername(httpClientInputs.getProxyUsername())
            .setProxyPassword(httpClientInputs.getProxyPassword()).setProxyHost(httpClientInputs.getProxyHost())
            .setProxyPort(httpClientInputs.getProxyPort()).buildCredentialsProvider();
    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);

    Lookup<AuthSchemeProvider> authSchemeLookup = authSchemeProviderLookupBuilder.setAuthTypes(authTypes)
            .setHost(uri.getHost()).setHeaders(theHeaders)
            .setSkipPortAtKerberosDatabaseLookup(httpClientInputs.getKerberosSkipPortCheck())
            .setKerberosConfigFile(httpClientInputs.getKerberosConfFile())
            .setKerberosLoginConfigFile(httpClientInputs.getKerberosLoginConfFile())
            .setUsername(httpClientInputs.getUsername()).setPassword(httpClientInputs.getPassword())
            .buildAuthSchemeProviderLookup();
    httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeLookup);

    httpRequestBase.setHeaders(theHeaders.toArray(new Header[theHeaders.size()]));

    CookieStore cookieStore = httpClientInputs.getCookieStoreSessionObject() == null ? null
            : cookieStoreBuilder.setUseCookies(httpClientInputs.getUseCookies())
                    .setCookieStoreSessionObject(httpClientInputs.getCookieStoreSessionObject())
                    .buildCookieStore();
    if (cookieStore != null) {
        httpClientBuilder.setDefaultCookieStore(cookieStore);
    }

    SSLConnectionSocketFactory sslConnectionSocketFactory = sslConnectionSocketFactoryBuilder
            .setTrustAllRoots(httpClientInputs.getTrustAllRoots()).setKeystore(httpClientInputs.getKeystore())
            .setKeystorePassword(httpClientInputs.getKeystorePassword())
            .setTrustKeystore(httpClientInputs.getTrustKeystore())
            .setTrustPassword(httpClientInputs.getTrustPassword())
            .setX509HostnameVerifier(httpClientInputs.getX509HostnameVerifier()).build();

    String connectionKey = ConnectionManagerBuilder.buildConnectionManagerMapKey(
            httpClientInputs.getTrustAllRoots(), httpClientInputs.getX509HostnameVerifier(),
            httpClientInputs.getKeystore(), httpClientInputs.getTrustKeystore());
    PoolingHttpClientConnectionManager connManager = poolingHttpClientConnectionManagerBuilder
            .setConnectionManagerMapKey(connectionKey)
            .setConnectionPoolHolder(httpClientInputs.getConnectionPoolSessionObject())
            .setSslsf(sslConnectionSocketFactory)
            .setDefaultMaxPerRoute(httpClientInputs.getConnectionsMaxPerRoute())
            .setTotalMax(httpClientInputs.getConnectionsMaxTotal()).buildConnectionManager();

    httpClientBuilder.setConnectionManager(connManager);

    if (StringUtils.isEmpty(httpClientInputs.getKeepAlive())
            || Boolean.parseBoolean(httpClientInputs.getKeepAlive())) {
        httpClientBuilder.setConnectionReuseStrategy(DefaultConnectionReuseStrategy.INSTANCE);
    } else {
        httpClientBuilder.setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE);
    }

    CloseableHttpClient closeableHttpClient = httpClientBuilder.build();

    HttpClientContext context = contextBuilder.setAuthSchemeLookup(authSchemeLookup).setAuthTypes(authTypes)
            .setCredentialsProvider(credentialsProvider).setUri(uri)
            .setPreemptiveAuth(httpClientInputs.getPreemptiveAuth()).build();

    HttpComponents result = new HttpComponents();
    result.setCloseableHttpClient(closeableHttpClient);
    result.setHttpRequestBase(httpRequestBase);
    result.setHttpClientContext(context);
    result.setUri(uri);
    result.setConnManager(connManager);
    result.setCookieStore(cookieStore);
    return result;
}

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.//  w  w  w .  j av a2s  .c  o  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.cisco.oss.foundation.http.apache.ApacheHttpClient.java

@Override
protected void configureClient() {

    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder.setConnectTimeout(metadata.getConnectTimeout());
    requestBuilder = requestBuilder.setSocketTimeout(metadata.getReadTimeout());
    requestBuilder = requestBuilder.setStaleConnectionCheckEnabled(metadata.isStaleConnectionCheckEnabled());

    RequestConfig requestConfig = requestBuilder.build();

    boolean addSslSupport = StringUtils.isNotEmpty(metadata.getKeyStorePath())
            && StringUtils.isNotEmpty(metadata.getKeyStorePassword());

    boolean addTrustSupport = StringUtils.isNotEmpty(metadata.getTrustStorePath())
            && StringUtils.isNotEmpty(metadata.getTrustStorePassword());

    autoCloseable = metadata.isAutoCloseable();

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    SSLContext sslContext = null;

    try {/*from  w w  w .  j  a v a 2 s . c o  m*/

        String keystoreType = "JKS";
        if (addSslSupport && addTrustSupport) {

            KeyStore keyStore = KeyStore.getInstance(keystoreType);
            keyStore.load(new FileInputStream(metadata.getKeyStorePath()),
                    metadata.getKeyStorePassword().toCharArray());

            KeyStore trustStore = KeyStore.getInstance(keystoreType);
            trustStore.load(new FileInputStream(metadata.getTrustStorePath()),
                    metadata.getTrustStorePassword().toCharArray());

            sslContext = SSLContexts.custom().useProtocol("TLS")
                    .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray())
                    .loadTrustMaterial(trustStore, null).build();

        } else if (addSslSupport) {

            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());

            KeyStore keyStore = KeyStore.getInstance(keystoreType);
            keyStore.load(new FileInputStream(metadata.getKeyStorePath()),
                    metadata.getKeyStorePassword().toCharArray());

            tmf.init(keyStore);

            sslContext = SSLContexts.custom().useProtocol("SSL")
                    .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray()).build();

            sslContext.init(null, tmf.getTrustManagers(), null);

            SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);

            httpClientBuilder.setSSLSocketFactory(sf);

        } else if (addTrustSupport) {

            KeyStore trustStore = KeyStore.getInstance(keystoreType);
            trustStore.load(new FileInputStream(metadata.getTrustStorePath()),
                    metadata.getTrustStorePassword().toCharArray());

            sslContext = SSLContexts.custom().useProtocol("TLS").loadTrustMaterial(trustStore, null).build();

        }

        if (addSslSupport | addTrustSupport) {
            SSLContext.setDefault(sslContext);
            httpClientBuilder.setSslcontext(sslContext);
        }

    } catch (Exception e) {
        LOGGER.error("can't set TLS Support. Error is: {}", e, e);
    }

    httpClientBuilder.setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress())
            .setMaxConnTotal(metadata.getMaxConnectionsTotal()).setDefaultRequestConfig(requestConfig)
            .evictExpiredConnections().evictIdleConnections(metadata.getIdleTimeout(), TimeUnit.MILLISECONDS)
            .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout()));

    HttpAsyncClientBuilder httpAsyncClientBuilder = HttpAsyncClients.custom();

    httpAsyncClientBuilder.setDefaultRequestConfig(requestConfig)
            .setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress())
            .setMaxConnTotal(metadata.getMaxConnectionsTotal())
            .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout()))
            .setSSLContext(sslContext);

    if (metadata.isDisableCookies()) {
        httpClientBuilder.disableCookieManagement();
        httpAsyncClientBuilder.disableCookieManagement();
    }

    if (hostnameVerifier != null) {
        httpClientBuilder.setSSLHostnameVerifier(hostnameVerifier);
        httpAsyncClientBuilder.setSSLHostnameVerifier(hostnameVerifier);
    }

    if (!followRedirects) {
        httpClientBuilder.disableRedirectHandling();
    }

    httpClient = httpClientBuilder.build();

    httpAsyncClient = httpAsyncClientBuilder.build();

    httpAsyncClient.start();

}

From source file:com.cisco.oss.foundation.http.netlifx.apache.ApacheNetflixHttpClient.java

protected void configureClient() {

    clientConfig = new DefaultClientConfigImpl();
    clientConfig.loadProperties(getApiName());
    setLoadBalancer(loadBalancer);// w  w w.j  a v  a 2s.  com
    //        clientConfig.set(CommonClientConfigKey.NIWSServerListClassName, DiscoveryEnabledNIWSServerList.class.getName());
    //        clientConfig.set(IClientConfigKey.Keys.DeploymentContextBasedVipAddresses, metadata.getServiceName());
    //        clientConfig.set(CommonClientConfigKey.NFLoadBalancerRuleClassName, RoundRobinRule.class.getName());
    //        clientConfig.set(CommonClientConfigKey.NFLoadBalancerPingClassName, NIWSDiscoveryPing.class.getName());
    //        clientConfig.set(CommonClientConfigKey.VipAddressResolverClassName, SimpleVipAddressResolver.class.getName());

    if (DiscoveryManager.getInstance().getDiscoveryClient() == null && startEurekaClient) {
        EurekaInstanceConfig eurekaInstanceConfig = new MyDataCenterInstanceConfig(getApiName());
        EurekaClientConfig eurekaClientConfig = new DefaultEurekaClientConfig(getApiName() + ".");
        DiscoveryManager.getInstance().initComponent(eurekaInstanceConfig, eurekaClientConfig);
    }

    loadBalancer.initWithNiwsConfig(clientConfig);

    //        if (HystrixPlugins.getInstance().getMetricsPublisher() == null) {
    //            HystrixPlugins.getInstance().registerMetricsPublisher(HystrixMetricsPublisherDefault.getInstance());
    //        }

    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder.setConnectTimeout(metadata.getConnectTimeout());
    requestBuilder = requestBuilder.setSocketTimeout(metadata.getReadTimeout());
    requestBuilder = requestBuilder.setStaleConnectionCheckEnabled(metadata.isStaleConnectionCheckEnabled());

    RequestConfig requestConfig = requestBuilder.build();

    boolean addSslSupport = StringUtils.isNotEmpty(metadata.getKeyStorePath())
            && StringUtils.isNotEmpty(metadata.getKeyStorePassword());

    boolean addTrustSupport = StringUtils.isNotEmpty(metadata.getTrustStorePath())
            && StringUtils.isNotEmpty(metadata.getTrustStorePassword());

    autoCloseable = metadata.isAutoCloseable();

    autoEncodeUri = metadata.isAutoEncodeUri();
    followRedirects = metadata.isFollowRedirects();

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    SSLContext sslContext = null;

    try {

        String keystoreType = "JKS";
        if (addSslSupport && addTrustSupport) {

            KeyStore keyStore = KeyStore.getInstance(keystoreType);
            keyStore.load(new FileInputStream(metadata.getKeyStorePath()),
                    metadata.getKeyStorePassword().toCharArray());

            KeyStore trustStore = KeyStore.getInstance(keystoreType);
            trustStore.load(new FileInputStream(metadata.getTrustStorePath()),
                    metadata.getTrustStorePassword().toCharArray());

            sslContext = SSLContexts.custom().useProtocol("TLS")
                    .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray())
                    .loadTrustMaterial(trustStore, null).build();

        } else if (addSslSupport) {

            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());

            KeyStore keyStore = KeyStore.getInstance(keystoreType);
            keyStore.load(new FileInputStream(metadata.getKeyStorePath()),
                    metadata.getKeyStorePassword().toCharArray());

            tmf.init(keyStore);

            sslContext = SSLContexts.custom().useProtocol("SSL")
                    .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray()).build();

            sslContext.init(null, tmf.getTrustManagers(), null);

            SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);

            httpClientBuilder.setSSLSocketFactory(sf);

        } else if (addTrustSupport) {

            KeyStore trustStore = KeyStore.getInstance(keystoreType);
            trustStore.load(new FileInputStream(metadata.getTrustStorePath()),
                    metadata.getTrustStorePassword().toCharArray());

            sslContext = SSLContexts.custom().useProtocol("TLS").loadTrustMaterial(trustStore, null).build();

        }

        if (addSslSupport | addTrustSupport) {
            SSLContext.setDefault(sslContext);
            httpClientBuilder.setSslcontext(sslContext);
        }

    } catch (Exception e) {
        LOGGER.error("can't set TLS Support. Error is: {}", e, e);
    }

    httpClientBuilder.setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress())
            .setMaxConnTotal(metadata.getMaxConnectionsTotal()).setDefaultRequestConfig(requestConfig)
            .evictExpiredConnections().evictIdleConnections(metadata.getIdleTimeout(), TimeUnit.MILLISECONDS)
            .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout()));

    HttpAsyncClientBuilder httpAsyncClientBuilder = HttpAsyncClients.custom();

    httpAsyncClientBuilder.setDefaultRequestConfig(requestConfig)
            .setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress())
            .setMaxConnTotal(metadata.getMaxConnectionsTotal())
            .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout()))
            .setSSLContext(sslContext);

    if (metadata.isDisableCookies()) {
        httpClientBuilder.disableCookieManagement();
        httpAsyncClientBuilder.disableCookieManagement();
    }

    if (hostnameVerifier != null) {
        httpClientBuilder.setSSLHostnameVerifier(hostnameVerifier);
        httpAsyncClientBuilder.setSSLHostnameVerifier(hostnameVerifier);
    }

    if (!followRedirects) {
        httpClientBuilder.disableRedirectHandling();
    }

    httpClient = httpClientBuilder.build();

    httpAsyncClient = httpAsyncClientBuilder.build();

    httpAsyncClient.start();

}

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

/**
 * Create the new Apache HTTP Client connector.
 *
 * @param config client configuration.//w  w  w  .  j ava2s.  com
 */
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.apache.manifoldcf.crawler.connectors.sharepoint.SharePointRepository.java

/** Set up a session */
protected void getSession() throws ManifoldCFException {
    if (proxy == null) {
        String serverVersion = params.getParameter(SharePointConfig.PARAM_SERVERVERSION);
        if (serverVersion == null)
            serverVersion = "4.0";
        supportsItemSecurity = !serverVersion.equals("2.0");
        dspStsWorks = serverVersion.equals("2.0") || serverVersion.equals("3.0");
        attachmentsSupported = !serverVersion.equals("2.0");

        String authorityType = params.getParameter(SharePointConfig.PARAM_AUTHORITYTYPE);
        if (authorityType == null)
            authorityType = "ActiveDirectory";

        activeDirectoryAuthority = authorityType.equals("ActiveDirectory");

        serverProtocol = params.getParameter(SharePointConfig.PARAM_SERVERPROTOCOL);
        if (serverProtocol == null)
            serverProtocol = "http";
        try {//  w  ww  . j a  v a2 s  .  c  o m
            String serverPort = params.getParameter(SharePointConfig.PARAM_SERVERPORT);
            if (serverPort == null || serverPort.length() == 0) {
                if (serverProtocol.equals("https"))
                    this.serverPort = 443;
                else
                    this.serverPort = 80;
            } else
                this.serverPort = Integer.parseInt(serverPort);
        } catch (NumberFormatException e) {
            throw new ManifoldCFException(e.getMessage(), e);
        }
        serverLocation = params.getParameter(SharePointConfig.PARAM_SERVERLOCATION);
        if (serverLocation == null)
            serverLocation = "";
        if (serverLocation.endsWith("/"))
            serverLocation = serverLocation.substring(0, serverLocation.length() - 1);
        if (serverLocation.length() > 0 && !serverLocation.startsWith("/"))
            serverLocation = "/" + serverLocation;
        encodedServerLocation = serverLocation;
        serverLocation = decodePath(serverLocation);

        userName = params.getParameter(SharePointConfig.PARAM_SERVERUSERNAME);
        password = params.getObfuscatedParameter(SharePointConfig.PARAM_SERVERPASSWORD);
        int index = userName.indexOf("\\");
        if (index != -1) {
            strippedUserName = userName.substring(index + 1);
            ntlmDomain = userName.substring(0, index);
        } else {
            strippedUserName = null;
            ntlmDomain = null;
        }

        String proxyHost = params.getParameter(SharePointConfig.PARAM_PROXYHOST);
        String proxyPortString = params.getParameter(SharePointConfig.PARAM_PROXYPORT);
        int proxyPort = 8080;
        if (proxyPortString != null && proxyPortString.length() > 0) {
            try {
                proxyPort = Integer.parseInt(proxyPortString);
            } catch (NumberFormatException e) {
                throw new ManifoldCFException(e.getMessage(), e);
            }
        }
        String proxyUsername = params.getParameter(SharePointConfig.PARAM_PROXYUSER);
        String proxyPassword = params.getParameter(SharePointConfig.PARAM_PROXYPASSWORD);
        String proxyDomain = params.getParameter(SharePointConfig.PARAM_PROXYDOMAIN);

        serverUrl = serverProtocol + "://" + serverName;
        if (serverProtocol.equals("https")) {
            if (serverPort != 443)
                serverUrl += ":" + Integer.toString(serverPort);
        } else {
            if (serverPort != 80)
                serverUrl += ":" + Integer.toString(serverPort);
        }

        fileBaseUrl = serverUrl + encodedServerLocation;

        // Set up ssl if indicated
        keystoreData = params.getParameter(SharePointConfig.PARAM_SERVERKEYSTORE);

        int connectionTimeout = 60000;
        int socketTimeout = 900000;

        connectionManager = new PoolingHttpClientConnectionManager();

        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        SSLConnectionSocketFactory myFactory = null;
        if (keystoreData != null) {
            keystoreManager = KeystoreManagerFactory.make("", keystoreData);
            myFactory = new SSLConnectionSocketFactory(keystoreManager.getSecureSocketFactory(),
                    new BrowserCompatHostnameVerifier());
        }

        if (strippedUserName != null) {
            credentialsProvider.setCredentials(new AuthScope(serverName, serverPort),
                    new NTCredentials(strippedUserName, password, currentHost, ntlmDomain));
        }

        RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
                .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true)
                .setExpectContinueEnabled(false).setConnectTimeout(connectionTimeout)
                .setConnectionRequestTimeout(socketTimeout);

        // If there's a proxy, set that too.
        if (proxyHost != null && proxyHost.length() > 0) {

            // Configure proxy authentication
            if (proxyUsername != null && proxyUsername.length() > 0) {
                if (proxyPassword == null)
                    proxyPassword = "";
                if (proxyDomain == null)
                    proxyDomain = "";

                credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                        new NTCredentials(proxyUsername, proxyPassword, currentHost, proxyDomain));
            }

            HttpHost proxy = new HttpHost(proxyHost, proxyPort);

            requestBuilder.setProxy(proxy);
        }

        HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connectionManager)
                .setMaxConnTotal(1).disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build())
                .setDefaultSocketConfig(
                        SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
                .setDefaultCredentialsProvider(credentialsProvider);
        if (myFactory != null)
            builder.setSSLSocketFactory(myFactory);
        builder.setRequestExecutor(new HttpRequestExecutor(socketTimeout))
                .setRedirectStrategy(new DefaultRedirectStrategy());
        httpClient = builder.build();

        proxy = new SPSProxyHelper(serverUrl, encodedServerLocation, serverLocation, userName, password,
                org.apache.manifoldcf.connectorcommon.common.CommonsHTTPSender.class, "client-config.wsdd",
                httpClient);

    }
    sessionTimeout = System.currentTimeMillis() + sessionExpirationInterval;
}