org.apache.http.impl.nio.client.HttpAsyncClientBuilder Java Examples

The following examples show how to use org.apache.http.impl.nio.client.HttpAsyncClientBuilder. 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: JfDemoESPlugin.java    From jframe with Apache License 2.0 8 votes vote down vote up
private void startRestClient() {
    try {
        HttpHost[] hosts = new HttpHost[] {
                // new HttpHost("10.132.161.173", 30002, "http")
                new HttpHost("127.0.0.1", 9200, "http") };
        client = RestClient.builder(hosts).setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
            @Override
            public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) {
                return requestConfigBuilder.setConnectTimeout(2000).setSocketTimeout(10000);
            }
        }).setMaxRetryTimeoutMillis(10000).setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
            @Override
            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                return httpClientBuilder.setMaxConnPerRoute(100).setMaxConnTotal(200);
                // return httpClientBuilder
                // .setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(1).build());
            }
        }).build();
    } catch (Exception e) {
        LOG.error(e.getMessage(), e.fillInStackTrace());
    }
}
 
Example #2
Source File: PiwikTracker.java    From matomo-java-tracker with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Get an async HTTP client. With proxy if a proxy is provided in the constructor.
 * @return an async HTTP client
 */
protected CloseableHttpAsyncClient getHttpAsyncClient(){

    HttpAsyncClientBuilder builder = HttpAsyncClientBuilder.create();

    if(proxyHost != null && proxyPort != 0) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
        builder.setRoutePlanner(routePlanner);
    }

    RequestConfig.Builder config = RequestConfig.custom()
            .setConnectTimeout(timeout)
            .setConnectionRequestTimeout(timeout)
            .setSocketTimeout(timeout);

    builder.setDefaultRequestConfig(config.build());

    return builder.build();
}
 
Example #3
Source File: XPackBaseDemo.java    From elasticsearch-full with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    /**
     * 如果es集群安装了x-pack插件则以此种方式连接集群
     * 1. java客户端的方式是以tcp协议在9300端口上进行通信
     * 2. http客户端的方式是以http协议在9200端口上进行通信
     */
    Settings settings = Settings.builder(). put("xpack.security.user", "elastic:changeme").build();
    client = new PreBuiltXPackTransportClient(settings)
            .addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"),9200));
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials("elastic", "changeme"));
    restClient = RestClient.builder(new HttpHost("localhost",9200,"http"))
            .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                @Override
                public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                    return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                }
            }).build();
}
 
Example #4
Source File: ThreadAffinityTest.java    From riptide with MIT License 6 votes vote down vote up
@Test
void syncNonBlockingApache() throws Exception {
    final HttpComponentsAsyncClientHttpRequestFactory requestFactory =
            new HttpComponentsAsyncClientHttpRequestFactory(HttpAsyncClientBuilder.create()
                    .setThreadFactory(threadFactory("io"))
                    .build());

    try {
        final ConfigurationStage stage = Http.builder()
                .asyncRequestFactory(requestFactory);

        test(stage, "main", "io", "io");
    } finally {
        requestFactory.destroy();
    }
}
 
Example #5
Source File: FiberApacheHttpClientRequestExecutor.java    From jbender with Apache License 2.0 6 votes vote down vote up
public FiberApacheHttpClientRequestExecutor(final Validator<CloseableHttpResponse> resValidator, final int maxConnections, final int timeout, final int parallelism) throws IOReactorException {
  final DefaultConnectingIOReactor ioreactor = new DefaultConnectingIOReactor(IOReactorConfig.custom().
    setConnectTimeout(timeout).
    setIoThreadCount(parallelism).
    setSoTimeout(timeout).
    build());

  final PoolingNHttpClientConnectionManager mngr = new PoolingNHttpClientConnectionManager(ioreactor);
  mngr.setDefaultMaxPerRoute(maxConnections);
  mngr.setMaxTotal(maxConnections);

  final CloseableHttpAsyncClient ahc = HttpAsyncClientBuilder.create().
    setConnectionManager(mngr).
    setDefaultRequestConfig(RequestConfig.custom().setLocalAddress(null).build()).build();

  client = new FiberHttpClient(ahc);
  validator = resValidator;
}
 
