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

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

Introduction

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

Prototype

public final HttpClientBuilder setConnectionManager(final HttpClientConnectionManager connManager) 

Source Link

Document

Assigns HttpClientConnectionManager instance.

Usage

From source file:gobblin.writer.http.AbstractHttpWriter.java

@SuppressWarnings("rawtypes")
public AbstractHttpWriter(AbstractHttpWriterBuilder builder) {
    super(builder.getState());
    this.log = builder.getLogger().isPresent() ? (Logger) builder.getLogger()
            : LoggerFactory.getLogger(this.getClass());
    this.debugLogEnabled = this.log.isDebugEnabled();

    HttpClientBuilder httpClientBuilder = builder.getHttpClientBuilder();
    httpClientBuilder.setConnectionManager(
            new HttpClientConnectionManagerWithConnTracking(builder.getHttpConnManager()));
    this.client = httpClientBuilder.build();
    this.singleThreadPool = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());

    if (builder.getSvcEndpoint().isPresent()) {
        setCurServerHost((URI) builder.getSvcEndpoint().get());
    }/*from  w  w  w.ja v a  2s  .  c  o  m*/
}

From source file:org.drugis.addis.config.MainConfig.java

@Bean
public HttpClient httpClient(RequestConfig requestConfig) throws KeyStoreException, IOException,
        CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException {
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(new FileInputStream(KEYSTORE_PATH), KEYSTORE_PASSWORD.toCharArray());
    String ADDIS_LOCAL = System.getenv("ADDIS_LOCAL");

    SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadKeyMaterial(keyStore,
            KEYSTORE_PASSWORD.toCharArray());
    if (ADDIS_LOCAL != null) {
        String TRUSTSTORE_PATH = WebConstants.loadSystemEnv("TRUSTSTORE_PATH");
        sslContextBuilder.loadTrustMaterial(new File(TRUSTSTORE_PATH));
    }//from w  w w . ja  va2 s. com
    sslContextBuilder.build();
    SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(
            sslContextBuilder.build());

    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", connectionSocketFactory).register("http", new PlainConnectionSocketFactory())
            .build();
    HttpClientConnectionManager clientConnectionManager = new PoolingHttpClientConnectionManager(registry);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    return httpClientBuilder.setConnectionManager(clientConnectionManager).setMaxConnTotal(20)
            .setMaxConnPerRoute(2).setDefaultRequestConfig(requestConfig).build();
}

From source file:com.crosstreelabs.cognitio.gumshoe.transport.HttpTransport.java

private void buildHttpClient() {
    requestConfig = RequestConfig.custom().setExpectContinueEnabled(false).setCookieSpec(CookieSpecs.DEFAULT)
            .setRedirectsEnabled(false).setSocketTimeout(5000).setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000).setStaleConnectionCheckEnabled(true).build();

    RegistryBuilder<ConnectionSocketFactory> connRegistryBuilder = RegistryBuilder.create();
    connRegistryBuilder.register("http", PlainConnectionSocketFactory.INSTANCE);
    try { // Fixing: https://code.google.com/p/crawler4j/issues/detail?id=174
          // By always trusting the ssl certificate
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            @Override//from www. ja  v a  2  s.  c  o  m
            public boolean isTrusted(final X509Certificate[] chain, String authType) {
                return true;
            }
        }).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        connRegistryBuilder.register("https", sslsf);
    } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException e) {
        LOGGER.warn("Exception thrown while trying to register https");
        LOGGER.debug("Stacktrace", e);
    }

    Registry<ConnectionSocketFactory> connRegistry = connRegistryBuilder.build();
    connectionManager = new PoolingHttpClientConnectionManager(connRegistry);
    connectionManager.setMaxTotal(5);
    connectionManager.setDefaultMaxPerRoute(5);

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setDefaultRequestConfig(requestConfig);
    clientBuilder.setConnectionManager(connectionManager);
    clientBuilder.setUserAgent("Cognitio");

    httpClient = clientBuilder.build();
}

From source file:io.fabric8.kit.build.service.docker.access.hc.util.AbstractNativeClientBuilder.java

