Java Code Examples for org.apache.http.impl.nio.client.HttpAsyncClientBuilder#setDefaultRequestConfig()

The following examples show how to use org.apache.http.impl.nio.client.HttpAsyncClientBuilder#setDefaultRequestConfig() . 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: 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 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: AsyncHttpClientGenerator.java    From cetty with Apache License 2.0 5 votes vote down vote up
@Override
protected CloseableHttpAsyncClient build(Payload payload) {
    HttpAsyncClientBuilder asyncClientBuilder = HttpAsyncClients.custom();

    if (StringUtils.isNotBlank(payload.getUserAgent())) {
        asyncClientBuilder.setUserAgent(payload.getUserAgent());
    } else {
        asyncClientBuilder.setUserAgent("");
    }

    asyncClientBuilder.setRedirectStrategy(new CustomRedirectStrategy());

    asyncClientBuilder.setConnectionManagerShared(true);

    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(payload.getConnectTimeout())
            .setSocketTimeout(payload.getSocketTimeout()).build();

    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE)
            .setCharset(Consts.UTF_8).build();

    poolingNHttpClientConnectionManager.setDefaultConnectionConfig(connectionConfig);
    asyncClientBuilder.setConnectionManager(poolingNHttpClientConnectionManager);
    asyncClientBuilder.setDefaultRequestConfig(requestConfig);
    if (payload.getProxy() != null) {
        Proxy proxy = payload.getProxy();
        HttpHost httpHost = new HttpHost(proxy.getHost(), proxy.getPort(), proxy.getScheme());
        asyncClientBuilder.setProxy(httpHost);
    }
    reduceCookie(asyncClientBuilder,payload);
    return asyncClientBuilder.build();
}
 
Example 4
Source File: AsyncInternalClient.java    From fc-java-sdk with MIT License 5 votes vote down vote up
private CloseableHttpAsyncClient createHttpAsyncClient(Config config, PoolingNHttpClientConnectionManager cm){
    HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClients.custom();
    httpClientBuilder.setConnectionManager(cm);
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(config.getConnectTimeoutMillis())
            .setConnectionRequestTimeout(config.getConnectTimeoutMillis())
            .setSocketTimeout(config.getReadTimeoutMillis())
            .build();
    httpClientBuilder.setDefaultRequestConfig(requestConfig);
    httpClientBuilder.setUserAgent(config.getUserAgent());
    httpClientBuilder.disableCookieManagement();

    return httpClientBuilder.build();
}
 
Example 5
Source File: PoolingHttpAsyncClientFactory.java    From caravan with Apache License 2.0 5 votes vote down vote up
public static CloseableHttpAsyncClient create(RequestConfig config, NHttpClientConnectionManager connectionManager) {
    HttpAsyncClientBuilder builder = HttpAsyncClientBuilder.create();
    builder.useSystemProperties().setRedirectStrategy(AlwaysRedirectStrategy.DEFAULT).addInterceptorLast(new RequestContent(true));
    if (config != null)
        builder.setDefaultRequestConfig(config);
    if (connectionManager != null)
        builder.setConnectionManager(connectionManager);
    return builder.build();
}
 
Example 6
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 7
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 8
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 9
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 10
Source File: HttpClient.java    From deprecated-security-advanced-modules with Apache License 2.0 4 votes vote down vote up
private final HttpAsyncClientBuilder asyncClientBuilder(HttpAsyncClientBuilder httpClientBuilder)
        throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {

    // basic auth
    // pki auth

    if (ssl) {

        final SSLContextBuilder sslContextBuilder = SSLContexts.custom();

        if (log.isTraceEnabled()) {
            log.trace("Configure HTTP client with SSL");
        }

        if (trustStore != null) {
            sslContextBuilder.loadTrustMaterial(trustStore, null);
        }

        if (keystore != null) {
            sslContextBuilder.loadKeyMaterial(keystore, keyPassword, new PrivateKeyStrategy() {

                @Override
                public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) {
                    if(aliases == null || aliases.isEmpty()) {
                        return keystoreAlias;
                    }

                    if(keystoreAlias == null || keystoreAlias.isEmpty()) {
                        return aliases.keySet().iterator().next();
                    }

                    return keystoreAlias;                    }
            });
        }

        final HostnameVerifier hnv = verifyHostnames?new DefaultHostnameVerifier():NoopHostnameVerifier.INSTANCE;

        final SSLContext sslContext = sslContextBuilder.build();
        httpClientBuilder.setSSLStrategy(new SSLIOSessionStrategy(
                sslContext,
                supportedProtocols,
                supportedCipherSuites,
                hnv
                ));
    }

    if (basicCredentials != null) {
        httpClientBuilder.setDefaultHeaders(Lists.newArrayList(new BasicHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicCredentials)));
    }

    // TODO: set a timeout until we have a proper way to deal with back pressure
    int timeout = 5;

    RequestConfig config = RequestConfig.custom()
      .setConnectTimeout(timeout * 1000)
      .setConnectionRequestTimeout(timeout * 1000)
      .setSocketTimeout(timeout * 1000).build();

    httpClientBuilder.setDefaultRequestConfig(config);

    return httpClientBuilder;

}
 