Example #6
Source File: HttpClientManager.java    From azure-notificationhubs-java-backend with Apache License 2.0 6 votes vote down vote up
private static void initializeHttpAsyncClient() {
    synchronized (HttpClientManager.class) {
        if (httpAsyncClient == null) {
            RequestConfig config = RequestConfig.custom()
                    .setConnectionRequestTimeout(connectionRequestTimeout)
                    .setConnectTimeout(connectionTimeout)
                    .setSocketTimeout(socketTimeout)
                    .build();
            CloseableHttpAsyncClient client = HttpAsyncClientBuilder.create()
                    .setDefaultRequestConfig(config)
                    .build();
            client.start();
            httpAsyncClient = client;
        }
    }
}
 
Example #7
Source File: ODataUtil.java    From syndesis with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link HttpClientBuilder} for the given options.
 *
 * @return the new http client builder
 */
public static HttpAsyncClientBuilder createHttpAsyncClientBuilder(Map<String, Object> options) {
    HttpAsyncClientBuilder builder = HttpAsyncClientBuilder.create();

    SSLContext sslContext = createSSLContext(options);
    if (sslContext != null) {
        // Skip verifying hostname
        HostnameVerifier allowAllHosts = new NoopHostnameVerifier();
        builder.setSSLContext(sslContext);
        builder.setSSLHostnameVerifier(allowAllHosts);
    }

    CredentialsProvider credentialsProvider = createCredentialProvider(options);
    if (credentialsProvider != null) {
        builder.setDefaultCredentialsProvider(credentialsProvider).build();
    }

    return builder;
}
 
Example #8
Source File: HttpAsyncDownloaderBuilder.java    From JMCCC with MIT License 6 votes vote down vote up
protected CloseableHttpAsyncClient buildDefaultHttpAsyncClient() {
	HttpHost httpProxy = resolveProxy(proxy);
	return HttpAsyncClientBuilder.create()
			.setMaxConnTotal(maxConnections)
			.setMaxConnPerRoute(maxConnections)
			.setProxy(httpProxy)
			.setDefaultIOReactorConfig(IOReactorConfig.custom()
					.setConnectTimeout(connectTimeout)
					.setSoTimeout(readTimeout)
					.build())
			.setDefaultRequestConfig(RequestConfig.custom()
					.setConnectTimeout(connectTimeout)
					.setSocketTimeout(readTimeout)
					.setProxy(httpProxy)
					.build())
			.setDefaultHeaders(Arrays.asList(new BasicHeader("Accept-Encoding", "gzip")))
			.build();
}
 
Example #9
Source File: HttpComponentsAsyncClientHttpRequestFactoryTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void defaultSettingsOfHttpAsyncClientLostOnExecutorCustomization() throws Exception {
	CloseableHttpAsyncClient client = HttpAsyncClientBuilder.create()
			.setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(1234).build())
			.build();
	HttpComponentsAsyncClientHttpRequestFactory factory = new HttpComponentsAsyncClientHttpRequestFactory(client);

	URI uri = new URI(baseUrl + "/status/ok");
	HttpComponentsAsyncClientHttpRequest request = (HttpComponentsAsyncClientHttpRequest)
			factory.createAsyncRequest(uri, HttpMethod.GET);

	assertNull("No custom config should be set with a custom HttpClient",
			request.getHttpContext().getAttribute(HttpClientContext.REQUEST_CONFIG));

	factory.setConnectionRequestTimeout(4567);
	HttpComponentsAsyncClientHttpRequest request2 = (HttpComponentsAsyncClientHttpRequest)
			factory.createAsyncRequest(uri, HttpMethod.GET);
	Object requestConfigAttribute = request2.getHttpContext().getAttribute(HttpClientContext.REQUEST_CONFIG);
	assertNotNull(requestConfigAttribute);
	RequestConfig requestConfig = (RequestConfig) requestConfigAttribute;

	assertEquals(4567, requestConfig.getConnectionRequestTimeout());
	// No way to access the request config of the HTTP client so no way to "merge" our customizations
	assertEquals(-1, requestConfig.getConnectTimeout());
}
 
