Skip to content

Commit

Permalink
HttpClientContext to use instance variables for standard attributes
Browse files Browse the repository at this point in the history
  • Loading branch information
ok2c committed Feb 29, 2024
1 parent f2b9a37 commit 762b18f
Show file tree
Hide file tree
Showing 55 changed files with 424 additions and 260 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public static HttpCacheContext adapt(final HttpContext context) {
}

public static HttpCacheContext create() {
return new HttpCacheContext(new HttpClientContext());
return new HttpCacheContext();
}

public HttpCacheContext(final HttpContext context) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -804,7 +804,7 @@ private void handleCacheHit(
scope.route,
scope.originalRequest,
new ComplexFuture<>(null),
HttpClientContext.create(),
HttpCacheContext.create(),
scope.execRuntime.fork(),
scope.scheduler,
scope.execCount);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ private ClassicHttpResponse handleCacheHit(
scope.route,
scope.originalRequest,
scope.execRuntime.fork(null),
HttpClientContext.create());
HttpCacheContext.create());
if (LOG.isDebugEnabled()) {
LOG.debug("{} starting asynchronous revalidation exchange {}", exchangeId, revalidationExchangeId);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -232,14 +232,14 @@ public Response execute(
final HttpClientContext localContext = HttpClientContext.create();
final CredentialsStore credentialsStoreSnapshot = credentialsStore;
if (credentialsStoreSnapshot != null) {
localContext.setAttribute(HttpClientContext.CREDS_PROVIDER, credentialsStoreSnapshot);
localContext.setCredentialsProvider(credentialsStoreSnapshot);
}
if (this.authCache != null) {
localContext.setAttribute(HttpClientContext.AUTH_CACHE, this.authCache);
localContext.setAuthCache(this.authCache);
}
final CookieStore cookieStoreSnapshot = cookieStore;
if (cookieStoreSnapshot != null) {
localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStoreSnapshot);
localContext.setCookieStore(cookieStoreSnapshot);
}
return new Response(request.internalExecute(this.httpclient, localContext));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ public ContextBuilder preemptiveBasicAuth(final HttpHost host, final UsernamePas

@Override
protected HttpClientContext createContext() {
return new HttpClientContext();
return HttpClientContext.create();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public Scope(
this.route = Args.notNull(route, "Route");
this.originalRequest = Args.notNull(originalRequest, "Original request");
this.cancellableDependency = Args.notNull(cancellableDependency, "Dependency");
this.clientContext = clientContext != null ? clientContext : HttpClientContext.create();
this.clientContext = Args.notNull(clientContext, "HTTP context");
this.execRuntime = Args.notNull(execRuntime, "Exec runtime");
this.scheduler = scheduler;
this.execCount = execCount != null ? execCount : new AtomicInteger(1);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public Scope(final String exchangeId, final HttpRoute route, final ClassicHttpRe
this.route = Args.notNull(route, "Route");
this.originalRequest = Args.notNull(originalRequest, "Original request");
this.execRuntime = Args.notNull(execRuntime, "Exec runtime");
this.clientContext = clientContext != null ? clientContext : HttpClientContext.create();
this.clientContext = Args.notNull(clientContext, "HTTP context");
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public List<AuthScheme> select(
Args.notNull(challengeType, "ChallengeType");
Args.notNull(challenges, "Map of auth challenges");
Args.notNull(context, "HTTP context");
final HttpClientContext clientContext = HttpClientContext.adapt(context);
final HttpClientContext clientContext = HttpClientContext.cast(context);
final String exchangeId = clientContext.getExchangeId();

final List<AuthScheme> options = new ArrayList<>();
Expand All @@ -88,7 +88,7 @@ public List<AuthScheme> select(
}
return options;
}
final RequestConfig config = clientContext.getRequestConfig();
final RequestConfig config = clientContext.getRequestConfigOrDefault();
Collection<String> authPrefs = challengeType == ChallengeType.TARGET ?
config.getTargetPreferredAuthSchemes() : config.getProxyPreferredAuthSchemes();
if (authPrefs == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,8 @@ public TimeValue getKeepAliveDuration(final HttpResponse response, final HttpCon
}
}
}
final HttpClientContext clientContext = HttpClientContext.adapt(context);
final RequestConfig requestConfig = clientContext.getRequestConfig();
final HttpClientContext clientContext = HttpClientContext.cast(context);
final RequestConfig requestConfig = clientContext.getRequestConfigOrDefault();
return requestConfig.getConnectionKeepAlive();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public Object getUserToken(final HttpRoute route, final HttpContext context) {
@Override
public Object getUserToken(final HttpRoute route, final HttpRequest request, final HttpContext context) {

final HttpClientContext clientContext = HttpClientContext.adapt(context);
final HttpClientContext clientContext = HttpClientContext.cast(context);

final HttpHost target = request != null ? new HttpHost(request.getScheme(), request.getAuthority()) : route.getTargetHost();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;

import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.core5.concurrent.Cancellable;
import org.apache.hc.core5.concurrent.ComplexFuture;
import org.apache.hc.core5.concurrent.FutureCallback;
Expand Down Expand Up @@ -86,7 +85,7 @@ public void cancelled() {
}

public final Cancellable execute(final AsyncClientExchangeHandler exchangeHandler) {
return execute(exchangeHandler, null, HttpClientContext.create());
return execute(exchangeHandler, null, null);
}

public abstract Cancellable execute(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -509,7 +509,7 @@ private boolean needAuthentication(
final HttpHost proxy,
final HttpResponse response,
final HttpClientContext context) {
final RequestConfig config = context.getRequestConfig();
final RequestConfig config = context.getRequestConfigOrDefault();
if (config.isAuthenticationEnabled()) {
final boolean proxyAuthRequested = authenticator.isChallenged(proxy, ChallengeType.PROXY, response, proxyAuthExchange, context);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ private boolean needAuthentication(
final String pathPrefix,
final HttpResponse response,
final HttpClientContext context) {
final RequestConfig config = context.getRequestConfig();
final RequestConfig config = context.getRequestConfigOrDefault();
if (config.isAuthenticationEnabled()) {
final boolean targetAuthRequested = authenticator.isChallenged(
target, ChallengeType.TARGET, response, targetAuthExchange, context);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ public AsyncDataConsumer handleResponse(
final EntityDetails entityDetails) throws HttpException, IOException {

state.redirectURI = null;
final RequestConfig config = clientContext.getRequestConfig();
final RequestConfig config = clientContext.getRequestConfigOrDefault();
if (config.isRedirectsEnabled() && redirectStrategy.isRedirected(request, response, clientContext)) {
if (state.redirectCount >= state.maxRedirects) {
throw new RedirectException("Maximum redirects (" + state.maxRedirects + ") exceeded");
Expand Down Expand Up @@ -263,11 +263,11 @@ public void execute(
RedirectLocations redirectLocations = clientContext.getRedirectLocations();
if (redirectLocations == null) {
redirectLocations = new RedirectLocations();
clientContext.setAttribute(HttpClientContext.REDIRECT_LOCATIONS, redirectLocations);
clientContext.setRedirectLocations(redirectLocations);
}
redirectLocations.clear();

final RequestConfig config = clientContext.getRequestConfig();
final RequestConfig config = clientContext.getRequestConfigOrDefault();

final State state = new State();
state.maxRedirects = config.getMaxRedirects() > 0 ? config.getMaxRedirects() : 50;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
import org.apache.hc.client5.http.async.methods.SimpleRequestProducer;
import org.apache.hc.client5.http.async.methods.SimpleResponseConsumer;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.core5.annotation.Contract;
import org.apache.hc.core5.annotation.ThreadingBehavior;
import org.apache.hc.core5.concurrent.FutureCallback;
Expand Down Expand Up @@ -113,7 +112,7 @@ public final <T> Future<T> execute(
final FutureCallback<T> callback) {
Args.notNull(requestProducer, "Request producer");
Args.notNull(responseConsumer, "Response consumer");
return execute(requestProducer, responseConsumer, HttpClientContext.create(), callback);
return execute(requestProducer, responseConsumer, null, callback);
}

public final Future<SimpleHttpResponse> execute(
Expand All @@ -127,7 +126,7 @@ public final Future<SimpleHttpResponse> execute(
public final Future<SimpleHttpResponse> execute(
final SimpleHttpRequest request,
final FutureCallback<SimpleHttpResponse> callback) {
return execute(request, HttpClientContext.create(), callback);
return execute(request, null, callback);
}

public abstract void register(String hostname, String uriPattern, Supplier<AsyncPushConsumer> supplier);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,9 +125,8 @@ public void cancel() {

@Override
public void produceRequest(final RequestChannel channel, final HttpContext context) throws HttpException, IOException {

clientContext.setAttribute(HttpClientContext.HTTP_ROUTE, route);
clientContext.setRequest(request);
clientContext.setRoute(route);
httpProcessor.process(request, entityProducer, clientContext);

channel.sendRequest(request, entityProducer, context);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ public void produceRequest(
final RequestChannel channel,
final HttpContext context) throws HttpException, IOException {

clientContext.setAttribute(HttpClientContext.HTTP_ROUTE, route);
clientContext.setRoute(route);
clientContext.setRequest(request);
httpProcessor.process(request, entityProducer, clientContext);

Expand Down Expand Up @@ -248,7 +248,7 @@ public void consumeResponse(
Object userToken = clientContext.getUserToken();
if (userToken == null) {
userToken = userTokenHandler.getUserToken(route, request, clientContext);
clientContext.setAttribute(HttpClientContext.USER_TOKEN, userToken);
clientContext.setUserToken(userToken);
}
execRuntime.markConnectionReusable(userToken, keepAliveDuration);
if (entityDetails == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ abstract class InternalAbstractHttpAsyncClient extends AbstractHttpAsyncClientBa
private final static ThreadFactory SCHEDULER_THREAD_FACTORY = new DefaultThreadFactory("Scheduled-executor", true);

private static final Logger LOG = LoggerFactory.getLogger(InternalAbstractHttpAsyncClient.class);

private final AsyncExecChainElement execChain;
private final Lookup<CookieSpecFactory> cookieSpecRegistry;
private final Lookup<AuthSchemeFactory> authSchemeRegistry;
Expand Down Expand Up @@ -165,20 +166,20 @@ void internalClose(final CloseMode closeMode) {
}

private void setupContext(final HttpClientContext context) {
if (context.getAttribute(HttpClientContext.AUTHSCHEME_REGISTRY) == null) {
context.setAttribute(HttpClientContext.AUTHSCHEME_REGISTRY, authSchemeRegistry);
if (context.getAuthSchemeRegistry() == null) {
context.setAuthSchemeRegistry(authSchemeRegistry);
}
if (context.getAttribute(HttpClientContext.COOKIESPEC_REGISTRY) == null) {
context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, cookieSpecRegistry);
if (context.getCookieSpecRegistry() == null) {
context.setCookieSpecRegistry(cookieSpecRegistry);
}
if (context.getAttribute(HttpClientContext.COOKIE_STORE) == null) {
context.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
if (context.getCookieStore() == null) {
context.setCookieStore(cookieStore);
}
if (context.getAttribute(HttpClientContext.CREDS_PROVIDER) == null) {
context.setAttribute(HttpClientContext.CREDS_PROVIDER, credentialsProvider);
if (context.getCredentialsProvider() == null) {
context.setCredentialsProvider(credentialsProvider);
}
if (context.getAttribute(HttpClientContext.REQUEST_CONFIG) == null) {
context.setAttribute(HttpClientContext.REQUEST_CONFIG, defaultConfig);
if (context.getRequestConfig() == null) {
context.setRequestConfig(defaultConfig);
}
}

Expand All @@ -199,7 +200,7 @@ protected <T> Future<T> doExecute(
if (!isRunning()) {
throw new CancellationException("Request execution cancelled");
}
final HttpClientContext clientContext = context != null ? HttpClientContext.adapt(context) : HttpClientContext.create();
final HttpClientContext clientContext = HttpClientContext.adapt(context);
requestProducer.sendRequest((request, entityDetails, c) -> {

RequestConfig requestConfig = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public Cancellable acquireEndpoint(
final HttpClientContext context,
final FutureCallback<AsyncExecRuntime> callback) {
if (sessionRef.get() == null) {
final RequestConfig requestConfig = context.getRequestConfig();
final RequestConfig requestConfig = context.getRequestConfigOrDefault();
@SuppressWarnings("deprecation")
final Timeout connectTimeout = requestConfig.getConnectTimeout();
if (log.isDebugEnabled()) {
Expand Down Expand Up @@ -183,7 +183,7 @@ public Cancellable connectEndpoint(
return Operations.nonCancellable();
}
final HttpRoute route = endpoint.route;
final RequestConfig requestConfig = context.getRequestConfig();
final RequestConfig requestConfig = context.getRequestConfigOrDefault();
@SuppressWarnings("deprecation")
final Timeout connectTimeout = requestConfig.getConnectTimeout();
if (log.isDebugEnabled()) {
Expand Down Expand Up @@ -262,7 +262,7 @@ public Cancellable execute(
Command.Priority.NORMAL);
} else {
final HttpRoute route = endpoint.route;
final RequestConfig requestConfig = context.getRequestConfig();
final RequestConfig requestConfig = context.getRequestConfigOrDefault();
@SuppressWarnings("deprecation")
final Timeout connectTimeout = requestConfig.getConnectTimeout();
connPool.getSession(route, connectTimeout, new FutureCallback<IOSession>() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ public Cancellable acquireEndpoint(
final FutureCallback<AsyncExecRuntime> callback) {
if (endpointRef.get() == null) {
state = object;
final RequestConfig requestConfig = context.getRequestConfig();
final RequestConfig requestConfig = context.getRequestConfigOrDefault();
final Timeout connectionRequestTimeout = requestConfig.getConnectionRequestTimeout();
if (log.isDebugEnabled()) {
log.debug("{} acquiring endpoint ({})", id, connectionRequestTimeout);
Expand Down Expand Up @@ -208,7 +208,7 @@ public Cancellable connectEndpoint(
callback.completed(this);
return Operations.nonCancellable();
}
final RequestConfig requestConfig = context.getRequestConfig();
final RequestConfig requestConfig = context.getRequestConfigOrDefault();
@SuppressWarnings("deprecation")
final Timeout connectTimeout = requestConfig.getConnectTimeout();
if (log.isDebugEnabled()) {
Expand Down Expand Up @@ -280,13 +280,13 @@ public Cancellable execute(
if (log.isDebugEnabled()) {
log.debug("{} start execution {}", ConnPoolSupport.getId(endpoint), id);
}
final RequestConfig requestConfig = context.getRequestConfig();
final RequestConfig requestConfig = context.getRequestConfigOrDefault();
final Timeout responseTimeout = requestConfig.getResponseTimeout();
if (responseTimeout != null) {
endpoint.setSocketTimeout(responseTimeout);
}
endpoint.execute(id, exchangeHandler, context);
if (context.getRequestConfig().isHardCancellationEnabled()) {
if (context.getRequestConfigOrDefault().isHardCancellationEnabled()) {
return () -> {
exchangeHandler.cancel();
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
import org.apache.hc.core5.reactor.IOEventHandlerFactory;
import org.apache.hc.core5.reactor.IOReactorConfig;
import org.apache.hc.core5.reactor.IOSession;
import org.apache.hc.core5.util.Args;
import org.apache.hc.core5.util.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand Down Expand Up @@ -122,12 +123,13 @@ public Cancellable execute(
final AsyncClientExchangeHandler exchangeHandler,
final HandlerFactory<AsyncPushConsumer> pushHandlerFactory,
final HttpContext context) {
Args.notNull(exchangeHandler, "Message exchange handler");
final ComplexCancellable cancellable = new ComplexCancellable();
try {
if (!isRunning()) {
throw new CancellationException("Request execution cancelled");
}
final HttpClientContext clientContext = context != null ? HttpClientContext.adapt(context) : HttpClientContext.create();
final HttpClientContext clientContext = HttpClientContext.adapt(context);
exchangeHandler.produceRequest((request, entityDetails, context1) -> {
RequestConfig requestConfig = null;
if (request instanceof Configurable) {
Expand All @@ -136,7 +138,7 @@ public Cancellable execute(
if (requestConfig != null) {
clientContext.setRequestConfig(requestConfig);
} else {
requestConfig = clientContext.getRequestConfig();
requestConfig = clientContext.getRequestConfigOrDefault();
}
@SuppressWarnings("deprecation")
final Timeout connectTimeout = requestConfig.getConnectTimeout();
Expand Down
Loading

0 comments on commit 762b18f

Please sign in to comment.