use of org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy in project dropwizard by dropwizard.
the class HttpClientBuilderTest method usesDefaultForNonPersistentConnections.
@Test
void usesDefaultForNonPersistentConnections() throws Exception {
configuration.setKeepAlive(Duration.seconds(1));
assertThat(builder.using(configuration).createClient(apacheBuilder, connectionManager, "test")).isNotNull();
final Field field = getInaccessibleField(httpClientBuilderClass, "keepAliveStrategy");
final DefaultConnectionKeepAliveStrategy strategy = (DefaultConnectionKeepAliveStrategy) field.get(apacheBuilder);
final HttpContext context = mock(HttpContext.class);
final HttpResponse response = mock(HttpResponse.class);
final HeaderIterator iterator = new BasicListHeaderIterator(Collections.singletonList(new BasicHeader(HttpHeaders.CONNECTION, "timeout=50")), HttpHeaders.CONNECTION);
when(response.headerIterator(HTTP.CONN_KEEP_ALIVE)).thenReturn(iterator);
assertThat(strategy.getKeepAliveDuration(response, context)).isEqualTo(50_000);
}
use of org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy in project dropwizard by dropwizard.
the class HttpClientBuilder method createClient.
/**
* Map the parameters in {@link HttpClientConfiguration} to configuration on a
* {@link org.apache.http.impl.client.HttpClientBuilder} instance
*
* @param builder
* @param manager
* @param name
* @return the configured {@link CloseableHttpClient}
*/
protected ConfiguredCloseableHttpClient createClient(final org.apache.http.impl.client.HttpClientBuilder builder, final InstrumentedHttpClientConnectionManager manager, final String name) {
final String cookiePolicy = configuration.isCookiesEnabled() ? CookieSpecs.DEFAULT : CookieSpecs.IGNORE_COOKIES;
final Integer timeout = (int) configuration.getTimeout().toMilliseconds();
final Integer connectionTimeout = (int) configuration.getConnectionTimeout().toMilliseconds();
final Integer connectionRequestTimeout = (int) configuration.getConnectionRequestTimeout().toMilliseconds();
final boolean normalizeUri = configuration.isNormalizeUriEnabled();
final long keepAlive = configuration.getKeepAlive().toMilliseconds();
final ConnectionReuseStrategy reuseStrategy = keepAlive == 0 ? new NoConnectionReuseStrategy() : new DefaultConnectionReuseStrategy();
final HttpRequestRetryHandler retryHandler = configuration.getRetries() == 0 ? NO_RETRIES : (httpRequestRetryHandler == null ? new DefaultHttpRequestRetryHandler(configuration.getRetries(), false) : httpRequestRetryHandler);
final RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(cookiePolicy).setSocketTimeout(timeout).setConnectTimeout(connectionTimeout).setConnectionRequestTimeout(connectionRequestTimeout).setNormalizeUri(normalizeUri).build();
final SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(timeout).build();
builder.setRequestExecutor(createRequestExecutor(name)).setConnectionManager(manager).setDefaultRequestConfig(requestConfig).setDefaultSocketConfig(socketConfig).setConnectionReuseStrategy(reuseStrategy).setRetryHandler(retryHandler).setUserAgent(createUserAgent(name));
if (keepAlive != 0) {
// either keep alive based on response header Keep-Alive,
// or if the server can keep a persistent connection (-1), then override based on client's configuration
builder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy() {
@Override
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
final long duration = super.getKeepAliveDuration(response, context);
return (duration == -1) ? keepAlive : duration;
}
});
}
// create a tunnel through a proxy host if it's specified in the config
final ProxyConfiguration proxy = configuration.getProxyConfiguration();
if (proxy != null) {
final HttpHost httpHost = new HttpHost(proxy.getHost(), proxy.getPort(), proxy.getScheme());
builder.setRoutePlanner(new NonProxyListProxyRoutePlanner(httpHost, proxy.getNonProxyHosts()));
// if the proxy host requires authentication then add the host credentials to the credentials provider
final AuthConfiguration auth = proxy.getAuth();
if (auth != null) {
if (credentialsProvider == null) {
credentialsProvider = new BasicCredentialsProvider();
}
// set the AuthScope
AuthScope authScope = new AuthScope(httpHost, auth.getRealm(), auth.getAuthScheme());
// set the credentials type
Credentials credentials = configureCredentials(auth);
credentialsProvider.setCredentials(authScope, credentials);
}
}
if (credentialsProvider != null) {
builder.setDefaultCredentialsProvider(credentialsProvider);
}
if (routePlanner != null) {
builder.setRoutePlanner(routePlanner);
}
if (disableContentCompression) {
builder.disableContentCompression();
}
if (redirectStrategy != null) {
builder.setRedirectStrategy(redirectStrategy);
}
if (defaultHeaders != null) {
builder.setDefaultHeaders(defaultHeaders);
}
if (verifier != null) {
builder.setSSLHostnameVerifier(verifier);
}
if (httpProcessor != null) {
builder.setHttpProcessor(httpProcessor);
}
if (serviceUnavailableRetryStrategy != null) {
builder.setServiceUnavailableRetryStrategy(serviceUnavailableRetryStrategy);
}
customizeBuilder(builder);
return new ConfiguredCloseableHttpClient(builder.build(), requestConfig);
}
use of org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy in project dropwizard by dropwizard.
the class HttpClientBuilderTest method usesKeepAliveForPersistentConnections.
@Test
void usesKeepAliveForPersistentConnections() throws Exception {
configuration.setKeepAlive(Duration.seconds(1));
assertThat(builder.using(configuration).createClient(apacheBuilder, connectionManager, "test")).isNotNull();
final DefaultConnectionKeepAliveStrategy strategy = (DefaultConnectionKeepAliveStrategy) spyHttpClientBuilderField("keepAliveStrategy", apacheBuilder);
final HttpContext context = mock(HttpContext.class);
final HttpResponse response = mock(HttpResponse.class);
when(response.headerIterator(HTTP.CONN_KEEP_ALIVE)).thenReturn(mock(HeaderIterator.class));
assertThat(strategy.getKeepAliveDuration(response, context)).isEqualTo(1000);
}
use of org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy in project scout.rt by eclipse.
the class ApacheHttpTransportFactory method setConnectionKeepAliveAndRetrySettings.
/**
* @param builder
*/
protected void setConnectionKeepAliveAndRetrySettings(HttpClientBuilder builder) {
final boolean keepAliveProp = CONFIG.getPropertyValue(ApacheHttpTransportKeepAliveProperty.class);
builder.setConnectionReuseStrategy(new ConnectionReuseStrategy() {
@Override
public boolean keepAlive(HttpResponse response, HttpContext context) {
return keepAliveProp;
}
});
// Connections should not be kept open forever, there are numerous reasons a connection could get invalid. Also it does not make much sense to keep a connection open forever
builder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy() {
@Override
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
long headerKeepAliveDuration = super.getKeepAliveDuration(response, context);
return headerKeepAliveDuration < 0 ? 5000 : headerKeepAliveDuration;
}
});
final boolean retryPostProp = CONFIG.getPropertyValue(ApacheHttpTransportRetryPostProperty.class);
builder.setRetryHandler(new DefaultHttpRequestRetryHandler(1, true) {
@Override
protected boolean handleAsIdempotent(HttpRequest request) {
return retryPostProp || super.handleAsIdempotent(request);
}
});
}
Aggregations