Example #10
Source File: HttpProxyClient.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
private CloseableHttpAsyncClient getAsyncProxyHttpClient(URI proxyUri) {
  LOG.info("Creating async proxy http client");
  PoolingNHttpClientConnectionManager cm = getAsyncConnectionManager();
  HttpHost proxy = new HttpHost(proxyUri.getHost(), proxyUri.getPort());
  
  HttpAsyncClientBuilder clientBuilder = HttpAsyncClients.custom();
  if (cm != null) {
    clientBuilder = clientBuilder.setConnectionManager(cm);
  }

  if (proxy != null) {
    clientBuilder = clientBuilder.setProxy(proxy);
  }
  clientBuilder = setRedirects(clientBuilder);
  return clientBuilder.build();
}
 
Example #11
Source File: HttpProxyClient.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
private HttpAsyncClientBuilder setRedirects(HttpAsyncClientBuilder clientBuilder) {
  clientBuilder.setRedirectStrategy(new DefaultRedirectStrategy() {
    /** Redirectable methods. */
    private String[] REDIRECT_METHODS = new String[] { 
      HttpGet.METHOD_NAME, HttpPost.METHOD_NAME, 
      HttpPut.METHOD_NAME, HttpDelete.METHOD_NAME, HttpHead.METHOD_NAME 
    };

    @Override
    protected boolean isRedirectable(String method) {
      for (String m : REDIRECT_METHODS) {
        if (m.equalsIgnoreCase(method)) {
          return true;
        }
      }
      return false;
    }
  });
  return clientBuilder;
}
 
Example #12
Source File: RestClient.java    From light with Apache License 2.0 6 votes vote down vote up
private CloseableHttpAsyncClient asyncHttpClient() throws Exception {
    PoolingNHttpClientConnectionManager connectionManager = new PoolingNHttpClientConnectionManager(
            ioReactor(), asyncRegistry());
    Map<String, Object> asyncHttpClientMap = (Map<String, Object>)configMap.get(ASYNC_REST_TEMPLATE);
    connectionManager.setMaxTotal((Integer)asyncHttpClientMap.get(MAX_CONNECTION_TOTAL));
    connectionManager.setDefaultMaxPerRoute((Integer) asyncHttpClientMap.get(MAX_CONNECTION_PER_ROUTE));
    // Now handle all the specific route defined.
    Map<String, Object> routeMap = (Map<String, Object>)asyncHttpClientMap.get(ROUTES);
    Iterator<String> it = routeMap.keySet().iterator();
    while (it.hasNext()) {
        String route = it.next();
        Integer maxConnection = (Integer)routeMap.get(route);
        connectionManager.setMaxPerRoute(new HttpRoute(new HttpHost(
                route)), maxConnection);
    }
    RequestConfig config = RequestConfig.custom()
            .setConnectTimeout((Integer) asyncHttpClientMap.get(TIMEOUT_MILLISECONDS))
            .build();

    return HttpAsyncClientBuilder
            .create()
            .setConnectionManager(connectionManager)
            .setDefaultRequestConfig(config)
            .build();
}
 
Example #13
Source File: SaltService.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Default constructor
 */
