Java Code Examples for org.apache.http.config.RegistryBuilder#build()

The following examples show how to use org.apache.http.config.RegistryBuilder#build() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LoginLogic.java    From raccoon4 with Apache License 2.0 6 votes vote down vote up
protected static HttpClient createLoginClient() {
	RegistryBuilder<ConnectionSocketFactory> rb = RegistryBuilder.create();
	rb.register("https", new DroidConnectionSocketFactory());
	// rb.register("http", new DroidConnectionSocketFactory());
	PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
			rb.build());
	connManager.setMaxTotal(100);
	connManager.setDefaultMaxPerRoute(30);
	// TODO: Increase the max connection limits. If we are doing bulkdownloads,
	// we will download from multiple hosts.
	int timeout = 9;
	RequestConfig config = RequestConfig.custom()
			.setConnectTimeout(timeout * 1000)
			.setConnectionRequestTimeout(timeout * 1000)
			.setSocketTimeout(timeout * 1000).build();
	HttpClientBuilder hcb = HttpClientBuilder.create().setDefaultRequestConfig(
			config);

	return hcb.setConnectionManager(connManager).build();
}
 
Example 2
Source File: DockerClient.java    From rapid with MIT License 6 votes vote down vote up
private void init() {
    final URI originalUri = URI.create(DEFAULT_UNIX_ENDPOINT);
    sanitizeUri = UnixFactory.sanitizeUri(originalUri);

    final RegistryBuilder<ConnectionSocketFactory> registryBuilder =
            RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", SSLConnectionSocketFactory.getSocketFactory())
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("unix", new UnixFactory(originalUri));

    final PoolingHttpClientConnectionManager cm =
            new PoolingHttpClientConnectionManager(registryBuilder.build());

    final RequestConfig requestConfig = RequestConfig.custom()
            .setConnectionRequestTimeout((int) SECONDS.toMillis(5))
            .setConnectTimeout((int) SECONDS.toMillis(5))
            .setSocketTimeout((int) SECONDS.toMillis(30))
            .build();

    final ClientConfig config = new ClientConfig()
            .connectorProvider(new ApacheConnectorProvider())
            .property(ApacheClientProperties.CONNECTION_MANAGER, cm)
            .property(ApacheClientProperties.REQUEST_CONFIG, requestConfig);

    client = ClientBuilder.newBuilder().withConfig(config).build();
}
 
Example 3
Source File: ClickHouseHttpClientBuilder.java    From clickhouse-jdbc with Apache License 2.0 6 votes vote down vote up
private PoolingHttpClientConnectionManager getConnectionManager()
    throws CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {
    RegistryBuilder<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
      .register("http", PlainConnectionSocketFactory.getSocketFactory());

    if (properties.getSsl()) {
        HostnameVerifier verifier = "strict".equals(properties.getSslMode()) ? SSLConnectionSocketFactory.getDefaultHostnameVerifier() : NoopHostnameVerifier.INSTANCE;
        registry.register("https", new SSLConnectionSocketFactory(getSSLContext(), verifier));
    }

    //noinspection resource
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
        registry.build(),
        null,
        null,
        new IpVersionPriorityResolver(),
        properties.getTimeToLiveMillis(),
        TimeUnit.MILLISECONDS
    );

    connectionManager.setDefaultMaxPerRoute(properties.getDefaultMaxPerRoute());
    connectionManager.setMaxTotal(properties.getMaxTotal());
    connectionManager.setDefaultConnectionConfig(getConnectionConfig());
    return connectionManager;
}
 
