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

The following examples show how to use org.apache.http.config.RegistryBuilder#register() . 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: 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 3
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 4
Source File: HTTPConnections.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected Registry<ConnectionSocketFactory> getRegistry() {
  if (this.protocolregistry == null) {
    RegistryBuilder rb = RegistryBuilder.<ConnectionSocketFactory>create();
    for (HashMap.Entry<String, ConnectionSocketFactory> entry : protocols.entrySet()) {
      rb.register(entry.getKey(), entry.getValue());
    }
    this.protocolregistry = rb.build();
  }
  return this.protocolregistry;
}
 
Example 5
Source File: CommonsDataLoader.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private RegistryBuilder<ConnectionSocketFactory> setConnectionManagerSchemeHttps(
		final RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistryBuilder) {
	try {

		SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();
		sslContextBuilder.setProtocol(sslProtocol);
		
		TrustStrategy trustStrategy = getTrustStrategy();
		if (trustStrategy != null) {
			LOG.debug("Set the TrustStrategy");
			sslContextBuilder.loadTrustMaterial(null, trustStrategy);
		}

		final KeyStore sslTrustStore = getSSLTrustStore();
		if (sslTrustStore != null) {
			LOG.debug("Set the SSL trust store as trust materials");
			sslContextBuilder.loadTrustMaterial(sslTrustStore, trustStrategy);
		}

		final KeyStore sslKeystore = getSSLKeyStore();
		if (sslKeystore != null) {
			LOG.debug("Set the SSL keystore as key materials");
			final char[] password = sslKeystorePassword != null ? sslKeystorePassword.toCharArray() : null;
			sslContextBuilder.loadKeyMaterial(sslKeystore, password);
			if (loadKeyStoreAsTrustMaterial) {
				LOG.debug("Set the SSL keystore as trust materials");
				sslContextBuilder.loadTrustMaterial(sslKeystore, trustStrategy);
			}
		}

		SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), getSupportedSSLProtocols(),
				getSupportedSSLCipherSuites(), getHostnameVerifier());
		return socketFactoryRegistryBuilder.register("https", sslConnectionSocketFactory);
	} catch (final Exception e) {
		throw new DSSException("Unable to configure the SSLContext/SSLConnectionSocketFactory", e);
	}
}
 
Example 6
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 7
Source File: BaseClient.java    From galaxy-sdk-java with Apache License 2.0 5 votes vote down vote up
private HttpClient createHttpClient(ConnectionConfig config) {
  RequestConfig requestConfig = RequestConfig.custom()
      .setConnectTimeout(config.getConnectionTimeoutMs())
      .setSocketTimeout(config.getSocketTimeoutMs())
      .build();

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

  if (config.isHttpsEnabled()) {
    SSLContext sslContext = SSLContexts.createSystemDefault();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
        sslContext,
        SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    registryBuilder.register("https", sslsf);
  }
  connectionManager = new PoolingHttpClientConnectionManager(registryBuilder.build());
  connectionManager.setDefaultMaxPerRoute(config.getMaxConnection());
  connectionManager.setMaxTotal(config.getMaxConnection());

  HttpClient httpClient = HttpClients.custom()
      .setConnectionManager(connectionManager)
      .setDefaultRequestConfig(requestConfig)
      .setRetryHandler(new DefaultHttpRequestRetryHandler(3, false))
      .build();
  return httpClient;
}
 
Example 8
Source File: AvaticaCommonsHttpClientImpl.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
protected void configureHttpsRegistry(RegistryBuilder<ConnectionSocketFactory> registryBuilder) {
  try {
    SSLContext sslContext = getSSLContext();
    final HostnameVerifier verifier = getHostnameVerifier(hostnameVerification);
    SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory(sslContext, verifier);
    registryBuilder.register("https", sslFactory);
  } catch (Exception e) {
    LOG.error("HTTPS registry configuration failed");
    throw new RuntimeException(e);
  }
}
 
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: 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 11
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 12
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 13
Source File: AvaticaCommonsHttpClientImpl.java    From calcite-avatica with Apache License 2.0 4 votes vote down vote up
protected void configureHttpRegistry(RegistryBuilder<ConnectionSocketFactory> registryBuilder) {
  registryBuilder.register("http", PlainConnectionSocketFactory.getSocketFactory());
}
 
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: SharedHttpClientConnectionManager.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
private static Registry<ConnectionSocketFactory> createRegistry(final List<SSLContextSelector> sslContextSelectors) {
  RegistryBuilder<ConnectionSocketFactory> builder = RegistryBuilder.create();
  builder.register(HTTP, PlainConnectionSocketFactory.getSocketFactory());
  builder.register(HTTPS, new NexusSSLConnectionSocketFactory(sslContextSelectors));
  return builder.build();
}
 
Example 16
Source File: CommonsDataLoader.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
private RegistryBuilder<ConnectionSocketFactory> setConnectionManagerSchemeHttp(RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistryBuilder) {
	return socketFactoryRegistryBuilder.register("http", PlainConnectionSocketFactory.getSocketFactory());
}
 
Example 17
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 18
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 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();
}