Skip to content

Commit

Permalink
@nickbabcock: expand glob imports
Browse files Browse the repository at this point in the history
  • Loading branch information
patrox committed Oct 26, 2017
1 parent 8d91aa2 commit c7d6ecb
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 65 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
import io.dropwizard.lifecycle.Managed;
import io.dropwizard.setup.Environment;
import io.dropwizard.util.Duration;
import javax.net.ssl.HostnameVerifier;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.Header;
import org.apache.http.HttpHost;
Expand All @@ -22,7 +21,11 @@
import org.apache.http.auth.Credentials;
import org.apache.http.auth.NTCredentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.*;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.RedirectStrategy;
import org.apache.http.client.ServiceUnavailableRetryStrategy;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
Expand All @@ -43,6 +46,7 @@
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;

import javax.net.ssl.HostnameVerifier;
import java.util.List;

/**
Expand Down Expand Up @@ -156,7 +160,7 @@ public HttpClientBuilder using(Registry<ConnectionSocketFactory> registry) {
/**
* Use the given {@link HttpRoutePlanner} instance.
*
* @param routePlanner a {@link HttpRoutePlanner} instance
* @param routePlanner a {@link HttpRoutePlanner} instance
* @return {@code this}
*/
public HttpClientBuilder using(HttpRoutePlanner routePlanner) {
Expand All @@ -178,7 +182,7 @@ public HttpClientBuilder using(CredentialsProvider credentialsProvider) {
/**
* Use the given {@link HttpClientMetricNameStrategy} instance.
*
* @param metricNameStrategy a {@link HttpClientMetricNameStrategy} instance
* @param metricNameStrategy a {@link HttpClientMetricNameStrategy} instance
* @return {@code this}
*/
public HttpClientBuilder using(HttpClientMetricNameStrategy metricNameStrategy) {
Expand All @@ -189,7 +193,7 @@ public HttpClientBuilder using(HttpClientMetricNameStrategy metricNameStrategy)
/**
* Use the given {@link org.apache.http.client.RedirectStrategy} instance.
*
* @param redirectStrategy a {@link org.apache.http.client.RedirectStrategy} instance
* @param redirectStrategy a {@link org.apache.http.client.RedirectStrategy} instance
* @return {@code this}
*/
public HttpClientBuilder using(RedirectStrategy redirectStrategy) {
Expand Down Expand Up @@ -274,12 +278,12 @@ public void stop() throws Exception {
*/
ConfiguredCloseableHttpClient buildWithDefaultRequestConfiguration(String name) {
return createClient(org.apache.http.impl.client.HttpClientBuilder.create(),
createConnectionManager(createConfiguredRegistry(), name), name);
createConnectionManager(createConfiguredRegistry(), name), name);
}

/**
* Configures an Apache {@link org.apache.http.impl.client.HttpClientBuilder HttpClientBuilder}.
*
* <p>
* Intended for use by subclasses to inject HttpClientBuilder
* configuration. The default implementation is an identity
* function.
Expand All @@ -300,41 +304,41 @@ protected org.apache.http.impl.client.HttpClientBuilder customizeBuilder(
* @return the configured {@link CloseableHttpClient}
*/
protected ConfiguredCloseableHttpClient createClient(
final org.apache.http.impl.client.HttpClientBuilder builder,
final InstrumentedHttpClientConnectionManager manager,
final String name) {
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 long keepAlive = configuration.getKeepAlive().toMilliseconds();
final ConnectionReuseStrategy reuseStrategy = keepAlive == 0
? new NoConnectionReuseStrategy()
: new DefaultConnectionReuseStrategy();
? new NoConnectionReuseStrategy()
: new DefaultConnectionReuseStrategy();
final HttpRequestRetryHandler retryHandler = configuration.getRetries() == 0
? NO_RETRIES
: (httpRequestRetryHandler == null ? new DefaultHttpRequestRetryHandler(configuration.getRetries(),
false) : httpRequestRetryHandler);
? NO_RETRIES
: (httpRequestRetryHandler == null ? new DefaultHttpRequestRetryHandler(configuration.getRetries(),
false) : httpRequestRetryHandler);

final RequestConfig requestConfig
= RequestConfig.custom().setCookieSpec(cookiePolicy)
.setSocketTimeout(timeout)
.setConnectTimeout(connectionTimeout)
.setConnectionRequestTimeout(connectionRequestTimeout)
.build();
= RequestConfig.custom().setCookieSpec(cookiePolicy)
.setSocketTimeout(timeout)
.setConnectTimeout(connectionTimeout)
.setConnectionRequestTimeout(connectionRequestTimeout)
.build();
final SocketConfig socketConfig = SocketConfig.custom()
.setTcpNoDelay(true)
.setSoTimeout(timeout)
.build();
.setTcpNoDelay(true)
.setSoTimeout(timeout)
.build();

customizeBuilder(builder)
.setRequestExecutor(new InstrumentedHttpRequestExecutor(metricRegistry, metricNameStrategy, name))
.setConnectionManager(manager)
.setDefaultRequestConfig(requestConfig)
.setDefaultSocketConfig(socketConfig)
.setConnectionReuseStrategy(reuseStrategy)
.setRetryHandler(retryHandler)
.setUserAgent(createUserAgent(name));
.setRequestExecutor(new InstrumentedHttpRequestExecutor(metricRegistry, metricNameStrategy, 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,
Expand Down Expand Up @@ -431,13 +435,13 @@ protected InstrumentedHttpClientConnectionManager createConnectionManager(Regist
String name) {
final Duration ttl = configuration.getTimeToLive();
final InstrumentedHttpClientConnectionManager manager = new InstrumentedHttpClientConnectionManager(
metricRegistry,
registry,
null, null,
resolver,
ttl.getQuantity(),
ttl.getUnit(),
name);
metricRegistry,
registry,
null, null,
resolver,
ttl.getQuantity(),
ttl.getUnit(),
name);
return configureConnectionManager(manager);
}

Expand All @@ -461,15 +465,15 @@ Registry<ConnectionSocketFactory> createConfiguredRegistry() {
}

return RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslConnectionSocketFactory)
.build();
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslConnectionSocketFactory)
.build();
}


@VisibleForTesting
protected InstrumentedHttpClientConnectionManager configureConnectionManager(
InstrumentedHttpClientConnectionManager connectionManager) {
InstrumentedHttpClientConnectionManager connectionManager) {
connectionManager.setDefaultMaxPerRoute(configuration.getMaxConnectionsPerRoute());
connectionManager.setMaxTotal(configuration.getMaxConnections());
connectionManager.setValidateAfterInactivity((int) configuration.getValidateAfterInactivityPeriod().toMilliseconds());
Expand All @@ -478,6 +482,7 @@ protected InstrumentedHttpClientConnectionManager configureConnectionManager(

/**
* determine the Credentials implementation to use
*
* @param auth
* @return a {@code Credentials} instance, either {{@link UsernamePasswordCredentials} or {@link NTCredentials}}
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,11 @@
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.net.*;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
Expand All @@ -59,7 +63,11 @@

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class JerseyClientBuilderTest {
private final JerseyClientBuilder builder = new JerseyClientBuilder(new MetricRegistry());
Expand Down Expand Up @@ -90,7 +98,7 @@ public void throwsAnExceptionWithoutAnEnvironmentOrAThreadPoolAndObjectMapper()
failBecauseExceptionWasNotThrown(IllegalStateException.class);
} catch (IllegalStateException e) {
assertThat(e.getMessage())
.isEqualTo("Must have either an environment or both an executor service and an object mapper");
.isEqualTo("Must have either an environment or both an executor service and an object mapper");
}
}

Expand All @@ -101,7 +109,7 @@ public void throwsAnExceptionWithoutAnEnvironmentAndOnlyObjectMapper() throws Ex
failBecauseExceptionWasNotThrown(IllegalStateException.class);
} catch (IllegalStateException e) {
assertThat(e.getMessage())
.isEqualTo("Must have either an environment or both an executor service and an object mapper");
.isEqualTo("Must have either an environment or both an executor service and an object mapper");
}
}

Expand All @@ -112,15 +120,15 @@ public void throwsAnExceptionWithoutAnEnvironmentAndOnlyAThreadPool() throws Exc
failBecauseExceptionWasNotThrown(IllegalStateException.class);
} catch (IllegalStateException e) {
assertThat(e.getMessage())
.isEqualTo("Must have either an environment or both an executor service and an object mapper");
.isEqualTo("Must have either an environment or both an executor service and an object mapper");
}
}

@Test
public void includesJerseyProperties() throws Exception {
final Client client = builder.withProperty("poop", true)
.using(executorService, objectMapper)
.build("test");
.using(executorService, objectMapper)
.build("test");

assertThat(client.getConfiguration().getProperty("poop")).isEqualTo(Boolean.TRUE);
}
Expand All @@ -129,18 +137,17 @@ public void includesJerseyProperties() throws Exception {
public void includesJerseyProviderSingletons() throws Exception {
final FakeMessageBodyReader provider = new FakeMessageBodyReader();
final Client client = builder.withProvider(provider)
.using(executorService, objectMapper)
.build("test");
.using(executorService, objectMapper)
.build("test");

assertThat(client.getConfiguration().isRegistered(provider)).isTrue();
}

@Test
public void includesJerseyProviderClasses() throws Exception {
@SuppressWarnings("unused")
final Client client = builder.withProvider(FakeMessageBodyReader.class)
.using(executorService, objectMapper)
.build("test");
@SuppressWarnings("unused") final Client client = builder.withProvider(FakeMessageBodyReader.class)
.using(executorService, objectMapper)
.build("test");

assertThat(client.getConfiguration().isRegistered(FakeMessageBodyReader.class)).isTrue();
}
Expand Down Expand Up @@ -189,11 +196,11 @@ public void addBidirectionalGzipSupportIfEnabled() throws Exception {
configuration.setGzipEnabled(true);

final Client client = builder.using(configuration)
.using(executorService, objectMapper).build("test");
.using(executorService, objectMapper).build("test");
assertThat(Iterables.filter(client.getConfiguration().getInstances(), GZipDecoder.class)
.iterator().hasNext()).isTrue();
.iterator().hasNext()).isTrue();
assertThat(Iterables.filter(client.getConfiguration().getInstances(), ConfiguredGZipEncoder.class)
.iterator().hasNext()).isTrue();
.iterator().hasNext()).isTrue();
verify(apacheHttpClientBuilder, never()).disableContentCompression(true);
}

Expand All @@ -203,12 +210,12 @@ public void disablesGzipSupportIfDisabled() throws Exception {
configuration.setGzipEnabled(false);

final Client client = builder.using(configuration)
.using(executorService, objectMapper).build("test");
.using(executorService, objectMapper).build("test");

assertThat(Iterables.filter(client.getConfiguration().getInstances(), GZipDecoder.class)
.iterator().hasNext()).isFalse();
.iterator().hasNext()).isFalse();
assertThat(Iterables.filter(client.getConfiguration().getInstances(), ConfiguredGZipEncoder.class)
.iterator().hasNext()).isFalse();
.iterator().hasNext()).isFalse();
verify(apacheHttpClientBuilder).disableContentCompression(true);
}

Expand All @@ -227,9 +234,9 @@ public void usesAnExecutorServiceFromTheEnvironment() throws Exception {
when(executorServiceBuilderMock.maxThreads(532)).thenReturn(executorServiceBuilderMock);

final ArgumentCaptor<ArrayBlockingQueue> arrayBlockingQueueCaptor =
ArgumentCaptor.forClass(ArrayBlockingQueue.class);
ArgumentCaptor.forClass(ArrayBlockingQueue.class);
when(executorServiceBuilderMock.workQueue(arrayBlockingQueueCaptor.capture()))
.thenReturn(executorServiceBuilderMock);
.thenReturn(executorServiceBuilderMock);
when(executorServiceBuilderMock.build()).thenReturn(mock(ExecutorService.class));

builder.using(configuration).using(environment).build("test");
Expand Down Expand Up @@ -293,9 +300,9 @@ public X509Certificate[] getAcceptedIssuers() {
}
}, null);
final Registry<ConnectionSocketFactory> customRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", new SSLConnectionSocketFactory(ctx, new NoopHostnameVerifier()))
.build();
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", new SSLConnectionSocketFactory(ctx, new NoopHostnameVerifier()))
.build();
builder.using(customRegistry);
verify(apacheHttpClientBuilder).using(customRegistry);
}
Expand Down

0 comments on commit c7d6ecb

Please sign in to comment.