Example 4
Source File: TestHttpClient4.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
public void testSSL() throws IOException {

        RegistryBuilder<ConnectionSocketFactory> schemeRegistry = RegistryBuilder.create();

        schemeRegistry.register("https", new SSLConnectionSocketFactory(new DavGatewaySSLSocketFactory(),
                SSLConnectionSocketFactory.getDefaultHostnameVerifier()));

        PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(schemeRegistry.build());
        HttpClientBuilder clientBuilder = HttpClientBuilder.create()
                .disableRedirectHandling()
                .setConnectionManager(poolingHttpClientConnectionManager);
        try (CloseableHttpClient httpClient = clientBuilder.build()) {

            HttpGet httpget = new HttpGet("https://outlook.office365.com");
            try (CloseableHttpResponse response = httpClient.execute(httpget)) {
                assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, response.getStatusLine().getStatusCode());
            }
        }
    }
 
Example 5
Source File: AvaticaCommonsHttpClientImpl.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
@Override public void setUsernamePassword(AuthenticationType authType, String username,
    String password) {
  this.credentials = new UsernamePasswordCredentials(
      Objects.requireNonNull(username), Objects.requireNonNull(password));

  this.credentialsProvider = new BasicCredentialsProvider();
  credentialsProvider.setCredentials(AuthScope.ANY, credentials);

  RegistryBuilder<AuthSchemeProvider> authRegistryBuilder = RegistryBuilder.create();
  switch (authType) {
  case BASIC:
    authRegistryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory());
    break;
  case DIGEST:
    authRegistryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory());
    break;
  default:
    throw new IllegalArgumentException("Unsupported authentiation type: " + authType);
  }
  this.authRegistry = authRegistryBuilder.build();
}
 
Example 6
Source File: ConsulUtils.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private static Registry<ConnectionSocketFactory> setupSchemeRegistry(SSLContext sslContext) {
    RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
    registryBuilder.register("http", PlainConnectionSocketFactory.getSocketFactory());
    if (sslContext != null) {
        registryBuilder.register("https", new SSLConnectionSocketFactory(sslContext));
    }
    return registryBuilder.build();
}
 
Example 7
Source File: YouTrackClient.java    From vk-java-sdk with MIT License 5 votes vote down vote up
public YouTrackClient(String host, String keyStoreType, String keyStorePath, String keyStorePassword, String keyPassword,
                      String trustStoreType, String trustStorePath, String trustStorePassword) {
    this.host = host;

    CookieStore cookieStore = new BasicCookieStore();
    RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(SOCKET_TIMEOUT_MS)
            .setConnectTimeout(CONNECTION_TIMEOUT_MS)
            .setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS)
            .setCookieSpec(CookieSpecs.STANDARD)
            .build();

    LayeredConnectionSocketFactory sslFactory;

    RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", new PlainConnectionSocketFactory());

    if (host.contains("https://")) {
        try {
            sslFactory = initSslContext(keyStoreType, keyStorePath, keyStorePassword, keyPassword, trustStoreType, trustStorePath, trustStorePassword);
            registryBuilder.register("https", sslFactory);
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

    Registry<ConnectionSocketFactory> registry = registryBuilder.build();

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);

    connectionManager.setMaxTotal(MAX_SIMULTANEOUS_CONNECTIONS);
    connectionManager.setDefaultMaxPerRoute(MAX_SIMULTANEOUS_CONNECTIONS);

    client = HttpClients.custom()
            .setConnectionManager(connectionManager)
            .setDefaultRequestConfig(requestConfig)
            .setDefaultCookieStore(cookieStore)
            .build();
}
 
Example 8
Source File: AvaticaCommonsHttpClientImpl.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
protected Registry<ConnectionSocketFactory> configureSocketFactories() {
  RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
  if (host.getSchemeName().equalsIgnoreCase("https")) {
    configureHttpsRegistry(registryBuilder);
  } else {
    configureHttpRegistry(registryBuilder);
  }
  return registryBuilder.build();
}
 