Example 11
Source File: HttpFactory.java    From mq-http-java-sdk with MIT License 4 votes vote down vote up
public static CloseableHttpAsyncClient createHttpAsyncClient(
        PoolingNHttpClientConnectionManager connManager,
        ClientConfiguration config) {
    HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClients.custom()
            .setConnectionManager(connManager);

    // Set proxy if set.
    String proxyHost = config.getProxyHost();
    int proxyPort = config.getProxyPort();

    if (proxyHost != null && proxyPort > 0) {
        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 credentialsProvider = new BasicCredentialsProvider();

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

            httpClientBuilder
                    .setDefaultCredentialsProvider(credentialsProvider);

        }
    }

    RequestConfig defaultRequestConfig = RequestConfig
            .custom()
            .setCookieSpec(CookieSpecs.BEST_MATCH)
            .setExpectContinueEnabled(true)
            .setStaleConnectionCheckEnabled(true)
            .setTargetPreferredAuthSchemes(
                    Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
            .setConnectTimeout(config.getConnectionTimeout())
            .setSocketTimeout(config.getSocketTimeout())
            .setExpectContinueEnabled(config.isExceptContinue()).build();

    httpClientBuilder.setDefaultRequestConfig(defaultRequestConfig);
    httpClientBuilder
            .setMaxConnPerRoute(config.getMaxConnectionsPerRoute());
    httpClientBuilder.setMaxConnTotal(config.getMaxConnections());
    httpClientBuilder.setUserAgent(VersionInfoUtils.getDefaultUserAgent());
    CloseableHttpAsyncClient httpclient = httpClientBuilder.build();

    return httpclient;
}
 
Example 12
Source File: HttpFactory.java    From mq-http-java-sdk with MIT License 4 votes vote down vote up
public static CloseableHttpAsyncClient createHttpAsyncClient(
        PoolingNHttpClientConnectionManager connManager,
        ClientConfiguration config) {
    HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClients.custom()
            .setConnectionManager(connManager);

    // Set proxy if set.
    String proxyHost = config.getProxyHost();
    int proxyPort = config.getProxyPort();

    if (proxyHost != null && proxyPort > 0) {
        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 credentialsProvider = new BasicCredentialsProvider();

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

            httpClientBuilder
                    .setDefaultCredentialsProvider(credentialsProvider);

        }
    }

    RequestConfig defaultRequestConfig = RequestConfig
            .custom()
            .setCookieSpec(CookieSpecs.BEST_MATCH)
            .setExpectContinueEnabled(true)
            .setStaleConnectionCheckEnabled(true)
            .setTargetPreferredAuthSchemes(
                    Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
            .setConnectTimeout(config.getConnectionTimeout())
            .setSocketTimeout(config.getSocketTimeout())
            .setExpectContinueEnabled(config.isExceptContinue()).build();

    httpClientBuilder.setDefaultRequestConfig(defaultRequestConfig);
    httpClientBuilder
            .setMaxConnPerRoute(config.getMaxConnectionsPerRoute());
    httpClientBuilder.setMaxConnTotal(config.getMaxConnections());
    httpClientBuilder.setUserAgent(VersionInfoUtils.getDefaultUserAgent());
    CloseableHttpAsyncClient httpclient = httpClientBuilder.build();

    return httpclient;
}
 
Example 13
Source File: HttpClientFactory.java    From aliyun-tsdb-java-sdk with Apache License 2.0 4 votes vote down vote up
private static CloseableHttpAsyncClient createPoolingHttpClient(
        Config config, PoolingNHttpClientConnectionManager cm) throws HttpClientInitException {
    int httpConnectionPool = config.getHttpConnectionPool();
    int httpConnectionLiveTime = config.getHttpConnectionLiveTime();
    int httpKeepaliveTime = config.getHttpKeepaliveTime();

    RequestConfig requestConfig = initRequestConfig(config);

    if (httpConnectionPool > 0) {
        cm.setMaxTotal(httpConnectionPool);
        cm.setDefaultMaxPerRoute(httpConnectionPool);
        cm.closeExpiredConnections();
    }

    HttpAsyncClientBuilder httpAsyncClientBuilder = HttpAsyncClients.custom();

    // 设置连接管理器
    httpAsyncClientBuilder.setConnectionManager(cm);

    // 设置RequestConfig
    if (requestConfig != null) {
        httpAsyncClientBuilder.setDefaultRequestConfig(requestConfig);
    }

    // 设置Keepalive
    if (httpKeepaliveTime > 0) {
        HiTSDBConnectionKeepAliveStrategy hiTSDBConnectionKeepAliveStrategy = new HiTSDBConnectionKeepAliveStrategy(httpConnectionLiveTime);
        httpAsyncClientBuilder.setKeepAliveStrategy(hiTSDBConnectionKeepAliveStrategy);
    } else if (httpKeepaliveTime == 0) {
        HiTSDBConnectionReuseStrategy hiTSDBConnectionReuseStrategy = new HiTSDBConnectionReuseStrategy();
        httpAsyncClientBuilder.setConnectionReuseStrategy(hiTSDBConnectionReuseStrategy);
    }

    // 设置连接自动关闭
    if (httpConnectionLiveTime > 0) {
        TSDBHttpAsyncCallbackExecutor httpAsyncCallbackExecutor = new TSDBHttpAsyncCallbackExecutor(httpConnectionLiveTime);
        httpAsyncClientBuilder.setEventHandler(httpAsyncCallbackExecutor);
    }

    CloseableHttpAsyncClient client = httpAsyncClientBuilder.build();
    return client;
}