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

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

Introduction

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

Prototype

public final HttpClientBuilder setDefaultSocketConfig(final SocketConfig config) 

Source Link

Document

Assigns default SocketConfig .

Usage

From source file:ninja.siden.internal.Testing.java

static CloseableHttpClient client() {
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(200).build());
    builder.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
    return builder.build();
}

From source file:com.hp.autonomy.hod.client.HodServiceConfigFactory.java

public static HodServiceConfig<EntityType.Application, TokenType.Simple> getHodServiceConfig(
        final TokenProxyService<EntityType.Application, TokenType.Simple> tokenProxyService,
        final Endpoint endpoint) {
    final HttpClientBuilder builder = HttpClientBuilder.create();
    builder.disableCookieManagement();//from www .  j  a v a 2  s . c  o m
    builder.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60000).build());

    final String proxyHost = System.getProperty("hp.hod.https.proxyHost");

    if (proxyHost != null) {
        final Integer proxyPort = Integer.valueOf(System.getProperty("hp.hod.https.proxyPort", "8080"));
        builder.setProxy(new HttpHost(proxyHost, proxyPort));
    }

    final HodServiceConfig.Builder<EntityType.Application, TokenType.Simple> configBuilder = new HodServiceConfig.Builder<EntityType.Application, TokenType.Simple>(
            endpoint.getUrl()).setHttpClient(builder.build());

    if (tokenProxyService != null) {
        configBuilder.setTokenProxyService(tokenProxyService);
    }

    return configBuilder.build();
}

From source file:com.thoughtworks.go.agent.common.ssl.GoAgentServerHttpClientBuilder.java

public CloseableHttpClient build() throws Exception {
    HttpClientBuilder builder = HttpClients.custom();
    builder.useSystemProperties();//w  w  w. ja  v  a  2  s.c om
    builder.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).setSoKeepAlive(true).build())
            .setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE);

    HostnameVerifier hostnameVerifier = sslVerificationMode.verifier();
    TrustStrategy trustStrategy = sslVerificationMode.trustStrategy();
    KeyStore trustStore = agentTruststore();

    SSLContextBuilder sslContextBuilder = SSLContextBuilder.create().useProtocol(
            systemEnvironment.get(SystemEnvironment.GO_SSL_TRANSPORT_PROTOCOL_TO_BE_USED_BY_AGENT));

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

    sslContextBuilder.loadKeyMaterial(agentKeystore(), keystorePassword().toCharArray());

    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
            sslContextBuilder.build(), hostnameVerifier);
    builder.setSSLSocketFactory(sslConnectionSocketFactory);
    return builder.build();
}

From source file:com.adobe.acs.commons.mcp.impl.processes.asset.UrlAssetImport.java

@Override
public void init() throws RepositoryException {
    super.init();
    if (httpFactory != null) {
        HttpClientBuilder clientBuilder = httpFactory.newBuilder();
        clientBuilder.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(timeout).build());
        clientBuilder.setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(timeout).build());
        httpClient = clientBuilder.build();
    }//  w w  w . j a v a2 s. c o m
}

From source file:es.auth.plugin.AbstractUnitTest.java

protected final JestHttpClient getJestClient(final String serverUri, final String username,
        final String password) throws Exception {
    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    final HttpClientConfig clientConfig1 = new HttpClientConfig.Builder(serverUri).multiThreaded(true).build();
    // Construct a new Jest client according to configuration via factory
    final JestClientFactory factory1 = new JestClientFactory();
    factory1.setHttpClientConfig(clientConfig1);
    final JestHttpClient c = factory1.getObject();
    final HttpClientBuilder hcb = HttpClients.custom();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY),
            new UsernamePasswordCredentials(username, password));
    hcb.setDefaultCredentialsProvider(credsProvider);
    hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build());
    final CloseableHttpClient httpClient = hcb.build();
    c.setHttpClient(httpClient);/*from w w  w. j ava 2  s  .  c om*/
    return c;
}

From source file:org.apache.sling.discovery.base.connectors.ping.TopologyConnectorClient.java

private CloseableHttpClient createHttpClient() {
    final HttpClientBuilder builder = HttpClientBuilder.create();
    // setting the SoTimeout (which is configured in seconds)
    builder.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(1000 * config.getSoTimeout()).build());
    builder.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));

    return builder.build();
}

From source file:com.nominanuda.web.http.HttpCoreHelper.java

public HttpClient createClient(int maxConnPerRoute, long connTimeoutMillis, long soTimeoutMillis,
        @Nullable String proxyHostAnPort) {
    Registry<ConnectionSocketFactory> defaultRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", SSLConnectionSocketFactory.getSocketFactory()).build();
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(defaultRegistry);
    connMgr.setDefaultMaxPerRoute(maxConnPerRoute);
    SocketConfig sCfg = SocketConfig.custom().setSoTimeout((int) soTimeoutMillis)
            .setSoTimeout((int) connTimeoutMillis).build();
    connMgr.setDefaultSocketConfig(sCfg);
    HttpClientBuilder hcb = HttpClientBuilder.create();
    hcb.setDefaultSocketConfig(sCfg).setConnectionManager(connMgr);
    if (proxyHostAnPort == null) {
    } else if ("jvm".equalsIgnoreCase(proxyHostAnPort)) {
        SystemDefaultRoutePlanner rp = new SystemDefaultRoutePlanner(ProxySelector.getDefault());
        hcb.setRoutePlanner(rp);/*from   w ww.  ja v  a2  s  .  co  m*/
    } else {
        String[] hostAndPort = proxyHostAnPort.split(":");
        Check.illegalargument.assertTrue(hostAndPort.length < 3, "wrong hostAndPort:" + proxyHostAnPort);
        String host = hostAndPort[0];
        int port = 80;
        if (hostAndPort.length > 1) {
            port = Integer.valueOf(hostAndPort[1]);
        }
        HttpHost proxy = new HttpHost(host, port);
        hcb.setProxy(proxy);
    }
    HttpClient httpClient = hcb.build();
    return httpClient;
}