Example 9
Source File: TestHttpClient4.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
public void testBasicAuthentication() throws IOException {
    Settings.setLoggingLevel("org.apache.http", Level.DEBUG);

    RegistryBuilder<ConnectionSocketFactory> schemeRegistry = RegistryBuilder.create();
    schemeRegistry.register("https", new SSLConnectionSocketFactory(new DavGatewaySSLSocketFactory(),
            SSLConnectionSocketFactory.getDefaultHostnameVerifier()));

    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials
            = new UsernamePasswordCredentials(username, password);
    provider.setCredentials(AuthScope.ANY, credentials);

    PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(schemeRegistry.build());
    HttpClientBuilder clientBuilder = HttpClientBuilder.create()
            .disableRedirectHandling()
            .setDefaultCredentialsProvider(provider)
            .setConnectionManager(poolingHttpClientConnectionManager);
    try (CloseableHttpClient httpClient = clientBuilder.build()) {

        HttpGet httpget = new HttpGet("https://outlook.office365.com/EWS/Exchange.asmx");
        try (CloseableHttpResponse response = httpClient.execute(httpget)) {
            assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
            String responseString = new BasicResponseHandler().handleResponse(response);
            System.out.println(responseString);
        }
    }
}
 
Example 10
Source File: HttpClientAdapter.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
private Registry<AuthSchemeProvider> getAuthSchemeRegistry() {
    final RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder.create();
    registryBuilder.register(AuthSchemes.NTLM, new JCIFSNTLMSchemeFactory())
            .register(AuthSchemes.BASIC, new BasicSchemeFactory())
            .register(AuthSchemes.DIGEST, new DigestSchemeFactory());
    if (Settings.getBooleanProperty("davmail.enableKerberos")) {
        registryBuilder.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
                .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory());
    }

    return registryBuilder.build();
}
 
Example 11
Source File: HttpsFactory.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
public CloseableHttpClient createSecureHttpClient() {
    Registry<ConnectionSocketFactory> socketFactoryRegistry;
    RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistryBuilder = RegistryBuilder
            .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory());

    socketFactoryRegistryBuilder.register("https", createSslSocketFactory());
    socketFactoryRegistry = socketFactoryRegistryBuilder.build();

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
            Objects.requireNonNull(socketFactoryRegistry));
    return HttpClientBuilder.create().setConnectionManager(connectionManager).disableCookieManagement()
            .disableAuthCaching().build();
}
 
Example 12
Source File: JerseyDockerHttpClient.java    From docker-java with Apache License 2.0 5 votes vote down vote up
private Registry<ConnectionSocketFactory> getSchemeRegistry(URI originalUri, SSLContext sslContext) {
    RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
    registryBuilder.register("http", PlainConnectionSocketFactory.getSocketFactory());
    if (sslContext != null) {
        registryBuilder.register("https", new SSLConnectionSocketFactory(sslContext));
    }
    registryBuilder.register("unix", new UnixConnectionSocketFactory(originalUri));
    return registryBuilder.build();
}
 
Example 13
Source File: TestHttpClient4.java    From davmail with GNU General Public License v2.0 4 votes vote down vote up
public void testTimeoutsWithProxy() throws IOException, InterruptedException {
    Settings.setLoggingLevel("org.apache.http", Level.DEBUG);
    Settings.setLoggingLevel("org.apache.http.impl.conn", Level.DEBUG);

    RegistryBuilder<ConnectionSocketFactory> schemeRegistry = RegistryBuilder.create();
    schemeRegistry.register("http", new PlainConnectionSocketFactory());
    schemeRegistry.register("https", new SSLConnectionSocketFactory(new DavGatewaySSLSocketFactory(),
            SSLConnectionSocketFactory.getDefaultHostnameVerifier()));

    Registry<ConnectionSocketFactory> registry = schemeRegistry.build();

    RequestConfig config = RequestConfig.custom()
            // time to get request from the pool
            .setConnectionRequestTimeout(5000)
            // socket connect timeout
            .setConnectTimeout(5000)
            // inactivity timeout
            .setSocketTimeout(5000)
            // disable redirect
            .setRedirectsEnabled(false)
            .build();
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
    HttpClientBuilder clientBuilder = HttpClientBuilder.create()
            .disableRedirectHandling()
            .setDefaultRequestConfig(config)
            .setConnectionManager(connectionManager);
    String proxyHost = Settings.getProperty("davmail.proxyHost");
    int proxyPort = Settings.getIntProperty("davmail.proxyPort");
    HttpHost proxy = new HttpHost(proxyHost, proxyPort);
    clientBuilder.setProxy(proxy);

    clientBuilder.setDefaultCredentialsProvider(getProxyCredentialProvider());

    IdleConnectionEvictor evictor = new IdleConnectionEvictor(connectionManager, 1, TimeUnit.MINUTES);
    evictor.start();

    try (CloseableHttpClient httpClient = clientBuilder.build()) {

        HttpGet httpget = new HttpGet("http://davmail.sourceforge.net/version.txt");

        try (CloseableHttpResponse response = httpClient.execute(httpget)) {
            assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
            String responseString = new BasicResponseHandler().handleResponse(response);
            System.out.println(responseString);
        }
        while (connectionManager.getTotalStats().getAvailable() > 0) {
            Thread.sleep(5000);
            System.out.println("Pool: " + connectionManager.getTotalStats());
        }
    } finally {
        evictor.shutdown();
    }

}
 