public SaltService() {
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(0)
            .setSocketTimeout(0)
            .setConnectionRequestTimeout(0)
            .setCookieSpec(CookieSpecs.STANDARD)
            .build();
    HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClients.custom();
    httpClientBuilder.setDefaultRequestConfig(requestConfig);

    asyncHttpClient = httpClientBuilder
            .setMaxConnPerRoute(20)
            .setMaxConnTotal(20)
            .build();
    asyncHttpClient.start();

    SALT_CLIENT = new SaltClient(SALT_MASTER_URI, new HttpAsyncClientImpl(asyncHttpClient));
    saltSSHService = new SaltSSHService(SALT_CLIENT, SaltActionChainGeneratorService.INSTANCE);
    defaultBatch = Batch.custom().withBatchAsAmount(ConfigDefaults.get().getSaltBatchSize())
                    .withDelay(ConfigDefaults.get().getSaltBatchDelay())
                    .withPresencePingTimeout(ConfigDefaults.get().getSaltPresencePingTimeout())
                    .withPresencePingGatherJobTimeout(ConfigDefaults.get().getSaltPresencePingGatherJobTimeout())
                    .build();
}
 
Example #14
Source File: HttpComponentsAsyncClientHttpRequestFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void defaultSettingsOfHttpAsyncClientLostOnExecutorCustomization() throws Exception {
	CloseableHttpAsyncClient client = HttpAsyncClientBuilder.create()
			.setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(1234).build())
			.build();
	HttpComponentsAsyncClientHttpRequestFactory factory = new HttpComponentsAsyncClientHttpRequestFactory(client);

	URI uri = new URI(baseUrl + "/status/ok");
	HttpComponentsAsyncClientHttpRequest request = (HttpComponentsAsyncClientHttpRequest)
			factory.createAsyncRequest(uri, HttpMethod.GET);

	assertNull("No custom config should be set with a custom HttpClient",
			request.getHttpContext().getAttribute(HttpClientContext.REQUEST_CONFIG));

	factory.setConnectionRequestTimeout(4567);
	HttpComponentsAsyncClientHttpRequest request2 = (HttpComponentsAsyncClientHttpRequest)
			factory.createAsyncRequest(uri, HttpMethod.GET);
	Object requestConfigAttribute = request2.getHttpContext().getAttribute(HttpClientContext.REQUEST_CONFIG);
	assertNotNull(requestConfigAttribute);
	RequestConfig requestConfig = (RequestConfig) requestConfigAttribute;

	assertEquals(4567, requestConfig.getConnectionRequestTimeout());
	// No way to access the request config of the HTTP client so no way to "merge" our customizations
	assertEquals(-1, requestConfig.getConnectTimeout());
}
 
Example #15
Source File: ElasticDatastoreFactoryTest.java    From elasticgeo with GNU General Public License v3.0 6 votes vote down vote up
@Before
public void setUp() throws IOException {
    dataStoreFactory = Mockito.spy(new ElasticDataStoreFactory());
    clientBuilder = mock(RestClientBuilder.class);
    hostsCaptor = ArgumentCaptor.forClass(HttpHost[].class);
    Mockito.doReturn(clientBuilder).when(dataStoreFactory).createClientBuilder(hostsCaptor.capture());
    final RestClient restClient = mock(RestClient.class);
    when(clientBuilder.build()).thenReturn(restClient);
    final DataStore dataStore = mock(DataStore.class);
    Mockito.doReturn(dataStore).when(dataStoreFactory).createDataStore(any(RestClient.class), any(), anyMap());
    configCallbackCaptor = ArgumentCaptor.forClass(RestClientBuilder.HttpClientConfigCallback.class);
    when(clientBuilder.setHttpClientConfigCallback(configCallbackCaptor.capture())).thenReturn(clientBuilder);
    httpClientBuilder = mock(HttpAsyncClientBuilder.class);
    credentialsProviderCaptor = ArgumentCaptor.forClass(CredentialsProvider.class);
    when(httpClientBuilder.setDefaultCredentialsProvider(credentialsProviderCaptor.capture())).thenReturn(httpClientBuilder);
    threadFactoryCaptor = ArgumentCaptor.forClass(ThreadFactory.class);
    when(httpClientBuilder.setThreadFactory(threadFactoryCaptor.capture())).thenReturn(httpClientBuilder);
    requestConfigCallbackCaptor = ArgumentCaptor.forClass(RestClientBuilder.RequestConfigCallback.class);
    when(clientBuilder.setRequestConfigCallback(requestConfigCallbackCaptor.capture())).thenReturn(clientBuilder);
    requestConfigBuilder = mock(RequestConfig.Builder.class);
    when(requestConfigBuilder.setAuthenticationEnabled(true)).thenReturn(requestConfigBuilder);

    params = getParams("localhost", 9200, "admin", "proxy");
    ElasticDataStoreFactory.httpThreads.set(1);
}
 