From source file:org.sonatype.nexus.internal.httpclient.HttpClientManagerImpl.java

@Override
@Guarded(by = STARTED)//  ww  w.j  av  a2s .  c  o  m
public HttpClientBuilder prepare(@Nullable final Customizer customizer) {
    final HttpClientPlan plan = httpClientPlan();

    // attach connection manager early, so customizer has chance to replace it if needed
    plan.getClient().setConnectionManager(sharedConnectionManager);

    // apply defaults
    defaultsCustomizer.customize(plan);

    // apply globals
    new ConfigurationCustomizer(getConfigurationInternal()).customize(plan);

    // apply instance customization
    if (customizer != null) {
        customizer.customize(plan);
    }

    // apply plan to builder
    HttpClientBuilder builder = plan.getClient();
    // User agent must be set here to apply to all apache http requests, including over proxies
    String userAgent = plan.getUserAgent();
    if (userAgent != null) {
        setUserAgent(builder, userAgent);
    }
    builder.setDefaultConnectionConfig(plan.getConnection().build());
    builder.setDefaultSocketConfig(plan.getSocket().build());
    builder.setDefaultRequestConfig(plan.getRequest().build());
    builder.setDefaultCredentialsProvider(plan.getCredentials());

    builder.addInterceptorFirst((HttpRequest request, HttpContext context) -> {
        // add custom http-context attributes
        for (Entry<String, Object> entry : plan.getAttributes().entrySet()) {
            // only set context attribute if not already set, to allow per request overrides
            if (context.getAttribute(entry.getKey()) == null) {
                context.setAttribute(entry.getKey(), entry.getValue());
            }
        }

        // add custom http-request headers
        for (Entry<String, String> entry : plan.getHeaders().entrySet()) {
            request.addHeader(entry.getKey(), entry.getValue());
        }
    });
    builder.addInterceptorLast((HttpRequest httpRequest, HttpContext httpContext) -> {
        if (outboundLog.isDebugEnabled()) {
            httpContext.setAttribute(CTX_REQ_STOPWATCH, Stopwatch.createStarted());
            httpContext.setAttribute(CTX_REQ_URI, getRequestURI(httpContext));
            outboundLog.debug("{} > {}", httpContext.getAttribute(CTX_REQ_URI), httpRequest.getRequestLine());
        }
    });
    builder.addInterceptorLast((HttpResponse httpResponse, HttpContext httpContext) -> {
        Stopwatch stopwatch = (Stopwatch) httpContext.getAttribute(CTX_REQ_STOPWATCH);
        if (stopwatch != null) {
            outboundLog.debug("{} < {} @ {}", httpContext.getAttribute(CTX_REQ_URI),
                    httpResponse.getStatusLine(), stopwatch);
        }
    });

    return builder;
}

From source file:com.opentable.jaxrs.JaxRsClientFactoryImpl.java

private void configureHttpEngine(String clientName, ResteasyClientBuilder clientBuilder,
        JaxRsClientConfig config) {/*w  ww.ja v a2s . co m*/
    final HttpClientBuilder builder = HttpClientBuilder.create();
    if (config.isEtcdHacksEnabled()) {
        builder.setRedirectStrategy(new ExtraLaxRedirectStrategy())
                .addInterceptorFirst(new SwallowHeaderInterceptor(HttpHeaders.CONTENT_LENGTH));
    }
    final MonitoredPoolingHttpClientConnectionManager connectionManager = new MonitoredPoolingHttpClientConnectionManager(
            clientName);

    connectionManager.setCheckoutWarnTime(Duration.ofMillis(config.connectionPoolWarnTime().getMillis()));
    connectionManager.setMaxTotal(config.connectionPoolSize());
    connectionManager.setDefaultMaxPerRoute(config.httpClientDefaultMaxPerRoute());

    final HttpClient client = builder
            .setDefaultSocketConfig(
                    SocketConfig.custom().setSoTimeout((int) config.socketTimeout().getMillis()).build())
            .setDefaultRequestConfig(customRequestConfig(config, RequestConfig.custom()))
            .setConnectionManager(connectionManager).build();
    final ApacheHttpClient4Engine engine = new HackedApacheHttpClient4Engine(config, client);
    clientBuilder.httpEngine(engine);
}

From source file:com.gargoylesoftware.htmlunit.HttpWebConnection.java

private void configureTimeout(final HttpClientBuilder builder, final int timeout) {
    final RequestConfig.Builder requestBuilder = createRequestConfigBuilder(timeout);
    builder.setDefaultRequestConfig(requestBuilder.build());

    builder.setDefaultSocketConfig(createSocketConfigBuilder(timeout).build());

    httpContext_.removeAttribute(HttpClientContext.REQUEST_CONFIG);
    usedOptions_.setTimeout(timeout);//from w w w .  j ava2 s  . co m
}