Example 14
Source File: TestHttpClient4.java    From davmail with GNU General Public License v2.0 4 votes vote down vote up
public void testTimeouts() throws IOException, InterruptedException {
    Settings.setLoggingLevel("org.apache.http", Level.DEBUG);
    Settings.setLoggingLevel("org.apache.http.impl.conn", Level.DEBUG);

    RegistryBuilder<ConnectionSocketFactory> schemeRegistry = RegistryBuilder.create();
    schemeRegistry.register("http", new PlainConnectionSocketFactory());
    schemeRegistry.register("https", new SSLConnectionSocketFactory(new DavGatewaySSLSocketFactory(),
            SSLConnectionSocketFactory.getDefaultHostnameVerifier()));

    Registry<ConnectionSocketFactory> registry = schemeRegistry.build();

    RequestConfig config = RequestConfig.custom()
            // time to get request from the pool
            .setConnectionRequestTimeout(5000)
            // socket connect timeout
            .setConnectTimeout(5000)
            // inactivity timeout
            .setSocketTimeout(5000)
            // disable redirect
            .setRedirectsEnabled(false)
            .build();
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
    HttpClientBuilder clientBuilder = HttpClientBuilder.create()
            .disableRedirectHandling()
            .setDefaultRequestConfig(config)
            .setConnectionManager(connectionManager);

    IdleConnectionEvictor evictor = new IdleConnectionEvictor(connectionManager, 1, TimeUnit.MINUTES);
    evictor.start();

    try (CloseableHttpClient httpClient = clientBuilder.build()) {

        HttpGet httpget = new HttpGet("http://davmail.sourceforge.net/version.txt");

        try (CloseableHttpResponse response = httpClient.execute(httpget)) {
            assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
            String responseString = new BasicResponseHandler().handleResponse(response);
            System.out.println(responseString);
        }
        while (connectionManager.getTotalStats().getAvailable() > 0) {
            Thread.sleep(5000);
            System.out.println("Pool: " + connectionManager.getTotalStats());
        }
    } finally {
        evictor.shutdown();
    }

}
 
Example 15
Source File: AbstractNativeClientBuilder.java    From jkube with Eclipse Public License 2.0 4 votes vote down vote up
private Registry<ConnectionSocketFactory> buildRegistry(String path) {
    final RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
    registryBuilder.register(getProtocol(), getConnectionSocketFactory());
    return registryBuilder.build();
}
 
Example 16
Source File: AbstractNativeClientBuilder.java    From docker-maven-plugin with Apache License 2.0 4 votes vote down vote up
private Registry<ConnectionSocketFactory> buildRegistry(String path) {
    final RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
    registryBuilder.register(getProtocol(), getConnectionSocketFactory());
    return registryBuilder.build();
}
 