Example #16
Source File: HttpComponentsAsyncClientHttpRequestFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void defaultSettingsOfHttpAsyncClientLostOnExecutorCustomization() throws Exception {
	CloseableHttpAsyncClient client = HttpAsyncClientBuilder.create()
			.setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(1234).build())
			.build();
	HttpComponentsAsyncClientHttpRequestFactory factory = new HttpComponentsAsyncClientHttpRequestFactory(client);

	URI uri = new URI(baseUrl + "/status/ok");
	HttpComponentsAsyncClientHttpRequest request = (HttpComponentsAsyncClientHttpRequest)
			factory.createAsyncRequest(uri, HttpMethod.GET);

	assertNull("No custom config should be set with a custom HttpClient",
			request.getHttpContext().getAttribute(HttpClientContext.REQUEST_CONFIG));

	factory.setConnectionRequestTimeout(4567);
	HttpComponentsAsyncClientHttpRequest request2 = (HttpComponentsAsyncClientHttpRequest)
			factory.createAsyncRequest(uri, HttpMethod.GET);
	Object requestConfigAttribute = request2.getHttpContext().getAttribute(HttpClientContext.REQUEST_CONFIG);
	assertNotNull(requestConfigAttribute);
	RequestConfig requestConfig = (RequestConfig) requestConfigAttribute;

	assertEquals(4567, requestConfig.getConnectionRequestTimeout());
	// No way to access the request config of the HTTP client so no way to "merge" our customizations
	assertEquals(-1, requestConfig.getConnectTimeout());
}
 
Example #17
Source File: ElasticsearchConnection.java    From components with Apache License 2.0 6 votes vote down vote up
public static RestClient createClient(ElasticsearchDatastoreProperties datastore) throws MalformedURLException {
    String urlStr = datastore.nodes.getValue();
    String[] urls = urlStr.split(",");
    HttpHost[] hosts = new HttpHost[urls.length];
    int i = 0;
    for (String address : urls) {
        URL url = new URL("http://" + address);
        hosts[i] = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
        i++;
    }
    RestClientBuilder restClientBuilder = RestClient.builder(hosts);
    if (datastore.auth.useAuth.getValue()) {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(datastore.auth.userId.getValue(), datastore.auth.password.getValue()));
        restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {

            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
                return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }
        });
    }
    return restClientBuilder.build();
}
 
Example #18
Source File: ApacheHttpAsyncClient.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
public ApacheHttpAsyncClient(HttpAsyncClientBuilder builder, Config config, SharedResourcesBroker<GobblinScopeTypes> broker) {
  super (broker, HttpUtils.createApacheHttpClientLimiterKey(config));
  config = config.withFallback(FALLBACK);

  RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT)
      .setSocketTimeout(config.getInt(REQUEST_TIME_OUT_MS_KEY))
      .setConnectTimeout(config.getInt(CONNECTION_TIME_OUT_MS_KEY))
      .setConnectionRequestTimeout(config.getInt(CONNECTION_TIME_OUT_MS_KEY))
      .build();

  try {
    builder.disableCookieManagement().useSystemProperties().setDefaultRequestConfig(requestConfig);
    builder.setConnectionManager(getNHttpConnManager(config));
    client = builder.build();
    client.start();
  } catch (IOException e) {
    throw new RuntimeException("ApacheHttpAsyncClient cannot be initialized");
  }
}
 