@Override
public CloseableHttpClient buildPooledClient() {
    final HttpClientBuilder httpBuilder = HttpClients.custom();
    final PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(registry,
            dnsResolver);/*from  ww w . j  a  va 2s.  co m*/
    manager.setDefaultMaxPerRoute(maxConnections);
    httpBuilder.setConnectionManager(manager);
    return httpBuilder.build();
}

From source file:com.datatorrent.stram.util.WebServicesClient.java

public WebServicesClient(ClientConfig config) {
    if (SecurityUtils.isHadoopWebSecurityEnabled()) {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setConnectionManager(connectionManager);
        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        httpClientBuilder.setDefaultAuthSchemeRegistry(authRegistry);
        ApacheHttpClient4Handler httpClientHandler = new ApacheHttpClient4Handler(httpClientBuilder.build(),
                new BasicCookieStore(), false);
        client = new Client(httpClientHandler, config);
    } else {//from w w w. j  a va2s  .c om
        client = Client.create(config);
    }
}

From source file:com.jaspersoft.studio.data.adapter.JSSBuiltinDataFileServiceFactory.java

@Override
public DataFileService createService(JasperReportsContext context, DataFile dataFile) {
    if (dataFile instanceof RepositoryDataLocation) {
        return new RepositoryDataLocationService(context, (RepositoryDataLocation) dataFile);
    }/*from www .jav  a  2 s  .  com*/
    if (dataFile instanceof HttpDataLocation) {
        return new HttpDataService(context, (HttpDataLocation) dataFile) {
            @Override
            protected CloseableHttpClient createHttpClient(Map<String, Object> parameters) {
                HttpClientBuilder clientBuilder = HttpClients.custom();
                HttpUtils.setupProxy(clientBuilder);
                // single connection
                BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager();
                clientBuilder.setConnectionManager(connManager);

                // ignore cookies for now
                RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES)
                        .build();
                clientBuilder.setDefaultRequestConfig(requestConfig);

                HttpClientContext clientContext = HttpClientContext.create();

                setAuthentication(parameters, clientContext);

                CloseableHttpClient client = clientBuilder.build();
                return client;
            }
        };
    }
    return null;
}

From source file:org.geosamples.utilities.HTTPClient.java

/**
 * This method relaxes SSL constraints because geosamples does not yet
 * provide certificate.//from   ww w . j ava  2  s .  co m
 *
 * @see <a href="http://literatejava.com/networks/ignore-ssl-certificate-errors-apache-httpclient-4-4/">Tom's Blog</a>
 * @return CloseableHttpClient
 * @throws java.security.NoSuchAlgorithmException
 * @throws java.security.KeyStoreException
 * @throws java.security.KeyManagementException
 */
public static CloseableHttpClient clientWithNoSecurityValidation()
        throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();

    // setup a Trust Strategy that allows all certificates.
    SSLContext sslContext = null;

    sslContext = new SSLContextBuilder().loadTrustMaterial(null, (X509Certificate[] arg0, String arg1) -> true)
            .build();

    clientBuilder.setSSLContext(sslContext);

    // don't check Hostnames, either.
    HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;

    // here's the special part:
    //      -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
    //      -- and create a Registry, to register it.
    //
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();

    // now, we create connection-manager using our Registry.
    //      -- allows multi-threaded use
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    clientBuilder.setConnectionManager(connMgr);

    CloseableHttpClient httpClient = clientBuilder.build();

    return httpClient;
}

From source file:fr.treeptik.cloudunit.utils.JSONClient.java

public CloseableHttpClient buildSecureHttpClient(Boolean httpRequired) throws IOException {
    if (isTLSActivated && !httpRequired) {
        org.apache.http.impl.client.HttpClientBuilder builder = HttpClients.custom();
        HttpClientConnectionManager manager = getConnectionFactory(certsDirPath, 10);
        builder.setConnectionManager(manager);
        return builder.build();
    } else {/*from   w w w.j  ava  2s.  c  o  m*/
        return HttpClients.createDefault();
    }
}