Example 17
Source File: CommonsDataLoader.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
private HttpClientConnectionManager getConnectionManager() {

		RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistryBuilder = RegistryBuilder.create();
		socketFactoryRegistryBuilder = setConnectionManagerSchemeHttp(socketFactoryRegistryBuilder);
		socketFactoryRegistryBuilder = setConnectionManagerSchemeHttps(socketFactoryRegistryBuilder);

		final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistryBuilder.build());

		connectionManager.setMaxTotal(getConnectionsMaxTotal());
		connectionManager.setDefaultMaxPerRoute(getConnectionsMaxPerRoute());

		LOG.debug("PoolingHttpClientConnectionManager: max total: {}", connectionManager.getMaxTotal());
		LOG.debug("PoolingHttpClientConnectionManager: max per route: {}", connectionManager.getDefaultMaxPerRoute());

		return connectionManager;
	}
 
Example 18
Source File: HttpClientUtils.java    From onetwo with Apache License 2.0 4 votes vote down vote up
private static HttpClient createHttpClient0(CookieStore cookieStore) throws KeyStoreException, KeyManagementException, NoSuchAlgorithmException{
		RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create();
		ConnectionSocketFactory http = new PlainConnectionSocketFactory();
		registryBuilder.register("http", http);
		
		/*TrustManager trustManager = new X509TrustManager(){
			@Override
			public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
	  
			}
	  
			@Override
			public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
	  
			}
	  
			@Override
			public X509Certificate[] getAcceptedIssuers() {
				return null;
			}
		}; */
		/***
		 * setConnectTimeout:设置连接超时时间,单位毫秒。
setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
setSocketTimeout:请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
		 */
		RequestConfig reqConfig = createDefaultRequestConfig();
		KeyStore trustStory = KeyStore.getInstance(KeyStore.getDefaultType());
		TrustStrategy anyTrustStrategy = new TrustStrategy(){
			@Override
			public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
				return true;
			}
		};
		SSLContext sslContext = SSLContexts.custom()
											.useProtocol("TLS")
											.loadTrustMaterial(trustStory, anyTrustStrategy)
											.build();
		LayeredConnectionSocketFactory https = new SSLConnectionSocketFactory(sslContext);
		registryBuilder.register("https", https);
		
		Registry<ConnectionSocketFactory> registry = registryBuilder.build();
		PoolingHttpClientConnectionManager poolMgr = new PoolingHttpClientConnectionManager(registry);
		return HttpClientBuilder.create()
								.setDefaultCookieStore(cookieStore)
								.setConnectionManager(poolMgr)
								.setDefaultRequestConfig(reqConfig)
								.build();
	}
 