Example #19
Source File: TestUtils.java    From salt-netapi-client with MIT License 5 votes vote down vote up
public static CloseableHttpAsyncClient defaultClient() {
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectionRequestTimeout(0)
            .setConnectTimeout(0)
            .setSocketTimeout(0)
            .setCookieSpec(CookieSpecs.STANDARD)
            .build();
    HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClients.custom();
    httpClientBuilder.setDefaultRequestConfig(requestConfig);

    CloseableHttpAsyncClient asyncHttpClient = httpClientBuilder.build();
    asyncHttpClient.start();
    return asyncHttpClient;
}
 
Example #20
Source File: BalancerConfiguration.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
protected CloseableHttpAsyncClient configuredHttpAsyncClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
    LOG.info("HttpAsyncClient settings: maxConnections: {}, socketTimeout: {}, connectTimeout: {}",
            maxConnections, socketTimeout, connectTimeout);
    return httpAsyncClientBuilder.setMaxConnPerRoute(maxConnections)
            .setMaxConnTotal(maxConnections)
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setSocketTimeout(socketTimeout)
                    .setConnectTimeout(connectTimeout)
                    .build())
            .disableCookieManagement()
            .build();
}
 
Example #21
Source File: SiteToSiteRestApiClient.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private void setupAsyncClient() {
    final HttpAsyncClientBuilder clientBuilder = HttpAsyncClients.custom();

    if (sslContext != null) {
        clientBuilder.setSSLContext(sslContext);
        clientBuilder.addInterceptorFirst(new HttpsResponseInterceptor());
    }

    httpAsyncClient = clientBuilder.setDefaultCredentialsProvider(getCredentialsProvider()).build();
    httpAsyncClient.start();
}
 