Example 19
Source File: FDSHttpClient.java    From galaxy-fds-sdk-java with Apache License 2.0 4 votes vote down vote up
private HttpClient createHttpClient(FDSClientConfiguration config) {
  RequestConfig.Builder requestConfigBuilder = RequestConfig.custom()
      .setConnectTimeout(config.getConnectionTimeoutMs())
      .setSocketTimeout(config.getSocketTimeoutMs());

  String proxyHost = config.getProxyHost();

  int proxyPort = config.getProxyPort();

  if (proxyHost != null && proxyPort > 0) {
    HttpHost proxy = new HttpHost(proxyHost, proxyPort);
    requestConfigBuilder.setProxy(proxy);

    String proxyUsername = config.getProxyUsername();
    String proxyPassword = config.getProxyPassword();
    String proxyDomain = config.getProxyDomain();
    String proxyWorkstation = config.getProxyWorkstation();
    if (proxyUsername != null && proxyPassword != null) {
      credentialsProvider = new BasicCredentialsProvider();

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

      authCache = new BasicAuthCache();
      authCache.put(proxy, new BasicScheme());
    }
  }

  RequestConfig requestConfig = requestConfigBuilder.build();

  SocketConfig socketConfig = SocketConfig.custom()
      .setSoTimeout(config.getSocketTimeoutMs())
      .build();

  RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
  registryBuilder.register("http", new ConnectionInfoRecorderSocketFactory(
      new PlainConnectionSocketFactory()));

  if (config.isHttpsEnabled()) {
    SSLContext sslContext = SSLContexts.createSystemDefault();
    SSLConnectionSocketFactory sslConnectionSocketFactory =
        new SSLConnectionInfoRecorderSocketFactory(
        sslContext,
        NoopHostnameVerifier.INSTANCE);
    registryBuilder.register("https", sslConnectionSocketFactory);
  }
  ipBlackList = new TimeBasedIpAddressBlackList(config.getIpAddressNegativeDurationMillsec());
  connectionManager = new PoolingHttpClientConnectionManager(registryBuilder.build(),
      null,
      null,
      new RoundRobinDNSResolver(new InternalSiteBlackListDNSResolver(ipBlackList,
          this.dnsResolver == null ?
              SystemDefaultDnsResolver.INSTANCE : this.dnsResolver)),
      config.getHTTPKeepAliveTimeoutMS(), TimeUnit.MILLISECONDS);
  connectionManager.setDefaultMaxPerRoute(config.getMaxConnection());
  connectionManager.setMaxTotal(config.getMaxConnection());
  connectionManager.setDefaultSocketConfig(socketConfig);
  FDSBlackListEnabledHostChecker fdsBlackListEnabledHostChecker =
      new FDSBlackListEnabledHostChecker();
  retryHandler = new InternalIpBlackListRetryHandler(config.getRetryCount(),
      ipBlackList, fdsBlackListEnabledHostChecker);

  return HttpClients.custom()
      .setRetryHandler(retryHandler)
      .setServiceUnavailableRetryStrategy(new ServiceUnavailableDNSBlackListStrategy(
          config.getRetryCount(),
          config.getRetryIntervalMilliSec(),
          ipBlackList,
          fdsBlackListEnabledHostChecker))
      .setConnectionManager(connectionManager)
      .setDefaultRequestConfig(requestConfig)
      .build();
}
 
Example 20
Source File: HttpConnection.java    From arangodb-java-driver with Apache License 2.0 4 votes vote down vote up
private HttpConnection(final HostDescription host, final Integer timeout, final String user, final String password,
                       final Boolean useSsl, final SSLContext sslContext, final ArangoSerialization util, final Protocol contentType,
                       final Long ttl, final String httpCookieSpec) {
    super();
    this.host = host;
    this.user = user;
    this.password = password;
    this.useSsl = useSsl;
    this.util = util;
    this.contentType = contentType;
    final RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder
            .create();
    if (Boolean.TRUE == useSsl) {
        if (sslContext != null) {
            registryBuilder.register("https", new SSLConnectionSocketFactory(sslContext));
        } else {
            registryBuilder.register("https", new SSLConnectionSocketFactory(SSLContexts.createSystemDefault()));
        }
    } else {
        registryBuilder.register("http", new PlainConnectionSocketFactory());
    }
    cm = new PoolingHttpClientConnectionManager(registryBuilder.build());
    cm.setDefaultMaxPerRoute(1);
    cm.setMaxTotal(1);
    final RequestConfig.Builder requestConfig = RequestConfig.custom();
    if (timeout != null && timeout >= 0) {
        requestConfig.setConnectTimeout(timeout);
        requestConfig.setConnectionRequestTimeout(timeout);
        requestConfig.setSocketTimeout(timeout);
    }

    if (httpCookieSpec != null && httpCookieSpec.length() > 1) {
        requestConfig.setCookieSpec(httpCookieSpec);
    }

    final ConnectionKeepAliveStrategy keepAliveStrategy = (response, context) -> HttpConnection.this.getKeepAliveDuration(response);
    final HttpClientBuilder builder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig.build())
            .setConnectionManager(cm).setKeepAliveStrategy(keepAliveStrategy)
            .setRetryHandler(new DefaultHttpRequestRetryHandler());
    if (ttl != null) {
        builder.setConnectionTimeToLive(ttl, TimeUnit.MILLISECONDS);
    }
    client = builder.build();
}