Example #22
Source File: HttpFactory.java    From aliyun-tablestore-java-sdk with Apache License 2.0 5 votes vote down vote up
public static CloseableHttpAsyncClient createHttpAsyncClient(
        ClientConfiguration config, PoolingNHttpClientConnectionManager cm) {
    HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClients.custom();
    httpClientBuilder.setConnectionManager(cm);
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(config.getConnectionTimeoutInMillisecond())
            .setSocketTimeout(config.getSocketTimeoutInMillisecond()).build();
    httpClientBuilder.setDefaultRequestConfig(requestConfig);
    httpClientBuilder.setUserAgent(Constants.USER_AGENT);
    httpClientBuilder.disableCookieManagement();

    String proxyHost = config.getProxyHost();
    int proxyPort = config.getProxyPort();
    if (proxyHost != null) {
        if (proxyPort <= 0) {
            throw new ClientException("The proxy port is invalid. Please check your configuration.");
        }
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        httpClientBuilder.setProxy(proxy);
        String proxyUsername = config.getProxyUsername();
        String proxyPassword = config.getProxyPassword();
        if (proxyUsername != null && proxyPassword != null) {
            String proxyDomain = config.getProxyDomain();
            String proxyWorkstation = config.getProxyWorkstation();
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(
                new AuthScope(proxyHost, proxyPort),
                new NTCredentials(
                    proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
            httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
        }
    }

    return httpClientBuilder.build();
}
 
Example #23
Source File: ApacheHttpRequester.java    From algoliasearch-client-java-2 with MIT License 5 votes vote down vote up
public ApacheHttpRequester(@Nonnull ConfigBase config) {
  this(
      config,
      config.getUseSystemProxy()
          ? HttpAsyncClientBuilder.create().useSystemProperties()
          : HttpAsyncClientBuilder.create().setMaxConnPerRoute(100));
}
 
Example #24
Source File: ClientProvider.java    From james-project with Apache License 2.0 5 votes vote down vote up
private void configureAuthentication(HttpAsyncClientBuilder builder) {
    configuration.getCredential()
        .ifPresent(credential -> {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(credential.getUsername(), String.valueOf(credential.getPassword())));
            builder.setDefaultCredentialsProvider(credentialsProvider);
        });
}
 
Example #25
Source File: ApacheHttpRequester.java    From algoliasearch-client-java-2 with MIT License 5 votes vote down vote up
public ApacheHttpRequester(@Nonnull ConfigBase config, @Nonnull HttpAsyncClientBuilder builder) {
  this.config = config;

  this.requestConfig =
      RequestConfig.custom()
          .setConnectTimeout(config.getConnectTimeOut())
          .setContentCompressionEnabled(true)
          .build();

  this.asyncHttpClient = builder.build();

  this.asyncHttpClient.start();
}
 
Example #26
Source File: SaltClientTest.java    From salt-netapi-client with MIT License 5 votes vote down vote up
@Test
public void testRunRequestWithSocketTimeout() {
    exception.expect(CompletionException.class);
    exception.expectCause(instanceOf(SocketTimeoutException.class));

    RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(1000)
            .setCookieSpec(CookieSpecs.STANDARD)
            .build();
    HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClients.custom();
    httpClientBuilder.setDefaultRequestConfig(requestConfig);

    CloseableHttpAsyncClient asyncHttpClient = httpClientBuilder.build();
    asyncHttpClient.start();

    // create a local SaltClient with a fast timeout configuration
    // to do not lock tests more than 2s
    URI uri = URI.create("http://localhost:" + Integer.toString(MOCK_HTTP_PORT));
    SaltClient clientWithFastTimeout = new SaltClient(uri, new HttpAsyncClientImpl(asyncHttpClient));


    stubFor(any(urlMatching(".*"))
            .willReturn(aResponse()
            .withFixedDelay(2000)));

    clientWithFastTimeout.login("user", "pass", AUTO).toCompletableFuture().join();
}
 
Example #27
Source File: ClientProvider.java    From james-project with Apache License 2.0 5 votes vote down vote up
private void configureSSLOptions(HttpAsyncClientBuilder builder) {
    try {
        builder
            .setSSLContext(sslContext())
            .setSSLHostnameVerifier(hostnameVerifier());
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException | CertificateException | IOException e) {
        throw new RuntimeException("Cannot set SSL options to the builder", e);
    }
}
 
Example #28
Source File: ElasticsearchHTTP.java    From hangout with MIT License 5 votes vote down vote up
private void initESClient() throws NumberFormatException,
        UnknownHostException {

    List<HttpHost> httpHostList = hosts.stream().map(hostString -> {
        return HttpHost.create(hostString);
    }).collect(toList());
    List<HttpHost> clusterHosts = unmodifiableList(httpHostList);

    if (config.containsKey("user") && config.containsKey("password")) {
        String user = config.get("user").toString();
        String password = config.get("password").toString();
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(user, password));

        restClient = RestClient.builder(clusterHosts.toArray(new HttpHost[clusterHosts.size()]))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    }
                }).build();
    } else {
        restClient = RestClient.builder(clusterHosts.toArray(new HttpHost[clusterHosts.size()]))
                .build();
    }
    if (this.isSniff) {
        sniffer = Sniffer.builder(restClient).build();
    }

}
 
Example #29
Source File: HttpClientUtils.java    From salt-netapi-client with MIT License 5 votes vote down vote up
/**
 * Creates a simple default http client
 * @return HttpAsyncClient
 */
public static CloseableHttpAsyncClient defaultClient() {
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectionRequestTimeout(0)
            .setConnectTimeout(10000)
            .setSocketTimeout(20000)
            .setCookieSpec(CookieSpecs.STANDARD)
            .build();
    HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClients.custom();
    httpClientBuilder.setDefaultRequestConfig(requestConfig);

    CloseableHttpAsyncClient asyncHttpClient = httpClientBuilder.build();
    asyncHttpClient.start();
    return asyncHttpClient;
}
 
Example #30
Source File: ClientProvider.java    From james-project with Apache License 2.0 5 votes vote down vote up
private void configureHostScheme(HttpAsyncClientBuilder builder) {
    HostScheme scheme = configuration.getHostScheme();

    switch (scheme) {
        case HTTP:
            return;
        case HTTPS:
            configureSSLOptions(builder);
            return;
        default:
            throw new NotImplementedException(
                String.format("unrecognized hostScheme '%s'", scheme.name()));
    }
}