HTTPCLIENT-2096: Migrate instance loggers to static fields

Note that this may change the origin of logging when classes
have been subclassed, as the logger origin will use the class
name that defined the logger where previously the subclass type
would be used. In scenarios where external libraries subclass
httpclient utilities this allows httpclient logging to maintain
the `org.apache.hc` prefix instead of inheriting arbitrary
subclass names.

Using some logging frameworks this may result in reduced churn
when httpclient components are created (new connections, for example)
because loggers are looked up once per class.
This commit is contained in:
Carter Kozak 2020-07-05 13:28:48 -04:00 committed by Oleg Kalnichevski
parent 9a967de60e
commit 9866865357
63 changed files with 701 additions and 682 deletions

View File

@ -75,6 +75,8 @@ import org.apache.hc.core5.http.protocol.HttpCoreContext;
import org.apache.hc.core5.net.URIAuthority;
import org.apache.hc.core5.util.Args;
import org.apache.hc.core5.util.ByteArrayBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Request executor in the request execution chain that is responsible for
@ -90,6 +92,7 @@ import org.apache.hc.core5.util.ByteArrayBuffer;
@Contract(threading = ThreadingBehavior.SAFE) // So long as the responseCache implementation is threadsafe
class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler {
private static final Logger LOG = LoggerFactory.getLogger(AsyncCachingExec.class);
private final HttpAsyncCache responseCache;
private final DefaultAsyncCacheRevalidator cacheRevalidator;
private final ConditionalRequestBuilder<HttpRequest> conditionalRequestBuilder;
@ -236,7 +239,7 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
request.addHeader("Via",via);
if (!cacheableRequestPolicy.isServableFromCache(request)) {
log.debug("Request is not servable from cache");
LOG.debug("Request is not servable from cache");
operation.setDependency(responseCache.flushCacheEntriesInvalidatedByRequest(target, request, new FutureCallback<Boolean>() {
@Override
@ -261,7 +264,7 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
@Override
public void completed(final HttpCacheEntry entry) {
if (entry == null) {
log.debug("Cache miss");
LOG.debug("Cache miss");
handleCacheMiss(target, request, entityProducer, scope, chain, asyncExecCallback);
} else {
handleCacheHit(target, request, entityProducer, scope, chain, asyncExecCallback, entry);
@ -303,7 +306,7 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
final AsyncExecChain.Scope scope,
final AsyncExecChain chain,
final AsyncExecCallback asyncExecCallback) {
log.debug("Calling the backend");
LOG.debug("Calling the backend");
final Date requestDate = getCurrentDate();
final AtomicReference<AsyncExecCallback> callbackRef = new AtomicReference<>();
chainProceed(request, entityProducer, scope, chain, new AsyncExecCallback() {
@ -396,7 +399,7 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
}
}
if (buffer.length() > cacheConfig.getMaxObjectSize()) {
log.debug("Backend response content length exceeds maximum");
LOG.debug("Backend response content length exceeds maximum");
// Over the max limit. Stop buffering and forward the response
// along with all the data buffered so far to the caller.
bufferRef.set(null);
@ -476,7 +479,7 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
@Override
public void failed(final Exception ex) {
log.warn("Unable to flush invalidated entries from cache", ex);
LOG.warn("Unable to flush invalidated entries from cache", ex);
}
@Override
@ -489,7 +492,7 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
cachingConsumerRef.set(new CachingAsyncDataConsumer(asyncExecCallback, backendResponse, entityDetails));
storeRequestIfModifiedSinceFor304Response(request, backendResponse);
} else {
log.debug("Backend response is not cacheable");
LOG.debug("Backend response is not cacheable");
responseCache.flushCacheEntriesFor(target, request, new FutureCallback<Boolean>() {
@Override
@ -498,7 +501,7 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
@Override
public void failed(final Exception ex) {
log.warn("Unable to flush invalidated entries from cache", ex);
LOG.warn("Unable to flush invalidated entries from cache", ex);
}
@Override
@ -509,7 +512,7 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
}
final CachingAsyncDataConsumer cachingDataConsumer = cachingConsumerRef.get();
if (cachingDataConsumer != null) {
log.debug("Caching backend response");
LOG.debug("Caching backend response");
return cachingDataConsumer;
}
return asyncExecCallback.handleResponse(backendResponse, entityDetails);
@ -533,7 +536,7 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
@Override
public void completed(final HttpCacheEntry newEntry) {
log.debug("Backend response successfully cached");
LOG.debug("Backend response successfully cached");
try {
final SimpleHttpResponse cacheResponse = responseGenerator.generateResponse(request, newEntry);
triggerResponse(cacheResponse, scope, asyncExecCallback);
@ -569,7 +572,7 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
@Override
public void completed(final HttpCacheEntry existingEntry) {
if (DateUtils.isAfter(existingEntry, backendResponse, HttpHeaders.DATE)) {
log.debug("Backend already contains fresher cache entry");
LOG.debug("Backend already contains fresher cache entry");
try {
final SimpleHttpResponse cacheResponse = responseGenerator.generateResponse(request, existingEntry);
triggerResponse(cacheResponse, scope, asyncExecCallback);
@ -619,7 +622,7 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
recordCacheHit(target, request);
final Date now = getCurrentDate();
if (suitabilityChecker.canCachedResponseBeUsed(target, request, entry, now)) {
log.debug("Cache hit");
LOG.debug("Cache hit");
try {
final SimpleHttpResponse cacheResponse = generateCachedResponse(request, context, entry, now);
triggerResponse(cacheResponse, scope, asyncExecCallback);
@ -638,15 +641,15 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
}
}
} else if (!mayCallBackend(request)) {
log.debug("Cache entry not suitable but only-if-cached requested");
LOG.debug("Cache entry not suitable but only-if-cached requested");
final SimpleHttpResponse cacheResponse = generateGatewayTimeout(context);
triggerResponse(cacheResponse, scope, asyncExecCallback);
} else if (!(entry.getStatus() == HttpStatus.SC_NOT_MODIFIED && !suitabilityChecker.isConditional(request))) {
log.debug("Revalidating cache entry");
LOG.debug("Revalidating cache entry");
if (cacheRevalidator != null
&& !staleResponseNotAllowed(request, entry, now)
&& validityPolicy.mayReturnStaleWhileRevalidating(entry, now)) {
log.debug("Serving stale with asynchronous revalidation");
LOG.debug("Serving stale with asynchronous revalidation");
try {
final SimpleHttpResponse cacheResponse = generateCachedResponse(request, context, entry, now);
final String exchangeId = ExecSupport.getNextExchangeId();
@ -676,7 +679,7 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
revalidateCacheEntry(target, request, entityProducer, scope, chain, asyncExecCallback, entry);
}
} else {
log.debug("Cache entry not usable; calling backend");
LOG.debug("Cache entry not usable; calling backend");
callBackend(target, request, entityProducer, scope, chain, asyncExecCallback);
}
}
@ -1016,7 +1019,7 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
} else {
final Header resultEtagHeader = backendResponse.getFirstHeader(HeaderConstants.ETAG);
if (resultEtagHeader == null) {
log.warn("304 response did not contain ETag");
LOG.warn("304 response did not contain ETag");
callback = new AsyncExecCallbackWrapper(asyncExecCallback, new Runnable() {
@Override
@ -1029,7 +1032,7 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
final String resultEtag = resultEtagHeader.getValue();
final Variant matchingVariant = variants.get(resultEtag);
if (matchingVariant == null) {
log.debug("304 response did not contain ETag matching one sent in If-None-Match");
LOG.debug("304 response did not contain ETag matching one sent in If-None-Match");
callback = new AsyncExecCallbackWrapper(asyncExecCallback, new Runnable() {
@Override

View File

@ -56,7 +56,7 @@ import org.slf4j.LoggerFactory;
class BasicHttpAsyncCache implements HttpAsyncCache {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(BasicHttpAsyncCache.class);
private final CacheUpdateHandler cacheUpdateHandler;
private final CacheKeyGenerator cacheKeyGenerator;
@ -97,8 +97,8 @@ class BasicHttpAsyncCache implements HttpAsyncCache {
@Override
public Cancellable flushCacheEntriesFor(
final HttpHost host, final HttpRequest request, final FutureCallback<Boolean> callback) {
if (log.isDebugEnabled()) {
log.debug("Flush cache entries: {}; {}", host, new RequestLine(request));
if (LOG.isDebugEnabled()) {
LOG.debug("Flush cache entries: {}; {}", host, new RequestLine(request));
}
if (!Method.isSafe(request.getMethod())) {
final String cacheKey = cacheKeyGenerator.generateKey(host, request);
@ -112,8 +112,8 @@ class BasicHttpAsyncCache implements HttpAsyncCache {
@Override
public void failed(final Exception ex) {
if (ex instanceof ResourceIOException) {
if (log.isWarnEnabled()) {
log.warn("I/O error removing cache entry with key {}", cacheKey);
if (LOG.isWarnEnabled()) {
LOG.warn("I/O error removing cache entry with key {}", cacheKey);
}
callback.completed(Boolean.TRUE);
} else {
@ -135,8 +135,8 @@ class BasicHttpAsyncCache implements HttpAsyncCache {
@Override
public Cancellable flushCacheEntriesInvalidatedByRequest(
final HttpHost host, final HttpRequest request, final FutureCallback<Boolean> callback) {
if (log.isDebugEnabled()) {
log.debug("Flush cache entries invalidated by request: {}; {}", host, new RequestLine(request));
if (LOG.isDebugEnabled()) {
LOG.debug("Flush cache entries invalidated by request: {}; {}", host, new RequestLine(request));
}
return cacheInvalidator.flushCacheEntriesInvalidatedByRequest(host, request, cacheKeyGenerator, storage, callback);
}
@ -144,8 +144,8 @@ class BasicHttpAsyncCache implements HttpAsyncCache {
@Override
public Cancellable flushCacheEntriesInvalidatedByExchange(
final HttpHost host, final HttpRequest request, final HttpResponse response, final FutureCallback<Boolean> callback) {
if (log.isDebugEnabled()) {
log.debug("Flush cache entries invalidated by exchange: {}; {} -> {}", host, new RequestLine(request), new StatusLine(response));
if (LOG.isDebugEnabled()) {
LOG.debug("Flush cache entries invalidated by exchange: {}; {} -> {}", host, new RequestLine(request), new StatusLine(response));
}
if (!Method.isSafe(request.getMethod())) {
return cacheInvalidator.flushCacheEntriesInvalidatedByExchange(host, request, response, cacheKeyGenerator, storage, callback);
@ -181,8 +181,8 @@ class BasicHttpAsyncCache implements HttpAsyncCache {
@Override
public void failed(final Exception ex) {
if (ex instanceof ResourceIOException) {
if (log.isWarnEnabled()) {
log.warn("I/O error storing cache entry with key {}", cacheKey);
if (LOG.isWarnEnabled()) {
LOG.warn("I/O error storing cache entry with key {}", cacheKey);
}
callback.completed(Boolean.TRUE);
} else {
@ -229,12 +229,12 @@ class BasicHttpAsyncCache implements HttpAsyncCache {
@Override
public void failed(final Exception ex) {
if (ex instanceof HttpCacheUpdateException) {
if (log.isWarnEnabled()) {
log.warn("Cannot update cache entry with key {}", cacheKey);
if (LOG.isWarnEnabled()) {
LOG.warn("Cannot update cache entry with key {}", cacheKey);
}
} else if (ex instanceof ResourceIOException) {
if (log.isWarnEnabled()) {
log.warn("I/O error updating cache entry with key {}", cacheKey);
if (LOG.isWarnEnabled()) {
LOG.warn("I/O error updating cache entry with key {}", cacheKey);
}
} else {
callback.failed(ex);
@ -252,8 +252,8 @@ class BasicHttpAsyncCache implements HttpAsyncCache {
@Override
public void failed(final Exception ex) {
if (ex instanceof ResourceIOException) {
if (log.isWarnEnabled()) {
log.warn("I/O error updating cache entry with key {}", variantCacheKey);
if (LOG.isWarnEnabled()) {
LOG.warn("I/O error updating cache entry with key {}", variantCacheKey);
}
callback.completed(Boolean.TRUE);
} else {
@ -272,8 +272,8 @@ class BasicHttpAsyncCache implements HttpAsyncCache {
@Override
public Cancellable reuseVariantEntryFor(
final HttpHost host, final HttpRequest request, final Variant variant, final FutureCallback<Boolean> callback) {
if (log.isDebugEnabled()) {
log.debug("Re-use variant entry: {}; {} / {}", host, new RequestLine(request), variant);
if (LOG.isDebugEnabled()) {
LOG.debug("Re-use variant entry: {}; {} / {}", host, new RequestLine(request), variant);
}
final String cacheKey = cacheKeyGenerator.generateKey(host, request);
final HttpCacheEntry entry = variant.getEntry();
@ -298,12 +298,12 @@ class BasicHttpAsyncCache implements HttpAsyncCache {
@Override
public void failed(final Exception ex) {
if (ex instanceof HttpCacheUpdateException) {
if (log.isWarnEnabled()) {
log.warn("Cannot update cache entry with key {}", cacheKey);
if (LOG.isWarnEnabled()) {
LOG.warn("Cannot update cache entry with key {}", cacheKey);
}
} else if (ex instanceof ResourceIOException) {
if (log.isWarnEnabled()) {
log.warn("I/O error updating cache entry with key {}", cacheKey);
if (LOG.isWarnEnabled()) {
LOG.warn("I/O error updating cache entry with key {}", cacheKey);
}
} else {
callback.failed(ex);
@ -327,8 +327,8 @@ class BasicHttpAsyncCache implements HttpAsyncCache {
final Date requestSent,
final Date responseReceived,
final FutureCallback<HttpCacheEntry> callback) {
if (log.isDebugEnabled()) {
log.debug("Update cache entry: {}; {}", host, new RequestLine(request));
if (LOG.isDebugEnabled()) {
LOG.debug("Update cache entry: {}; {}", host, new RequestLine(request));
}
final String cacheKey = cacheKeyGenerator.generateKey(host, request);
try {
@ -357,8 +357,8 @@ class BasicHttpAsyncCache implements HttpAsyncCache {
});
} catch (final ResourceIOException ex) {
if (log.isWarnEnabled()) {
log.warn("I/O error updating cache entry with key {}", cacheKey);
if (LOG.isWarnEnabled()) {
LOG.warn("I/O error updating cache entry with key {}", cacheKey);
}
callback.completed(stale);
return Operations.nonCancellable();
@ -374,8 +374,8 @@ class BasicHttpAsyncCache implements HttpAsyncCache {
final Date requestSent,
final Date responseReceived,
final FutureCallback<HttpCacheEntry> callback) {
if (log.isDebugEnabled()) {
log.debug("Update variant cache entry: {}; {} / {}", host, new RequestLine(request), variant);
if (LOG.isDebugEnabled()) {
LOG.debug("Update variant cache entry: {}; {} / {}", host, new RequestLine(request), variant);
}
final HttpCacheEntry entry = variant.getEntry();
final String cacheKey = variant.getCacheKey();
@ -405,8 +405,8 @@ class BasicHttpAsyncCache implements HttpAsyncCache {
});
} catch (final ResourceIOException ex) {
if (log.isWarnEnabled()) {
log.warn("I/O error updating cache entry with key {}", cacheKey);
if (LOG.isWarnEnabled()) {
LOG.warn("I/O error updating cache entry with key {}", cacheKey);
}
callback.completed(entry);
return Operations.nonCancellable();
@ -422,8 +422,8 @@ class BasicHttpAsyncCache implements HttpAsyncCache {
final Date requestSent,
final Date responseReceived,
final FutureCallback<HttpCacheEntry> callback) {
if (log.isDebugEnabled()) {
log.debug("Create cache entry: {}; {}", host, new RequestLine(request));
if (LOG.isDebugEnabled()) {
LOG.debug("Create cache entry: {}; {}", host, new RequestLine(request));
}
final String cacheKey = cacheKeyGenerator.generateKey(host, request);
try {
@ -447,8 +447,8 @@ class BasicHttpAsyncCache implements HttpAsyncCache {
});
} catch (final ResourceIOException ex) {
if (log.isWarnEnabled()) {
log.warn("I/O error creating cache entry with key {}", cacheKey);
if (LOG.isWarnEnabled()) {
LOG.warn("I/O error creating cache entry with key {}", cacheKey);
}
callback.completed(new HttpCacheEntry(
requestSent,
@ -462,8 +462,8 @@ class BasicHttpAsyncCache implements HttpAsyncCache {
@Override
public Cancellable getCacheEntry(final HttpHost host, final HttpRequest request, final FutureCallback<HttpCacheEntry> callback) {
if (log.isDebugEnabled()) {
log.debug("Get cache entry: {}; {}", host, new RequestLine(request));
if (LOG.isDebugEnabled()) {
LOG.debug("Get cache entry: {}; {}", host, new RequestLine(request));
}
final ComplexCancellable complexCancellable = new ComplexCancellable();
final String cacheKey = cacheKeyGenerator.generateKey(host, request);
@ -488,8 +488,8 @@ class BasicHttpAsyncCache implements HttpAsyncCache {
@Override
public void failed(final Exception ex) {
if (ex instanceof ResourceIOException) {
if (log.isWarnEnabled()) {
log.warn("I/O error retrieving cache entry with key {}", variantCacheKey);
if (LOG.isWarnEnabled()) {
LOG.warn("I/O error retrieving cache entry with key {}", variantCacheKey);
}
callback.completed(null);
} else {
@ -513,8 +513,8 @@ class BasicHttpAsyncCache implements HttpAsyncCache {
@Override
public void failed(final Exception ex) {
if (ex instanceof ResourceIOException) {
if (log.isWarnEnabled()) {
log.warn("I/O error retrieving cache entry with key {}", cacheKey);
if (LOG.isWarnEnabled()) {
LOG.warn("I/O error retrieving cache entry with key {}", cacheKey);
}
callback.completed(null);
} else {
@ -534,8 +534,8 @@ class BasicHttpAsyncCache implements HttpAsyncCache {
@Override
public Cancellable getVariantCacheEntriesWithEtags(
final HttpHost host, final HttpRequest request, final FutureCallback<Map<String, Variant>> callback) {
if (log.isDebugEnabled()) {
log.debug("Get variant cache entries: {}; {}", host, new RequestLine(request));
if (LOG.isDebugEnabled()) {
LOG.debug("Get variant cache entries: {}; {}", host, new RequestLine(request));
}
final ComplexCancellable complexCancellable = new ComplexCancellable();
final String cacheKey = cacheKeyGenerator.generateKey(host, request);
@ -566,8 +566,8 @@ class BasicHttpAsyncCache implements HttpAsyncCache {
@Override
public void failed(final Exception ex) {
if (ex instanceof ResourceIOException) {
if (log.isWarnEnabled()) {
log.warn("I/O error retrieving cache entry with keys {}", variantCacheKeys);
if (LOG.isWarnEnabled()) {
LOG.warn("I/O error retrieving cache entry with keys {}", variantCacheKeys);
}
callback.completed(variants);
} else {
@ -589,8 +589,8 @@ class BasicHttpAsyncCache implements HttpAsyncCache {
@Override
public void failed(final Exception ex) {
if (ex instanceof ResourceIOException) {
if (log.isWarnEnabled()) {
log.warn("I/O error retrieving cache entry with key {}", cacheKey);
if (LOG.isWarnEnabled()) {
LOG.warn("I/O error retrieving cache entry with key {}", cacheKey);
}
callback.completed(variants);
} else {

View File

@ -51,7 +51,7 @@ import org.slf4j.LoggerFactory;
class BasicHttpCache implements HttpCache {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(BasicHttpCache.class);
private final CacheUpdateHandler cacheUpdateHandler;
private final CacheKeyGenerator cacheKeyGenerator;
@ -99,16 +99,16 @@ class BasicHttpCache implements HttpCache {
@Override
public void flushCacheEntriesFor(final HttpHost host, final HttpRequest request) {
if (log.isDebugEnabled()) {
log.debug("Flush cache entries: {}; {}", host, new RequestLine(request));
if (LOG.isDebugEnabled()) {
LOG.debug("Flush cache entries: {}; {}", host, new RequestLine(request));
}
if (!Method.isSafe(request.getMethod())) {
final String cacheKey = cacheKeyGenerator.generateKey(host, request);
try {
storage.removeEntry(cacheKey);
} catch (final ResourceIOException ex) {
if (log.isWarnEnabled()) {
log.warn("I/O error removing cache entry with key {}", cacheKey);
if (LOG.isWarnEnabled()) {
LOG.warn("I/O error removing cache entry with key {}", cacheKey);
}
}
}
@ -116,16 +116,16 @@ class BasicHttpCache implements HttpCache {
@Override
public void flushCacheEntriesInvalidatedByRequest(final HttpHost host, final HttpRequest request) {
if (log.isDebugEnabled()) {
log.debug("Flush cache entries invalidated by request: {}; {}", host, new RequestLine(request));
if (LOG.isDebugEnabled()) {
LOG.debug("Flush cache entries invalidated by request: {}; {}", host, new RequestLine(request));
}
cacheInvalidator.flushCacheEntriesInvalidatedByRequest(host, request, cacheKeyGenerator, storage);
}
@Override
public void flushCacheEntriesInvalidatedByExchange(final HttpHost host, final HttpRequest request, final HttpResponse response) {
if (log.isDebugEnabled()) {
log.debug("Flush cache entries invalidated by exchange: {}; {} -> {}", host, new RequestLine(request), new StatusLine(response));
if (LOG.isDebugEnabled()) {
LOG.debug("Flush cache entries invalidated by exchange: {}; {} -> {}", host, new RequestLine(request), new StatusLine(response));
}
if (!Method.isSafe(request.getMethod())) {
cacheInvalidator.flushCacheEntriesInvalidatedByExchange(host, request, response, cacheKeyGenerator, storage);
@ -148,8 +148,8 @@ class BasicHttpCache implements HttpCache {
try {
storage.putEntry(cacheKey, entry);
} catch (final ResourceIOException ex) {
if (log.isWarnEnabled()) {
log.warn("I/O error storing cache entry with key {}", cacheKey);
if (LOG.isWarnEnabled()) {
LOG.warn("I/O error storing cache entry with key {}", cacheKey);
}
}
}
@ -172,12 +172,12 @@ class BasicHttpCache implements HttpCache {
});
} catch (final HttpCacheUpdateException ex) {
if (log.isWarnEnabled()) {
log.warn("Cannot update cache entry with key {}", cacheKey);
if (LOG.isWarnEnabled()) {
LOG.warn("Cannot update cache entry with key {}", cacheKey);
}
} catch (final ResourceIOException ex) {
if (log.isWarnEnabled()) {
log.warn("I/O error updating cache entry with key {}", cacheKey);
if (LOG.isWarnEnabled()) {
LOG.warn("I/O error updating cache entry with key {}", cacheKey);
}
}
}
@ -185,8 +185,8 @@ class BasicHttpCache implements HttpCache {
@Override
public void reuseVariantEntryFor(
final HttpHost host, final HttpRequest request, final Variant variant) {
if (log.isDebugEnabled()) {
log.debug("Re-use variant entry: {}; {} / {}", host, new RequestLine(request), variant);
if (LOG.isDebugEnabled()) {
LOG.debug("Re-use variant entry: {}; {} / {}", host, new RequestLine(request), variant);
}
final String cacheKey = cacheKeyGenerator.generateKey(host, request);
final HttpCacheEntry entry = variant.getEntry();
@ -203,12 +203,12 @@ class BasicHttpCache implements HttpCache {
});
} catch (final HttpCacheUpdateException ex) {
if (log.isWarnEnabled()) {
log.warn("Cannot update cache entry with key {}", cacheKey);
if (LOG.isWarnEnabled()) {
LOG.warn("Cannot update cache entry with key {}", cacheKey);
}
} catch (final ResourceIOException ex) {
if (log.isWarnEnabled()) {
log.warn("I/O error updating cache entry with key {}", cacheKey);
if (LOG.isWarnEnabled()) {
LOG.warn("I/O error updating cache entry with key {}", cacheKey);
}
}
}
@ -221,8 +221,8 @@ class BasicHttpCache implements HttpCache {
final HttpResponse originResponse,
final Date requestSent,
final Date responseReceived) {
if (log.isDebugEnabled()) {
log.debug("Update cache entry: {}; {}", host, new RequestLine(request));
if (LOG.isDebugEnabled()) {
LOG.debug("Update cache entry: {}; {}", host, new RequestLine(request));
}
final String cacheKey = cacheKeyGenerator.generateKey(host, request);
try {
@ -235,8 +235,8 @@ class BasicHttpCache implements HttpCache {
storeInCache(cacheKey, host, request, updatedEntry);
return updatedEntry;
} catch (final ResourceIOException ex) {
if (log.isWarnEnabled()) {
log.warn("I/O error updating cache entry with key {}", cacheKey);
if (LOG.isWarnEnabled()) {
LOG.warn("I/O error updating cache entry with key {}", cacheKey);
}
return stale;
}
@ -250,8 +250,8 @@ class BasicHttpCache implements HttpCache {
final Variant variant,
final Date requestSent,
final Date responseReceived) {
if (log.isDebugEnabled()) {
log.debug("Update variant cache entry: {}; {} / {}", host, new RequestLine(request), variant);
if (LOG.isDebugEnabled()) {
LOG.debug("Update variant cache entry: {}; {} / {}", host, new RequestLine(request), variant);
}
final HttpCacheEntry entry = variant.getEntry();
final String cacheKey = variant.getCacheKey();
@ -265,8 +265,8 @@ class BasicHttpCache implements HttpCache {
storeEntry(cacheKey, updatedEntry);
return updatedEntry;
} catch (final ResourceIOException ex) {
if (log.isWarnEnabled()) {
log.warn("I/O error updating cache entry with key {}", cacheKey);
if (LOG.isWarnEnabled()) {
LOG.warn("I/O error updating cache entry with key {}", cacheKey);
}
return entry;
}
@ -280,8 +280,8 @@ class BasicHttpCache implements HttpCache {
final ByteArrayBuffer content,
final Date requestSent,
final Date responseReceived) {
if (log.isDebugEnabled()) {
log.debug("Create cache entry: {}; {}", host, new RequestLine(request));
if (LOG.isDebugEnabled()) {
LOG.debug("Create cache entry: {}; {}", host, new RequestLine(request));
}
final String cacheKey = cacheKeyGenerator.generateKey(host, request);
try {
@ -289,8 +289,8 @@ class BasicHttpCache implements HttpCache {
storeInCache(cacheKey, host, request, entry);
return entry;
} catch (final ResourceIOException ex) {
if (log.isWarnEnabled()) {
log.warn("I/O error creating cache entry with key {}", cacheKey);
if (LOG.isWarnEnabled()) {
LOG.warn("I/O error creating cache entry with key {}", cacheKey);
}
return new HttpCacheEntry(
requestSent,
@ -303,16 +303,16 @@ class BasicHttpCache implements HttpCache {
@Override
public HttpCacheEntry getCacheEntry(final HttpHost host, final HttpRequest request) {
if (log.isDebugEnabled()) {
log.debug("Get cache entry: {}; {}", host, new RequestLine(request));
if (LOG.isDebugEnabled()) {
LOG.debug("Get cache entry: {}; {}", host, new RequestLine(request));
}
final String cacheKey = cacheKeyGenerator.generateKey(host, request);
final HttpCacheEntry root;
try {
root = storage.getEntry(cacheKey);
} catch (final ResourceIOException ex) {
if (log.isWarnEnabled()) {
log.warn("I/O error retrieving cache entry with key {}", cacheKey);
if (LOG.isWarnEnabled()) {
LOG.warn("I/O error retrieving cache entry with key {}", cacheKey);
}
return null;
}
@ -330,8 +330,8 @@ class BasicHttpCache implements HttpCache {
try {
return storage.getEntry(variantCacheKey);
} catch (final ResourceIOException ex) {
if (log.isWarnEnabled()) {
log.warn("I/O error retrieving cache entry with key {}", variantCacheKey);
if (LOG.isWarnEnabled()) {
LOG.warn("I/O error retrieving cache entry with key {}", variantCacheKey);
}
return null;
}
@ -339,8 +339,8 @@ class BasicHttpCache implements HttpCache {
@Override
public Map<String, Variant> getVariantCacheEntriesWithEtags(final HttpHost host, final HttpRequest request) {
if (log.isDebugEnabled()) {
log.debug("Get variant cache entries: {}; {}", host, new RequestLine(request));
if (LOG.isDebugEnabled()) {
LOG.debug("Get variant cache entries: {}; {}", host, new RequestLine(request));
}
final Map<String,Variant> variants = new HashMap<>();
final String cacheKey = cacheKeyGenerator.generateKey(host, request);
@ -348,8 +348,8 @@ class BasicHttpCache implements HttpCache {
try {
root = storage.getEntry(cacheKey);
} catch (final ResourceIOException ex) {
if (log.isWarnEnabled()) {
log.warn("I/O error retrieving cache entry with key {}", cacheKey);
if (LOG.isWarnEnabled()) {
LOG.warn("I/O error retrieving cache entry with key {}", cacheKey);
}
return variants;
}
@ -365,8 +365,8 @@ class BasicHttpCache implements HttpCache {
}
}
} catch (final ResourceIOException ex) {
if (log.isWarnEnabled()) {
log.warn("I/O error retrieving cache entry with key {}", variantCacheKey);
if (LOG.isWarnEnabled()) {
LOG.warn("I/O error retrieving cache entry with key {}", variantCacheKey);
}
return variants;
}

View File

@ -94,7 +94,7 @@ class CacheRevalidatorBase implements Closeable {
private final Set<String> pendingRequest;
private final ConcurrentCountMap<String> failureCache;
final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(CacheRevalidatorBase.class);
/**
* Create CacheValidator which will make ache revalidation requests
@ -131,7 +131,7 @@ class CacheRevalidatorBase implements Closeable {
scheduledExecutor.schedule(command, executionTime);
pendingRequest.add(cacheKey);
} catch (final RejectedExecutionException ex) {
log.debug("Revalidation of cache entry with key {} could not be scheduled", cacheKey, ex);
LOG.debug("Revalidation of cache entry with key {} could not be scheduled", cacheKey, ex);
}
}
}

View File

@ -42,7 +42,7 @@ import org.slf4j.LoggerFactory;
*/
class CacheableRequestPolicy {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(CacheableRequestPolicy.class);
/**
* Determines if an HttpRequest can be served from the cache.
@ -56,19 +56,19 @@ class CacheableRequestPolicy {
final ProtocolVersion pv = request.getVersion() != null ? request.getVersion() : HttpVersion.DEFAULT;
if (HttpVersion.HTTP_1_1.compareToVersion(pv) != 0) {
log.debug("non-HTTP/1.1 request is not serveable from cache");
LOG.debug("non-HTTP/1.1 request is not serveable from cache");
return false;
}
if (!method.equals(HeaderConstants.GET_METHOD) && !method.equals(HeaderConstants.HEAD_METHOD)) {
if (log.isDebugEnabled()) {
log.debug("{} request is not serveable from cache", method);
if (LOG.isDebugEnabled()) {
LOG.debug("{} request is not serveable from cache", method);
}
return false;
}
if (request.countHeaders(HeaderConstants.PRAGMA) > 0) {
log.debug("request with Pragma header is not serveable from cache");
LOG.debug("request with Pragma header is not serveable from cache");
return false;
}
@ -76,16 +76,16 @@ class CacheableRequestPolicy {
while (it.hasNext()) {
final HeaderElement cacheControlElement = it.next();
if (HeaderConstants.CACHE_CONTROL_NO_STORE.equalsIgnoreCase(cacheControlElement.getName())) {
log.debug("Request with no-store is not serveable from cache");
LOG.debug("Request with no-store is not serveable from cache");
return false;
}
if (HeaderConstants.CACHE_CONTROL_NO_CACHE.equalsIgnoreCase(cacheControlElement.getName())) {
log.debug("Request with no-cache is not serveable from cache");
LOG.debug("Request with no-cache is not serveable from cache");
return false;
}
}
log.debug("Request is serveable from cache");
LOG.debug("Request is serveable from cache");
return true;
}

View File

@ -48,7 +48,7 @@ import org.slf4j.LoggerFactory;
*/
class CachedResponseSuitabilityChecker {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(CachedResponseSuitabilityChecker.class);
private final boolean sharedCache;
private final boolean useHeuristicCaching;
@ -143,32 +143,32 @@ class CachedResponseSuitabilityChecker {
*/
public boolean canCachedResponseBeUsed(final HttpHost host, final HttpRequest request, final HttpCacheEntry entry, final Date now) {
if (!isFreshEnough(entry, request, now)) {
log.debug("Cache entry is not fresh enough");
LOG.debug("Cache entry is not fresh enough");
return false;
}
if (isGet(request) && !validityStrategy.contentLengthHeaderMatchesActualLength(entry)) {
log.debug("Cache entry Content-Length and header information do not match");
LOG.debug("Cache entry Content-Length and header information do not match");
return false;
}
if (hasUnsupportedConditionalHeaders(request)) {
log.debug("Request contains unsupported conditional headers");
LOG.debug("Request contains unsupported conditional headers");
return false;
}
if (!isConditional(request) && entry.getStatus() == HttpStatus.SC_NOT_MODIFIED) {
log.debug("Unconditional request and non-modified cached response");
LOG.debug("Unconditional request and non-modified cached response");
return false;
}
if (isConditional(request) && !allConditionalsMatch(request, entry, now)) {
log.debug("Conditional request and with mismatched conditions");
LOG.debug("Conditional request and with mismatched conditions");
return false;
}
if (hasUnsupportedCacheEntryForGet(request, entry)) {
log.debug("HEAD response caching enabled but the cache entry does not contain a " +
LOG.debug("HEAD response caching enabled but the cache entry does not contain a " +
"request method, entity or a 204 response");
return false;
}
@ -176,12 +176,12 @@ class CachedResponseSuitabilityChecker {
while (it.hasNext()) {
final HeaderElement elt = it.next();
if (HeaderConstants.CACHE_CONTROL_NO_CACHE.equals(elt.getName())) {
log.debug("Response contained NO CACHE directive, cache was not suitable");
LOG.debug("Response contained NO CACHE directive, cache was not suitable");
return false;
}
if (HeaderConstants.CACHE_CONTROL_NO_STORE.equals(elt.getName())) {
log.debug("Response contained NO STORE directive, cache was not suitable");
LOG.debug("Response contained NO STORE directive, cache was not suitable");
return false;
}
@ -190,12 +190,12 @@ class CachedResponseSuitabilityChecker {
// in seconds
final int maxAge = Integer.parseInt(elt.getValue());
if (validityStrategy.getCurrentAge(entry, now).toSeconds() > maxAge) {
log.debug("Response from cache was not suitable due to max age");
LOG.debug("Response from cache was not suitable due to max age");
return false;
}
} catch (final NumberFormatException ex) {
// err conservatively
log.debug("Response from cache was malformed: {}", ex.getMessage());
LOG.debug("Response from cache was malformed: {}", ex.getMessage());
return false;
}
}
@ -205,12 +205,12 @@ class CachedResponseSuitabilityChecker {
// in seconds
final int maxStale = Integer.parseInt(elt.getValue());
if (validityStrategy.getFreshnessLifetime(entry).toSeconds() > maxStale) {
log.debug("Response from cache was not suitable due to max stale freshness");
LOG.debug("Response from cache was not suitable due to max stale freshness");
return false;
}
} catch (final NumberFormatException ex) {
// err conservatively
log.debug("Response from cache was malformed: {}", ex.getMessage());
LOG.debug("Response from cache was malformed: {}", ex.getMessage());
return false;
}
}
@ -225,19 +225,19 @@ class CachedResponseSuitabilityChecker {
final TimeValue age = validityStrategy.getCurrentAge(entry, now);
final TimeValue freshness = validityStrategy.getFreshnessLifetime(entry);
if (freshness.toSeconds() - age.toSeconds() < minFresh) {
log.debug("Response from cache was not suitable due to min fresh " +
LOG.debug("Response from cache was not suitable due to min fresh " +
"freshness requirement");
return false;
}
} catch (final NumberFormatException ex) {
// err conservatively
log.debug("Response from cache was malformed: {}", ex.getMessage());
LOG.debug("Response from cache was malformed: {}", ex.getMessage());
return false;
}
}
}
log.debug("Response from cache was suitable");
LOG.debug("Response from cache was suitable");
return true;
}

View File

@ -104,7 +104,7 @@ class CachingExec extends CachingExecBase implements ExecChainHandler {
private final DefaultCacheRevalidator cacheRevalidator;
private final ConditionalRequestBuilder<ClassicHttpRequest> conditionalRequestBuilder;
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(CachingExec.class);
CachingExec(final HttpCache cache, final DefaultCacheRevalidator cacheRevalidator, final CacheConfig config) {
super(config);
@ -186,14 +186,14 @@ class CachingExec extends CachingExecBase implements ExecChainHandler {
request.addHeader("Via",via);
if (!cacheableRequestPolicy.isServableFromCache(request)) {
log.debug("Request is not servable from cache");
LOG.debug("Request is not servable from cache");
responseCache.flushCacheEntriesInvalidatedByRequest(target, request);
return callBackend(target, request, scope, chain);
}
final HttpCacheEntry entry = responseCache.getCacheEntry(target, request);
if (entry == null) {
log.debug("Cache miss");
LOG.debug("Cache miss");
return handleCacheMiss(target, request, scope, chain);
} else {
return handleCacheHit(target, request, scope, chain, entry);
@ -229,7 +229,7 @@ class CachingExec extends CachingExecBase implements ExecChainHandler {
final Date requestDate = getCurrentDate();
log.debug("Calling the backend");
LOG.debug("Calling the backend");
final ClassicHttpResponse backendResponse = chain.proceed(request, scope);
try {
backendResponse.addHeader("Via", generateViaHeader(backendResponse));
@ -251,7 +251,7 @@ class CachingExec extends CachingExecBase implements ExecChainHandler {
recordCacheHit(target, request);
final Date now = getCurrentDate();
if (suitabilityChecker.canCachedResponseBeUsed(target, request, entry, now)) {
log.debug("Cache hit");
LOG.debug("Cache hit");
try {
return convert(generateCachedResponse(request, context, entry, now), scope);
} catch (final ResourceIOException ex) {
@ -263,15 +263,15 @@ class CachingExec extends CachingExecBase implements ExecChainHandler {
return chain.proceed(request, scope);
}
} else if (!mayCallBackend(request)) {
log.debug("Cache entry not suitable but only-if-cached requested");
LOG.debug("Cache entry not suitable but only-if-cached requested");
return convert(generateGatewayTimeout(context), scope);
} else if (!(entry.getStatus() == HttpStatus.SC_NOT_MODIFIED && !suitabilityChecker.isConditional(request))) {
log.debug("Revalidating cache entry");
LOG.debug("Revalidating cache entry");
try {
if (cacheRevalidator != null
&& !staleResponseNotAllowed(request, entry, now)
&& validityPolicy.mayReturnStaleWhileRevalidating(entry, now)) {
log.debug("Serving stale with asynchronous revalidation");
LOG.debug("Serving stale with asynchronous revalidation");
final String exchangeId = ExecSupport.getNextExchangeId();
final ExecChain.Scope fork = new ExecChain.Scope(
exchangeId,
@ -297,7 +297,7 @@ class CachingExec extends CachingExecBase implements ExecChainHandler {
return convert(handleRevalidationFailure(request, context, entry, now), scope);
}
} else {
log.debug("Cache entry not usable; calling backend");
LOG.debug("Cache entry not usable; calling backend");
return callBackend(target, request, scope, chain);
}
}
@ -376,7 +376,7 @@ class CachingExec extends CachingExecBase implements ExecChainHandler {
storeRequestIfModifiedSinceFor304Response(request, backendResponse);
return cacheAndReturnResponse(target, request, backendResponse, scope, requestDate, responseDate);
}
log.debug("Backend response is not cacheable");
LOG.debug("Backend response is not cacheable");
responseCache.flushCacheEntriesFor(target, request);
return backendResponse;
}
@ -388,7 +388,7 @@ class CachingExec extends CachingExecBase implements ExecChainHandler {
final ExecChain.Scope scope,
final Date requestSent,
final Date responseReceived) throws IOException {
log.debug("Caching backend response");
LOG.debug("Caching backend response");
final ByteArrayBuffer buf;
final HttpEntity entity = backendResponse.getEntity();
if (entity != null) {
@ -401,7 +401,7 @@ class CachingExec extends CachingExecBase implements ExecChainHandler {
buf.append(tmp, 0, l);
total += l;
if (total > cacheConfig.getMaxObjectSize()) {
log.debug("Backend response content length exceeds maximum");
LOG.debug("Backend response content length exceeds maximum");
backendResponse.setEntity(new CombinedEntity(entity, buf));
return backendResponse;
}
@ -415,15 +415,15 @@ class CachingExec extends CachingExecBase implements ExecChainHandler {
if (cacheConfig.isFreshnessCheckEnabled()) {
final HttpCacheEntry existingEntry = responseCache.getCacheEntry(target, request);
if (DateUtils.isAfter(existingEntry, backendResponse, HttpHeaders.DATE)) {
log.debug("Backend already contains fresher cache entry");
LOG.debug("Backend already contains fresher cache entry");
cacheEntry = existingEntry;
} else {
cacheEntry = responseCache.createCacheEntry(target, request, backendResponse, buf, requestSent, responseReceived);
log.debug("Backend response successfully cached");
LOG.debug("Backend response successfully cached");
}
} else {
cacheEntry = responseCache.createCacheEntry(target, request, backendResponse, buf, requestSent, responseReceived);
log.debug("Backend response successfully cached (freshness check skipped)");
LOG.debug("Backend response successfully cached (freshness check skipped)");
}
return convert(responseGenerator.generateResponse(request, cacheEntry), scope);
}
@ -468,7 +468,7 @@ class CachingExec extends CachingExecBase implements ExecChainHandler {
final Header resultEtagHeader = backendResponse.getFirstHeader(HeaderConstants.ETAG);
if (resultEtagHeader == null) {
log.warn("304 response did not contain ETag");
LOG.warn("304 response did not contain ETag");
EntityUtils.consume(backendResponse.getEntity());
backendResponse.close();
return callBackend(target, request, scope, chain);
@ -477,7 +477,7 @@ class CachingExec extends CachingExecBase implements ExecChainHandler {
final String resultEtag = resultEtagHeader.getValue();
final Variant matchingVariant = variants.get(resultEtag);
if (matchingVariant == null) {
log.debug("304 response did not contain ETag matching one sent in If-None-Match");
LOG.debug("304 response did not contain ETag matching one sent in If-None-Match");
EntityUtils.consume(backendResponse.getEntity());
backendResponse.close();
return callBackend(target, request, scope, chain);

View File

@ -78,7 +78,7 @@ public class CachingExecBase {
final RequestProtocolCompliance requestCompliance;
final CacheConfig cacheConfig;
final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(CachingExecBase.class);
CachingExecBase(
final CacheValidityPolicy validityPolicy,
@ -153,22 +153,22 @@ public class CachingExecBase {
void recordCacheMiss(final HttpHost target, final HttpRequest request) {
cacheMisses.getAndIncrement();
if (log.isDebugEnabled()) {
log.debug("Cache miss [host: {}; uri: {}]", target, request.getRequestUri());
if (LOG.isDebugEnabled()) {
LOG.debug("Cache miss [host: {}; uri: {}]", target, request.getRequestUri());
}
}
void recordCacheHit(final HttpHost target, final HttpRequest request) {
cacheHits.getAndIncrement();
if (log.isDebugEnabled()) {
log.debug("Cache hit [host: {}; uri: {}]", target, request.getRequestUri());
if (LOG.isDebugEnabled()) {
LOG.debug("Cache hit [host: {}; uri: {}]", target, request.getRequestUri());
}
}
void recordCacheFailure(final HttpHost target, final HttpRequest request) {
cacheMisses.getAndIncrement();
if (log.isDebugEnabled()) {
log.debug("Cache failure [host: {}; uri: {}]", target, request.getRequestUri());
if (LOG.isDebugEnabled()) {
LOG.debug("Cache failure [host: {}; uri: {}]", target, request.getRequestUri());
}
}
@ -235,7 +235,7 @@ public class CachingExecBase {
while (it.hasNext()) {
final HeaderElement elt = it.next();
if ("only-if-cached".equals(elt.getName())) {
log.debug("Request marked only-if-cached");
LOG.debug("Request marked only-if-cached");
return false;
}
}

View File

@ -62,26 +62,26 @@ public class DefaultAsyncCacheInvalidator extends CacheInvalidatorBase implement
public static final DefaultAsyncCacheInvalidator INSTANCE = new DefaultAsyncCacheInvalidator();
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(DefaultAsyncCacheInvalidator.class);
private void removeEntry(final HttpAsyncCacheStorage storage, final String cacheKey) {
storage.removeEntry(cacheKey, new FutureCallback<Boolean>() {
@Override
public void completed(final Boolean result) {
if (log.isDebugEnabled()) {
if (LOG.isDebugEnabled()) {
if (result) {
log.debug("Cache entry with key {} successfully flushed", cacheKey);
LOG.debug("Cache entry with key {} successfully flushed", cacheKey);
} else {
log.debug("Cache entry with key {} could not be flushed", cacheKey);
LOG.debug("Cache entry with key {} could not be flushed", cacheKey);
}
}
}
@Override
public void failed(final Exception ex) {
if (log.isWarnEnabled()) {
log.warn("Unable to flush cache entry with key {}", cacheKey, ex);
if (LOG.isWarnEnabled()) {
LOG.warn("Unable to flush cache entry with key {}", cacheKey, ex);
}
}
@ -108,8 +108,8 @@ public class DefaultAsyncCacheInvalidator extends CacheInvalidatorBase implement
public void completed(final HttpCacheEntry parentEntry) {
if (requestShouldNotBeCached(request) || shouldInvalidateHeadCacheEntry(request, parentEntry)) {
if (parentEntry != null) {
if (log.isDebugEnabled()) {
log.debug("Invalidating parentEntry cache entry with key {}", cacheKey);
if (LOG.isDebugEnabled()) {
LOG.debug("Invalidating parentEntry cache entry with key {}", cacheKey);
}
for (final String variantURI : parentEntry.getVariantMap().values()) {
removeEntry(storage, variantURI);
@ -117,8 +117,8 @@ public class DefaultAsyncCacheInvalidator extends CacheInvalidatorBase implement
removeEntry(storage, cacheKey);
}
if (uri != null) {
if (log.isWarnEnabled()) {
log.warn("{} is not a valid URI", s);
if (LOG.isWarnEnabled()) {
LOG.warn("{} is not a valid URI", s);
}
final Header clHdr = request.getFirstHeader("Content-Location");
if (clHdr != null) {

View File

@ -42,6 +42,8 @@ import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.nio.AsyncDataConsumer;
import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class used for asynchronous revalidations to be used when the {@code stale-while-revalidate}
@ -49,6 +51,8 @@ import org.apache.hc.core5.util.Timeout;
*/
class DefaultAsyncCacheRevalidator extends CacheRevalidatorBase {
private static final Logger LOG = LoggerFactory.getLogger(DefaultAsyncCacheRevalidator.class);
interface RevalidationCall {
void execute(AsyncExecCallback asyncExecCallback);
@ -150,11 +154,11 @@ class DefaultAsyncCacheRevalidator extends CacheRevalidatorBase {
@Override
public void failed(final Exception cause) {
if (cause instanceof IOException) {
log.debug("Asynchronous revalidation failed due to I/O error", cause);
LOG.debug("Asynchronous revalidation failed due to I/O error", cause);
} else if (cause instanceof HttpException) {
log.error("HTTP protocol exception during asynchronous revalidation", cause);
LOG.error("HTTP protocol exception during asynchronous revalidation", cause);
} else {
log.error("Unexpected runtime exception thrown during asynchronous revalidation", cause);
LOG.error("Unexpected runtime exception thrown during asynchronous revalidation", cause);
}
try {
jobFailed(cacheKey);

View File

@ -56,14 +56,14 @@ public class DefaultCacheInvalidator extends CacheInvalidatorBase implements Htt
public static final DefaultCacheInvalidator INSTANCE = new DefaultCacheInvalidator();
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(DefaultCacheInvalidator.class);
private HttpCacheEntry getEntry(final HttpCacheStorage storage, final String cacheKey) {
try {
return storage.getEntry(cacheKey);
} catch (final ResourceIOException ex) {
if (log.isWarnEnabled()) {
log.warn("Unable to get cache entry with key {}", cacheKey, ex);
if (LOG.isWarnEnabled()) {
LOG.warn("Unable to get cache entry with key {}", cacheKey, ex);
}
return null;
}
@ -73,8 +73,8 @@ public class DefaultCacheInvalidator extends CacheInvalidatorBase implements Htt
try {
storage.removeEntry(cacheKey);
} catch (final ResourceIOException ex) {
if (log.isWarnEnabled()) {
log.warn("Unable to flush cache entry with key {}", cacheKey, ex);
if (LOG.isWarnEnabled()) {
LOG.warn("Unable to flush cache entry with key {}", cacheKey, ex);
}
}
}
@ -92,8 +92,8 @@ public class DefaultCacheInvalidator extends CacheInvalidatorBase implements Htt
if (requestShouldNotBeCached(request) || shouldInvalidateHeadCacheEntry(request, parent)) {
if (parent != null) {
if (log.isDebugEnabled()) {
log.debug("Invalidating parent cache entry with key {}", cacheKey);
if (LOG.isDebugEnabled()) {
LOG.debug("Invalidating parent cache entry with key {}", cacheKey);
}
for (final String variantURI : parent.getVariantMap().values()) {
removeEntry(storage, variantURI);
@ -101,8 +101,8 @@ public class DefaultCacheInvalidator extends CacheInvalidatorBase implements Htt
removeEntry(storage, cacheKey);
}
if (uri != null) {
if (log.isWarnEnabled()) {
log.warn("{} is not a valid URI", s);
if (LOG.isWarnEnabled()) {
LOG.warn("{} is not a valid URI", s);
}
final Header clHdr = request.getFirstHeader("Content-Location");
if (clHdr != null) {

View File

@ -33,6 +33,8 @@ import org.apache.hc.client5.http.schedule.SchedulingStrategy;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.HttpException;
import org.apache.hc.core5.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class used for asynchronous revalidations to be used when
@ -40,6 +42,8 @@ import org.apache.hc.core5.http.HttpStatus;
*/
class DefaultCacheRevalidator extends CacheRevalidatorBase {
private static final Logger LOG = LoggerFactory.getLogger(DefaultCacheRevalidator.class);
interface RevalidationCall {
ClassicHttpResponse execute() throws IOException, HttpException;
@ -83,13 +87,13 @@ class DefaultCacheRevalidator extends CacheRevalidatorBase {
}
} catch (final IOException ex) {
jobFailed(cacheKey);
log.debug("Asynchronous revalidation failed due to I/O error", ex);
LOG.debug("Asynchronous revalidation failed due to I/O error", ex);
} catch (final HttpException ex) {
jobFailed(cacheKey);
log.error("HTTP protocol exception during asynchronous revalidation", ex);
LOG.error("HTTP protocol exception during asynchronous revalidation", ex);
} catch (final RuntimeException ex) {
jobFailed(cacheKey);
log.error("Unexpected runtime exception thrown during asynchronous revalidation", ex);
LOG.error("Unexpected runtime exception thrown during asynchronous revalidation", ex);
}
}

View File

@ -60,7 +60,7 @@ class ResponseCachingPolicy {
HttpStatus.SC_MOVED_PERMANENTLY,
HttpStatus.SC_GONE));
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(ResponseCachingPolicy.class);
private final long maxObjectSizeBytes;
private final boolean sharedCache;
@ -103,8 +103,8 @@ class ResponseCachingPolicy {
boolean cacheable = false;
if (!HeaderConstants.GET_METHOD.equals(httpMethod) && !HeaderConstants.HEAD_METHOD.equals(httpMethod)) {
if (log.isDebugEnabled()) {
log.debug("{} method response is not cacheable", httpMethod);
if (LOG.isDebugEnabled()) {
LOG.debug("{} method response is not cacheable", httpMethod);
}
return false;
}
@ -114,15 +114,15 @@ class ResponseCachingPolicy {
// these response codes MAY be cached
cacheable = true;
} else if (uncacheableStatusCodes.contains(status)) {
if (log.isDebugEnabled()) {
log.debug("{} response is not cacheable", status);
if (LOG.isDebugEnabled()) {
LOG.debug("{} response is not cacheable", status);
}
return false;
} else if (unknownStatusCode(status)) {
// a response with an unknown status code MUST NOT be
// cached
if (log.isDebugEnabled()) {
log.debug("{} response is unknown", status);
if (LOG.isDebugEnabled()) {
LOG.debug("{} response is unknown", status);
}
return false;
}
@ -131,31 +131,31 @@ class ResponseCachingPolicy {
if (contentLength != null) {
final long contentLengthValue = Long.parseLong(contentLength.getValue());
if (contentLengthValue > this.maxObjectSizeBytes) {
if (log.isDebugEnabled()) {
log.debug("Response content length exceeds {}", this.maxObjectSizeBytes);
if (LOG.isDebugEnabled()) {
LOG.debug("Response content length exceeds {}", this.maxObjectSizeBytes);
}
return false;
}
}
if (response.countHeaders(HeaderConstants.AGE) > 1) {
log.debug("Multiple Age headers");
LOG.debug("Multiple Age headers");
return false;
}
if (response.countHeaders(HeaderConstants.EXPIRES) > 1) {
log.debug("Multiple Expires headers");
LOG.debug("Multiple Expires headers");
return false;
}
if (response.countHeaders(HttpHeaders.DATE) > 1) {
log.debug("Multiple Date headers");
LOG.debug("Multiple Date headers");
return false;
}
final Date date = DateUtils.parseDate(response, HttpHeaders.DATE);
if (date == null) {
log.debug("Invalid / missing Date header");
LOG.debug("Invalid / missing Date header");
return false;
}
@ -163,15 +163,15 @@ class ResponseCachingPolicy {
while (it.hasNext()) {
final HeaderElement elem = it.next();
if ("*".equals(elem.getName())) {
if (log.isDebugEnabled()) {
log.debug("Vary * found");
if (LOG.isDebugEnabled()) {
LOG.debug("Vary * found");
}
return false;
}
}
if (isExplicitlyNonCacheable(response)) {
log.debug("Response is explicitly non-cacheable");
LOG.debug("Response is explicitly non-cacheable");
return false;
}
@ -246,37 +246,37 @@ class ResponseCachingPolicy {
public boolean isResponseCacheable(final HttpRequest request, final HttpResponse response) {
final ProtocolVersion version = request.getVersion() != null ? request.getVersion() : HttpVersion.DEFAULT;
if (version.compareToVersion(HttpVersion.HTTP_1_1) > 0) {
if (log.isDebugEnabled()) {
log.debug("Protocol version {} is non-cacheable", version);
if (LOG.isDebugEnabled()) {
LOG.debug("Protocol version {} is non-cacheable", version);
}
return false;
}
final String[] uncacheableRequestDirectives = { HeaderConstants.CACHE_CONTROL_NO_STORE };
if (hasCacheControlParameterFrom(request,uncacheableRequestDirectives)) {
log.debug("Response is explcitily non-cacheable per cache control directive");
LOG.debug("Response is explcitily non-cacheable per cache control directive");
return false;
}
if (request.getRequestUri().contains("?")) {
if (neverCache1_0ResponsesWithQueryString && from1_0Origin(response)) {
log.debug("Response is not cacheable as it had a query string");
LOG.debug("Response is not cacheable as it had a query string");
return false;
} else if (!isExplicitlyCacheable(response)) {
log.debug("Response is not cacheable as it is missing explicit caching headers");
LOG.debug("Response is not cacheable as it is missing explicit caching headers");
return false;
}
}
if (expiresHeaderLessOrEqualToDateHeaderAndNoCacheControl(response)) {
log.debug("Expires header less or equal to Date header and no cache control directives");
LOG.debug("Expires header less or equal to Date header and no cache control directives");
return false;
}
if (sharedCache) {
if (request.countHeaders(HeaderConstants.AUTHORIZATION) > 0
&& !hasCacheControlParameterFrom(response, AUTH_CACHEABLE_PARAMS)) {
log.debug("Request contains private credentials");
LOG.debug("Request contains private credentials");
return false;
}
}

View File

@ -46,7 +46,7 @@ public final class SHA256KeyHashingScheme implements KeyHashingScheme {
public static final SHA256KeyHashingScheme INSTANCE = new SHA256KeyHashingScheme();
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(SHA256KeyHashingScheme.class);
@Override
public String hash(final String key) {
@ -59,7 +59,7 @@ public final class SHA256KeyHashingScheme implements KeyHashingScheme {
try {
return MessageDigest.getInstance("SHA-256");
} catch (final NoSuchAlgorithmException nsae) {
log.error("can't find SHA-256 implementation for cache key hashing");
LOG.error("can't find SHA-256 implementation for cache key hashing");
throw new MemcachedKeyHashingException(nsae);
}
}

View File

@ -72,7 +72,7 @@ import com.sun.jna.ptr.IntByReference;
@Experimental
public class WindowsNegotiateScheme implements AuthScheme {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(WindowsNegotiateScheme.class);
// NTLM or Negotiate
private final String schemeName;
@ -91,8 +91,8 @@ public class WindowsNegotiateScheme implements AuthScheme {
this.continueNeeded = true;
this.servicePrincipalName = servicePrincipalName;
if (this.log.isDebugEnabled()) {
this.log.debug("Created WindowsNegotiateScheme using {}", this.schemeName);
if (LOG.isDebugEnabled()) {
LOG.debug("Created WindowsNegotiateScheme using {}", this.schemeName);
}
}
@ -257,8 +257,8 @@ public class WindowsNegotiateScheme implements AuthScheme {
}
}
}
if (this.log.isDebugEnabled()) {
this.log.debug("Using SPN: {}", spn);
if (LOG.isDebugEnabled()) {
LOG.debug("Using SPN: {}", spn);
}
return spn;
}

View File

@ -34,7 +34,7 @@ public class IgnoreCompleteExceptonFutureCallback<T> implements FutureCallback<T
private final FutureCallback<T> callback;
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(IgnoreCompleteExceptonFutureCallback.class);
public IgnoreCompleteExceptonFutureCallback(final FutureCallback<T> callback) {
super();
@ -47,7 +47,7 @@ public class IgnoreCompleteExceptonFutureCallback<T> implements FutureCallback<T
try {
callback.completed(result);
} catch (final Exception ex) {
log.error(ex.getMessage(), ex);
LOG.error(ex.getMessage(), ex);
}
}
}

View File

@ -59,7 +59,7 @@ import org.slf4j.LoggerFactory;
@Contract(threading = ThreadingBehavior.STATELESS)
public class DefaultAuthenticationStrategy implements AuthenticationStrategy {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(DefaultAuthenticationStrategy.class);
public static final DefaultAuthenticationStrategy INSTANCE = new DefaultAuthenticationStrategy();
@ -84,7 +84,7 @@ public class DefaultAuthenticationStrategy implements AuthenticationStrategy {
final List<AuthScheme> options = new ArrayList<>();
final Lookup<AuthSchemeFactory> registry = clientContext.getAuthSchemeRegistry();
if (registry == null) {
this.log.debug("Auth scheme registry not set in the context");
LOG.debug("Auth scheme registry not set in the context");
return options;
}
final RequestConfig config = clientContext.getRequestConfig();
@ -93,8 +93,8 @@ public class DefaultAuthenticationStrategy implements AuthenticationStrategy {
if (authPrefs == null) {
authPrefs = DEFAULT_SCHEME_PRIORITY;
}
if (this.log.isDebugEnabled()) {
this.log.debug("Authentication schemes in the order of preference: {}", authPrefs);
if (LOG.isDebugEnabled()) {
LOG.debug("Authentication schemes in the order of preference: {}", authPrefs);
}
for (final String schemeName: authPrefs) {
@ -102,8 +102,8 @@ public class DefaultAuthenticationStrategy implements AuthenticationStrategy {
if (challenge != null) {
final AuthSchemeFactory authSchemeFactory = registry.lookup(schemeName);
if (authSchemeFactory == null) {
if (this.log.isWarnEnabled()) {
this.log.warn("Authentication scheme {} not supported", schemeName);
if (LOG.isWarnEnabled()) {
LOG.warn("Authentication scheme {} not supported", schemeName);
// Try again
}
continue;
@ -111,8 +111,8 @@ public class DefaultAuthenticationStrategy implements AuthenticationStrategy {
final AuthScheme authScheme = authSchemeFactory.create(context);
options.add(authScheme);
} else {
if (this.log.isDebugEnabled()) {
this.log.debug("Challenge for {} authentication scheme not available", schemeName);
if (LOG.isDebugEnabled()) {
LOG.debug("Challenge for {} authentication scheme not available", schemeName);
}
}
}

View File

@ -48,7 +48,7 @@ import org.slf4j.LoggerFactory;
public class InMemoryDnsResolver implements DnsResolver {
/** Logger associated to this class. */
private final Logger log = LoggerFactory.getLogger(InMemoryDnsResolver.class);
private static final Logger LOG = LoggerFactory.getLogger(InMemoryDnsResolver.class);
/**
* In-memory collection that will hold the associations between a host name
@ -86,8 +86,8 @@ public class InMemoryDnsResolver implements DnsResolver {
@Override
public InetAddress[] resolve(final String host) throws UnknownHostException {
final InetAddress[] resolvedAddresses = dnsMap.get(host);
if (log.isInfoEnabled()) {
log.info("Resolving {} to {}", host, Arrays.deepToString(resolvedAddresses));
if (LOG.isInfoEnabled()) {
LOG.info("Resolving {} to {}", host, Arrays.deepToString(resolvedAddresses));
}
if(resolvedAddresses == null){
throw new UnknownHostException(host + " cannot be resolved");

View File

@ -89,7 +89,7 @@ public class Wire {
buffer.append("[\\n]\"");
buffer.insert(0, "\"");
buffer.insert(0, header);
this.log.debug("{} {}", this.id, buffer);
log.debug("{} {}", this.id, buffer);
buffer.setLength(0);
} else if ((ch < 32) || (ch >= 127)) {
buffer.append("[0x");
@ -103,13 +103,13 @@ public class Wire {
buffer.append('\"');
buffer.insert(0, '\"');
buffer.insert(0, header);
this.log.debug("{} {}", this.id, buffer);
log.debug("{} {}", this.id, buffer);
}
}
public boolean isEnabled() {
return this.log.isDebugEnabled();
return log.isDebugEnabled();
}
public void output(final byte[] b, final int pos, final int off) {

View File

@ -45,7 +45,7 @@ abstract class AbstractHttpAsyncClientBase extends CloseableHttpAsyncClient {
enum Status { READY, RUNNING, TERMINATED }
final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(AbstractHttpAsyncClientBase.class);
private final AsyncPushConsumerRegistry pushConsumerRegistry;
private final DefaultConnectingIOReactor ioReactor;
@ -101,8 +101,8 @@ abstract class AbstractHttpAsyncClientBase extends CloseableHttpAsyncClient {
@Override
public final void initiateShutdown() {
if (log.isDebugEnabled()) {
log.debug("Initiating shutdown");
if (LOG.isDebugEnabled()) {
LOG.debug("Initiating shutdown");
}
ioReactor.initiateShutdown();
}
@ -112,8 +112,8 @@ abstract class AbstractHttpAsyncClientBase extends CloseableHttpAsyncClient {
@Override
public final void close(final CloseMode closeMode) {
if (log.isDebugEnabled()) {
log.debug("Shutdown {}", closeMode);
if (LOG.isDebugEnabled()) {
LOG.debug("Shutdown {}", closeMode);
}
ioReactor.initiateShutdown();
ioReactor.close(closeMode);

View File

@ -78,7 +78,7 @@ import org.slf4j.LoggerFactory;
@Internal
public final class AsyncConnectExec implements AsyncExecChainHandler {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(AsyncConnectExec.class);
private final HttpProcessor proxyHttpProcessor;
private final AuthenticationStrategy proxyAuthStrategy;
@ -92,7 +92,7 @@ public final class AsyncConnectExec implements AsyncExecChainHandler {
Args.notNull(proxyAuthStrategy, "Proxy authentication strategy");
this.proxyHttpProcessor = proxyHttpProcessor;
this.proxyAuthStrategy = proxyAuthStrategy;
this.authenticator = new HttpAuthenticator(log);
this.authenticator = new HttpAuthenticator(LOG);
this.routeDirector = new BasicRouteDirector();
}
@ -128,8 +128,8 @@ public final class AsyncConnectExec implements AsyncExecChainHandler {
if (!execRuntime.isEndpointAcquired()) {
final Object userToken = clientContext.getUserToken();
if (log.isDebugEnabled()) {
log.debug("{}: acquiring connection with route {}", exchangeId, route);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: acquiring connection with route {}", exchangeId, route);
}
cancellableDependency.setDependency(execRuntime.acquireEndpoint(
exchangeId, route, userToken, clientContext, new FutureCallback<AsyncExecRuntime>() {
@ -197,8 +197,8 @@ public final class AsyncConnectExec implements AsyncExecChainHandler {
@Override
public void completed(final AsyncExecRuntime execRuntime) {
tracker.connectTarget(route.isSecure());
if (log.isDebugEnabled()) {
log.debug("{}: connected to target", exchangeId);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: connected to target", exchangeId);
}
proceedToNextHop(state, request, entityProducer, scope, chain, asyncExecCallback);
}
@ -223,8 +223,8 @@ public final class AsyncConnectExec implements AsyncExecChainHandler {
public void completed(final AsyncExecRuntime execRuntime) {
final HttpHost proxy = route.getProxyHost();
tracker.connectProxy(proxy, route.isSecure() && !route.isTunnelled());
if (log.isDebugEnabled()) {
log.debug("{}: connected to proxy", exchangeId);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: connected to proxy", exchangeId);
}
proceedToNextHop(state, request, entityProducer, scope, chain, asyncExecCallback);
}
@ -263,8 +263,8 @@ public final class AsyncConnectExec implements AsyncExecChainHandler {
@Override
public void completed() {
if (log.isDebugEnabled()) {
log.debug("{}: tunnel to target created", exchangeId);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: tunnel to target created", exchangeId);
}
tracker.tunnelTarget(false);
proceedToNextHop(state, request, entityProducer, scope, chain, asyncExecCallback);
@ -291,8 +291,8 @@ public final class AsyncConnectExec implements AsyncExecChainHandler {
case HttpRouteDirector.LAYER_PROTOCOL:
execRuntime.upgradeTls(clientContext);
if (log.isDebugEnabled()) {
log.debug("{}: upgraded to TLS", exchangeId);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: upgraded to TLS", exchangeId);
}
tracker.layerProtocol(route.isSecure());
break;
@ -303,8 +303,8 @@ public final class AsyncConnectExec implements AsyncExecChainHandler {
return;
case HttpRouteDirector.COMPLETE:
if (log.isDebugEnabled()) {
log.debug("{}: route fully established", exchangeId);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: route fully established", exchangeId);
}
try {
chain.proceed(request, entityProducer, scope, asyncExecCallback);

View File

@ -67,7 +67,7 @@ import org.slf4j.LoggerFactory;
@Internal
public final class AsyncHttpRequestRetryExec implements AsyncExecChainHandler {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(AsyncHttpRequestRetryExec.class);
private final HttpRequestRetryStrategy retryStrategy;
@ -101,8 +101,8 @@ public final class AsyncHttpRequestRetryExec implements AsyncExecChainHandler {
final EntityDetails entityDetails) throws HttpException, IOException {
final HttpClientContext clientContext = scope.clientContext;
if (entityProducer != null && !entityProducer.isRepeatable()) {
if (log.isDebugEnabled()) {
log.debug("{}: cannot retry non-repeatable request", exchangeId);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: cannot retry non-repeatable request", exchangeId);
}
return asyncExecCallback.handleResponse(response, entityDetails);
}
@ -139,15 +139,15 @@ public final class AsyncHttpRequestRetryExec implements AsyncExecChainHandler {
final HttpRoute route = scope.route;
final HttpClientContext clientContext = scope.clientContext;
if (entityProducer != null && !entityProducer.isRepeatable()) {
if (log.isDebugEnabled()) {
log.debug("{}: cannot retry non-repeatable request", exchangeId);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: cannot retry non-repeatable request", exchangeId);
}
} else if (retryStrategy.retryRequest(request, (IOException) cause, state.execCount, clientContext)) {
if (log.isDebugEnabled()) {
log.debug("{}: {}", exchangeId, cause.getMessage(), cause);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: {}", exchangeId, cause.getMessage(), cause);
}
if (log.isInfoEnabled()) {
log.info("Recoverable I/O exception ({}) caught when processing request to {}",
if (LOG.isInfoEnabled()) {
LOG.info("Recoverable I/O exception ({}) caught when processing request to {}",
cause.getClass().getName(), route);
}
scope.execRuntime.discardEndpoint();

View File

@ -83,7 +83,7 @@ import org.slf4j.LoggerFactory;
@Internal
public final class AsyncProtocolExec implements AsyncExecChainHandler {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(AsyncProtocolExec.class);
private final HttpProcessor httpProcessor;
private final AuthenticationStrategy targetAuthStrategy;
@ -97,7 +97,7 @@ public final class AsyncProtocolExec implements AsyncExecChainHandler {
this.httpProcessor = Args.notNull(httpProcessor, "HTTP protocol processor");
this.targetAuthStrategy = Args.notNull(targetAuthStrategy, "Target authentication strategy");
this.proxyAuthStrategy = Args.notNull(proxyAuthStrategy, "Proxy authentication strategy");
this.authenticator = new HttpAuthenticator(log);
this.authenticator = new HttpAuthenticator(LOG);
}
@Override
@ -164,14 +164,14 @@ public final class AsyncProtocolExec implements AsyncExecChainHandler {
httpProcessor.process(request, entityProducer, clientContext);
if (!request.containsHeader(HttpHeaders.AUTHORIZATION)) {
if (log.isDebugEnabled()) {
log.debug("{}: target auth state: {}", exchangeId, targetAuthExchange.getState());
if (LOG.isDebugEnabled()) {
LOG.debug("{}: target auth state: {}", exchangeId, targetAuthExchange.getState());
}
authenticator.addAuthResponse(target, ChallengeType.TARGET, request, targetAuthExchange, clientContext);
}
if (!request.containsHeader(HttpHeaders.PROXY_AUTHORIZATION) && !route.isTunnelled()) {
if (log.isDebugEnabled()) {
log.debug("{}: proxy auth state: {}", exchangeId, proxyAuthExchange.getState());
if (LOG.isDebugEnabled()) {
LOG.debug("{}: proxy auth state: {}", exchangeId, proxyAuthExchange.getState());
}
authenticator.addAuthResponse(proxy, ChallengeType.PROXY, request, proxyAuthExchange, clientContext);
}
@ -209,15 +209,15 @@ public final class AsyncProtocolExec implements AsyncExecChainHandler {
if (!execRuntime.isEndpointConnected()) {
if (proxyAuthExchange.getState() == AuthExchange.State.SUCCESS
&& proxyAuthExchange.isConnectionBased()) {
if (log.isDebugEnabled()) {
log.debug("{}: resetting proxy auth state", exchangeId);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: resetting proxy auth state", exchangeId);
}
proxyAuthExchange.reset();
}
if (targetAuthExchange.getState() == AuthExchange.State.SUCCESS
&& targetAuthExchange.isConnectionBased()) {
if (log.isDebugEnabled()) {
log.debug("{}: resetting target auth state", exchangeId);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: resetting target auth state", exchangeId);
}
targetAuthExchange.reset();
}
@ -225,8 +225,8 @@ public final class AsyncProtocolExec implements AsyncExecChainHandler {
if (challenged.get()) {
if (entityProducer != null && !entityProducer.isRepeatable()) {
if (log.isDebugEnabled()) {
log.debug("{}: cannot retry non-repeatable request", exchangeId);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: cannot retry non-repeatable request", exchangeId);
}
asyncExecCallback.completed();
} else {

View File

@ -75,7 +75,7 @@ import org.slf4j.LoggerFactory;
@Internal
public final class AsyncRedirectExec implements AsyncExecChainHandler {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(AsyncRedirectExec.class);
private final HttpRoutePlanner routePlanner;
private final RedirectStrategy redirectStrategy;
@ -126,8 +126,8 @@ public final class AsyncRedirectExec implements AsyncExecChainHandler {
state.redirectCount++;
final URI redirectUri = redirectStrategy.getLocationURI(request, response, clientContext);
if (log.isDebugEnabled()) {
log.debug("{}: redirect requested to location '{}'", exchangeId, redirectUri);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: redirect requested to location '{}'", exchangeId, redirectUri);
}
if (!config.isCircularRedirectsAllowed()) {
if (state.redirectLocations.contains(redirectUri)) {
@ -170,15 +170,15 @@ public final class AsyncRedirectExec implements AsyncExecChainHandler {
if (!LangUtils.equals(currentRoute, newRoute)) {
state.reroute = true;
final AuthExchange targetAuthExchange = clientContext.getAuthExchange(currentRoute.getTargetHost());
if (log.isDebugEnabled()) {
log.debug("{}: resetting target auth state", exchangeId);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: resetting target auth state", exchangeId);
}
targetAuthExchange.reset();
if (currentRoute.getProxyHost() != null) {
final AuthExchange proxyAuthExchange = clientContext.getAuthExchange(currentRoute.getProxyHost());
if (proxyAuthExchange.isConnectionBased()) {
if (log.isDebugEnabled()) {
log.debug("{}: resetting proxy auth state", exchangeId);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: resetting proxy auth state", exchangeId);
}
proxyAuthExchange.reset();
}
@ -189,8 +189,8 @@ public final class AsyncRedirectExec implements AsyncExecChainHandler {
}
}
if (state.redirectURI != null) {
if (log.isDebugEnabled()) {
log.debug("{}: redirecting to '{}' via {}", exchangeId, state.redirectURI, currentRoute);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: redirecting to '{}' via {}", exchangeId, state.redirectURI, currentRoute);
}
return null;
}
@ -210,8 +210,8 @@ public final class AsyncRedirectExec implements AsyncExecChainHandler {
} else {
final AsyncEntityProducer entityProducer = state.currentEntityProducer;
if (entityProducer != null && !entityProducer.isRepeatable()) {
if (log.isDebugEnabled()) {
log.debug("{}: cannot redirect non-repeatable request", exchangeId);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: cannot redirect non-repeatable request", exchangeId);
}
asyncExecCallback.completed();
} else {

View File

@ -51,10 +51,10 @@ import org.slf4j.LoggerFactory;
class H2AsyncClientEventHandlerFactory implements IOEventHandlerFactory {
private final Logger headerLog = LoggerFactory.getLogger("org.apache.hc.client5.http.headers");
private final Logger frameLog = LoggerFactory.getLogger("org.apache.hc.client5.http2.frame");
private final Logger framePayloadLog = LoggerFactory.getLogger("org.apache.hc.client5.http2.frame.payload");
private final Logger flowCtrlLog = LoggerFactory.getLogger("org.apache.hc.client5.http2.flow");
private static final Logger HEADER_LOG = LoggerFactory.getLogger("org.apache.hc.client5.http.headers");
private static final Logger FRAME_LOG = LoggerFactory.getLogger("org.apache.hc.client5.http2.frame");
private static final Logger FRAME_PAYLOAD_LOG = LoggerFactory.getLogger("org.apache.hc.client5.http2.frame.payload");
private static final Logger FLOW_CTRL_LOG = LoggerFactory.getLogger("org.apache.hc.client5.http2.flow");
private final HttpProcessor httpProcessor;
private final HandlerFactory<AsyncPushConsumer> exchangeHandlerFactory;
@ -74,10 +74,10 @@ class H2AsyncClientEventHandlerFactory implements IOEventHandlerFactory {
@Override
public IOEventHandler createHandler(final ProtocolIOSession ioSession, final Object attachment) {
if (headerLog.isDebugEnabled()
|| frameLog.isDebugEnabled()
|| framePayloadLog.isDebugEnabled()
|| flowCtrlLog.isDebugEnabled()) {
if (HEADER_LOG.isDebugEnabled()
|| FRAME_LOG.isDebugEnabled()
|| FRAME_PAYLOAD_LOG.isDebugEnabled()
|| FLOW_CTRL_LOG.isDebugEnabled()) {
final String id = ioSession.getId();
final ClientH2StreamMultiplexerFactory http2StreamHandlerFactory = new ClientH2StreamMultiplexerFactory(
httpProcessor,
@ -90,7 +90,7 @@ class H2AsyncClientEventHandlerFactory implements IOEventHandlerFactory {
private void logFrameInfo(final String prefix, final RawFrame frame) {
try {
final LogAppendable logAppendable = new LogAppendable(frameLog, prefix);
final LogAppendable logAppendable = new LogAppendable(FRAME_LOG, prefix);
framePrinter.printFrameInfo(frame, logAppendable);
logAppendable.flush();
} catch (final IOException ignore) {
@ -99,7 +99,7 @@ class H2AsyncClientEventHandlerFactory implements IOEventHandlerFactory {
private void logFramePayload(final String prefix, final RawFrame frame) {
try {
final LogAppendable logAppendable = new LogAppendable(framePayloadLog, prefix);
final LogAppendable logAppendable = new LogAppendable(FRAME_PAYLOAD_LOG, prefix);
framePrinter.printPayload(frame, logAppendable);
logAppendable.flush();
} catch (final IOException ignore) {
@ -107,61 +107,57 @@ class H2AsyncClientEventHandlerFactory implements IOEventHandlerFactory {
}
private void logFlowControl(final String prefix, final int streamId, final int delta, final int actualSize) {
final StringBuilder buffer = new StringBuilder();
buffer.append(prefix).append(" stream ").append(streamId).append(" flow control " )
.append(delta).append(" -> ")
.append(actualSize);
flowCtrlLog.debug(buffer.toString());
FLOW_CTRL_LOG.debug("{} stream {} flow control {} -> {}", prefix, streamId, delta, actualSize);
}
@Override
public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
if (headerLog.isDebugEnabled()) {
if (HEADER_LOG.isDebugEnabled()) {
for (int i = 0; i < headers.size(); i++) {
headerLog.debug("{} << {}", id, headers.get(i));
HEADER_LOG.debug("{} << {}", id, headers.get(i));
}
}
}
@Override
public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
if (headerLog.isDebugEnabled()) {
if (HEADER_LOG.isDebugEnabled()) {
for (int i = 0; i < headers.size(); i++) {
headerLog.debug("{} >> {}", id, headers.get(i));
HEADER_LOG.debug("{} >> {}", id, headers.get(i));
}
}
}
@Override
public void onFrameInput(final HttpConnection connection, final int streamId, final RawFrame frame) {
if (frameLog.isDebugEnabled()) {
if (FRAME_LOG.isDebugEnabled()) {
logFrameInfo(id + " <<", frame);
}
if (framePayloadLog.isDebugEnabled()) {
if (FRAME_PAYLOAD_LOG.isDebugEnabled()) {
logFramePayload(id + " <<", frame);
}
}
@Override
public void onFrameOutput(final HttpConnection connection, final int streamId, final RawFrame frame) {
if (frameLog.isDebugEnabled()) {
if (FRAME_LOG.isDebugEnabled()) {
logFrameInfo(id + " >>", frame);
}
if (framePayloadLog.isDebugEnabled()) {
if (FRAME_PAYLOAD_LOG.isDebugEnabled()) {
logFramePayload(id + " >>", frame);
}
}
@Override
public void onInputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
if (flowCtrlLog.isDebugEnabled()) {
if (FLOW_CTRL_LOG.isDebugEnabled()) {
logFlowControl(id + " <<", streamId, delta, actualSize);
}
}
@Override
public void onOutputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
if (flowCtrlLog.isDebugEnabled()) {
if (FLOW_CTRL_LOG.isDebugEnabled()) {
logFlowControl(id + " >>", streamId, delta, actualSize);
}
}

View File

@ -68,7 +68,7 @@ import org.slf4j.LoggerFactory;
@Internal
public class H2AsyncMainClientExec implements AsyncExecChainHandler {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(H2AsyncMainClientExec.class);
@Override
public void execute(
@ -82,8 +82,8 @@ public class H2AsyncMainClientExec implements AsyncExecChainHandler {
final HttpClientContext clientContext = scope.clientContext;
final AsyncExecRuntime execRuntime = scope.execRuntime;
if (log.isDebugEnabled()) {
log.debug("{}: executing {}", exchangeId, new RequestLine(request));
if (LOG.isDebugEnabled()) {
LOG.debug("{}: executing {}", exchangeId, new RequestLine(request));
}
final AsyncClientExchangeHandler internalExchangeHandler = new AsyncClientExchangeHandler() {
@ -175,10 +175,10 @@ public class H2AsyncMainClientExec implements AsyncExecChainHandler {
};
if (log.isDebugEnabled()) {
if (LOG.isDebugEnabled()) {
operation.setDependency(execRuntime.execute(
exchangeId,
new LoggingAsyncClientExchangeHandler(log, exchangeId, internalExchangeHandler),
new LoggingAsyncClientExchangeHandler(LOG, exchangeId, internalExchangeHandler),
clientContext));
} else {
operation.setDependency(execRuntime.execute(exchangeId, internalExchangeHandler, clientContext));

View File

@ -66,11 +66,11 @@ import org.slf4j.LoggerFactory;
class HttpAsyncClientEventHandlerFactory implements IOEventHandlerFactory {
private final Logger streamLog = LoggerFactory.getLogger(InternalHttpAsyncClient.class);
private final Logger headerLog = LoggerFactory.getLogger("org.apache.hc.client5.http.headers");
private final Logger frameLog = LoggerFactory.getLogger("org.apache.hc.client5.http2.frame");
private final Logger framePayloadLog = LoggerFactory.getLogger("org.apache.hc.client5.http2.frame.payload");
private final Logger flowCtrlLog = LoggerFactory.getLogger("org.apache.hc.client5.http2.flow");
private static final Logger STREAM_LOG = LoggerFactory.getLogger(InternalHttpAsyncClient.class);
private static final Logger HEADER_LOG = LoggerFactory.getLogger("org.apache.hc.client5.http.headers");
private static final Logger FRAME_LOG = LoggerFactory.getLogger("org.apache.hc.client5.http2.frame");
private static final Logger FRAME_PAYLOAD_LOG = LoggerFactory.getLogger("org.apache.hc.client5.http2.frame.payload");
private static final Logger FLOW_CTRL_LOG = LoggerFactory.getLogger("org.apache.hc.client5.http2.flow");
private final HttpProcessor httpProcessor;
private final HandlerFactory<AsyncPushConsumer> exchangeHandlerFactory;
@ -103,11 +103,11 @@ class HttpAsyncClientEventHandlerFactory implements IOEventHandlerFactory {
@Override
public IOEventHandler createHandler(final ProtocolIOSession ioSession, final Object attachment) {
if (streamLog.isDebugEnabled()
|| headerLog.isDebugEnabled()
|| frameLog.isDebugEnabled()
|| framePayloadLog.isDebugEnabled()
|| flowCtrlLog.isDebugEnabled()) {
if (STREAM_LOG.isDebugEnabled()
|| HEADER_LOG.isDebugEnabled()
|| FRAME_LOG.isDebugEnabled()
|| FRAME_PAYLOAD_LOG.isDebugEnabled()
|| FLOW_CTRL_LOG.isDebugEnabled()) {
final String id = ioSession.getId();
final ClientHttp1StreamDuplexerFactory http1StreamHandlerFactory = new ClientHttp1StreamDuplexerFactory(
httpProcessor,
@ -120,31 +120,31 @@ class HttpAsyncClientEventHandlerFactory implements IOEventHandlerFactory {
@Override
public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
if (headerLog.isDebugEnabled()) {
headerLog.debug("{} >> {}", id, new RequestLine(request));
if (HEADER_LOG.isDebugEnabled()) {
HEADER_LOG.debug("{} >> {}", id, new RequestLine(request));
for (final Iterator<Header> it = request.headerIterator(); it.hasNext(); ) {
headerLog.debug("{} >> {}", id, it.next());
HEADER_LOG.debug("{} >> {}", id, it.next());
}
}
}
@Override
public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
if (headerLog.isDebugEnabled()) {
headerLog.debug("{} << {}", id, new StatusLine(response));
if (HEADER_LOG.isDebugEnabled()) {
HEADER_LOG.debug("{} << {}", id, new StatusLine(response));
for (final Iterator<Header> it = response.headerIterator(); it.hasNext(); ) {
headerLog.debug("{} << {}", id, it.next());
HEADER_LOG.debug("{} << {}", id, it.next());
}
}
}
@Override
public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
if (streamLog.isDebugEnabled()) {
if (STREAM_LOG.isDebugEnabled()) {
if (keepAlive) {
streamLog.debug("{} Connection is kept alive", id);
STREAM_LOG.debug("{} Connection is kept alive", id);
} else {
streamLog.debug("{} Connection is not kept alive", id);
STREAM_LOG.debug("{} Connection is not kept alive", id);
}
}
}
@ -161,7 +161,7 @@ class HttpAsyncClientEventHandlerFactory implements IOEventHandlerFactory {
private void logFrameInfo(final String prefix, final RawFrame frame) {
try {
final LogAppendable logAppendable = new LogAppendable(frameLog, prefix);
final LogAppendable logAppendable = new LogAppendable(FRAME_LOG, prefix);
framePrinter.printFrameInfo(frame, logAppendable);
logAppendable.flush();
} catch (final IOException ignore) {
@ -170,7 +170,7 @@ class HttpAsyncClientEventHandlerFactory implements IOEventHandlerFactory {
private void logFramePayload(final String prefix, final RawFrame frame) {
try {
final LogAppendable logAppendable = new LogAppendable(framePayloadLog, prefix);
final LogAppendable logAppendable = new LogAppendable(FRAME_PAYLOAD_LOG, prefix);
framePrinter.printPayload(frame, logAppendable);
logAppendable.flush();
} catch (final IOException ignore) {
@ -178,61 +178,57 @@ class HttpAsyncClientEventHandlerFactory implements IOEventHandlerFactory {
}
private void logFlowControl(final String prefix, final int streamId, final int delta, final int actualSize) {
final StringBuilder buffer = new StringBuilder();
buffer.append(prefix).append(" stream ").append(streamId).append(" flow control " )
.append(delta).append(" -> ")
.append(actualSize);
flowCtrlLog.debug(buffer.toString());
FLOW_CTRL_LOG.debug("{} stream {} flow control {} -> {}", prefix, streamId, delta, actualSize);
}
@Override
public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
if (headerLog.isDebugEnabled()) {
if (HEADER_LOG.isDebugEnabled()) {
for (int i = 0; i < headers.size(); i++) {
headerLog.debug("{} << {}", id, headers.get(i));
HEADER_LOG.debug("{} << {}", id, headers.get(i));
}
}
}
@Override
public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
if (headerLog.isDebugEnabled()) {
if (HEADER_LOG.isDebugEnabled()) {
for (int i = 0; i < headers.size(); i++) {
headerLog.debug("{} >> {}", id, headers.get(i));
HEADER_LOG.debug("{} >> {}", id, headers.get(i));
}
}
}
@Override
public void onFrameInput(final HttpConnection connection, final int streamId, final RawFrame frame) {
if (frameLog.isDebugEnabled()) {
if (FRAME_LOG.isDebugEnabled()) {
logFrameInfo(id + " <<", frame);
}
if (framePayloadLog.isDebugEnabled()) {
if (FRAME_PAYLOAD_LOG.isDebugEnabled()) {
logFramePayload(id + " <<", frame);
}
}
@Override
public void onFrameOutput(final HttpConnection connection, final int streamId, final RawFrame frame) {
if (frameLog.isDebugEnabled()) {
if (FRAME_LOG.isDebugEnabled()) {
logFrameInfo(id + " >>", frame);
}
if (framePayloadLog.isDebugEnabled()) {
if (FRAME_PAYLOAD_LOG.isDebugEnabled()) {
logFramePayload(id + " >>", frame);
}
}
@Override
public void onInputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
if (flowCtrlLog.isDebugEnabled()) {
if (FLOW_CTRL_LOG.isDebugEnabled()) {
logFlowControl(id + " <<", streamId, delta, actualSize);
}
}
@Override
public void onOutputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
if (flowCtrlLog.isDebugEnabled()) {
if (FLOW_CTRL_LOG.isDebugEnabled()) {
logFlowControl(id + " >>", streamId, delta, actualSize);
}
}

View File

@ -74,7 +74,7 @@ import org.slf4j.LoggerFactory;
@Internal
class HttpAsyncMainClientExec implements AsyncExecChainHandler {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(HttpAsyncMainClientExec.class);
private final ConnectionKeepAliveStrategy keepAliveStrategy;
private final UserTokenHandler userTokenHandler;
@ -97,8 +97,8 @@ class HttpAsyncMainClientExec implements AsyncExecChainHandler {
final HttpClientContext clientContext = scope.clientContext;
final AsyncExecRuntime execRuntime = scope.execRuntime;
if (log.isDebugEnabled()) {
log.debug("{}: executing {}", exchangeId, new RequestLine(request));
if (LOG.isDebugEnabled()) {
LOG.debug("{}: executing {}", exchangeId, new RequestLine(request));
}
final AtomicInteger messageCountDown = new AtomicInteger(2);
@ -241,10 +241,10 @@ class HttpAsyncMainClientExec implements AsyncExecChainHandler {
};
if (log.isDebugEnabled()) {
if (LOG.isDebugEnabled()) {
operation.setDependency(execRuntime.execute(
exchangeId,
new LoggingAsyncClientExchangeHandler(log, exchangeId, internalExchangeHandler),
new LoggingAsyncClientExchangeHandler(LOG, exchangeId, internalExchangeHandler),
clientContext));
} else {
operation.setDependency(execRuntime.execute(exchangeId, internalExchangeHandler, clientContext));

View File

@ -71,9 +71,12 @@ import org.apache.hc.core5.http.protocol.HttpContext;
import org.apache.hc.core5.io.CloseMode;
import org.apache.hc.core5.io.ModalCloseable;
import org.apache.hc.core5.reactor.DefaultConnectingIOReactor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
abstract class InternalAbstractHttpAsyncClient extends AbstractHttpAsyncClientBase {
private static final Logger LOG = LoggerFactory.getLogger(InternalAbstractHttpAsyncClient.class);
private final AsyncExecChainElement execChain;
private final Lookup<CookieSpecFactory> cookieSpecRegistry;
private final Lookup<AuthSchemeFactory> authSchemeRegistry;
@ -115,7 +118,7 @@ abstract class InternalAbstractHttpAsyncClient extends AbstractHttpAsyncClientBa
closeable.close();
}
} catch (final IOException ex) {
this.log.error(ex.getMessage(), ex);
LOG.error(ex.getMessage(), ex);
}
}
}
@ -176,8 +179,8 @@ abstract class InternalAbstractHttpAsyncClient extends AbstractHttpAsyncClientBa
httpHost != null ? httpHost : RoutingSupport.determineHost(request),
clientContext);
final String exchangeId = ExecSupport.getNextExchangeId();
if (log.isDebugEnabled()) {
log.debug("{}: preparing request execution", exchangeId);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: preparing request execution", exchangeId);
}
final AsyncExecRuntime execRuntime = createAsyncExecRuntime(pushHandlerFactory);
@ -286,8 +289,8 @@ abstract class InternalAbstractHttpAsyncClient extends AbstractHttpAsyncClientBa
@Override
public void completed() {
if (log.isDebugEnabled()) {
log.debug("{}: message exchange successfully completed", exchangeId);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: message exchange successfully completed", exchangeId);
}
try {
execRuntime.releaseEndpoint();
@ -299,8 +302,8 @@ abstract class InternalAbstractHttpAsyncClient extends AbstractHttpAsyncClientBa
@Override
public void failed(final Exception cause) {
if (log.isDebugEnabled()) {
log.debug("{}: request failed: {}", exchangeId, cause.getMessage());
if (LOG.isDebugEnabled()) {
LOG.debug("{}: request failed: {}", exchangeId, cause.getMessage());
}
try {
execRuntime.discardEndpoint();

View File

@ -49,6 +49,8 @@ import org.apache.hc.core5.http.nio.AsyncPushConsumer;
import org.apache.hc.core5.http.nio.HandlerFactory;
import org.apache.hc.core5.http2.nio.pool.H2ConnPool;
import org.apache.hc.core5.reactor.DefaultConnectingIOReactor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Internal implementation of HTTP/2 only {@link CloseableHttpAsyncClient}.
@ -64,6 +66,7 @@ import org.apache.hc.core5.reactor.DefaultConnectingIOReactor;
@Internal
public final class InternalH2AsyncClient extends InternalAbstractHttpAsyncClient {
private static final Logger LOG = LoggerFactory.getLogger(InternalH2AsyncClient.class);
private final HttpRoutePlanner routePlanner;
private final H2ConnPool connPool;
@ -88,7 +91,7 @@ public final class InternalH2AsyncClient extends InternalAbstractHttpAsyncClient
@Override
AsyncExecRuntime createAsyncExecRuntime(final HandlerFactory<AsyncPushConsumer> pushHandlerFactory) {
return new InternalH2AsyncExecRuntime(log, connPool, pushHandlerFactory);
return new InternalH2AsyncExecRuntime(LOG, connPool, pushHandlerFactory);
}
@Override

View File

@ -52,6 +52,8 @@ import org.apache.hc.core5.http.nio.AsyncPushConsumer;
import org.apache.hc.core5.http.nio.HandlerFactory;
import org.apache.hc.core5.http2.HttpVersionPolicy;
import org.apache.hc.core5.reactor.DefaultConnectingIOReactor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Internal implementation of {@link CloseableHttpAsyncClient} that can negotiate
@ -68,6 +70,7 @@ import org.apache.hc.core5.reactor.DefaultConnectingIOReactor;
@Internal
public final class InternalHttpAsyncClient extends InternalAbstractHttpAsyncClient {
private static final Logger LOG = LoggerFactory.getLogger(InternalHttpAsyncClient.class);
private final AsyncClientConnectionManager manager;
private final HttpRoutePlanner routePlanner;
private final HttpVersionPolicy versionPolicy;
@ -95,7 +98,7 @@ public final class InternalHttpAsyncClient extends InternalAbstractHttpAsyncClie
@Override
AsyncExecRuntime createAsyncExecRuntime(final HandlerFactory<AsyncPushConsumer> pushHandlerFactory) {
return new InternalHttpAsyncExecRuntime(log, manager, getConnectionInitiator(), pushHandlerFactory, versionPolicy);
return new InternalHttpAsyncExecRuntime(LOG, manager, getConnectionInitiator(), pushHandlerFactory, versionPolicy);
}
@Override

View File

@ -35,14 +35,14 @@ class LoggingExceptionCallback implements Callback<Exception> {
static LoggingExceptionCallback INSTANCE = new LoggingExceptionCallback();
private final Logger log = LoggerFactory.getLogger("org.apache.hc.client5.http.impl.async");
private static final Logger LOG = LoggerFactory.getLogger("org.apache.hc.client5.http.impl.async");
private LoggingExceptionCallback() {
}
@Override
public void execute(final Exception ex) {
log.error(ex.getMessage(), ex);
LOG.error(ex.getMessage(), ex);
}
}

View File

@ -80,8 +80,8 @@ class LoggingIOSession implements IOSession {
@Override
public void enqueue(final Command command, final Command.Priority priority) {
this.session.enqueue(command, priority);
if (this.log.isDebugEnabled()) {
this.log.debug("{} Enqueued {} with priority {}", this.session, command.getClass().getSimpleName(), priority);
if (log.isDebugEnabled()) {
log.debug("{} Enqueued {} with priority {}", this.session, command.getClass().getSimpleName(), priority);
}
}
@ -127,24 +127,24 @@ class LoggingIOSession implements IOSession {
@Override
public void setEventMask(final int ops) {
this.session.setEventMask(ops);
if (this.log.isDebugEnabled()) {
this.log.debug("{} {}: Event mask set {}", this.id, this.session, formatOps(ops));
if (log.isDebugEnabled()) {
log.debug("{} {}: Event mask set {}", this.id, this.session, formatOps(ops));
}
}
@Override
public void setEvent(final int op) {
this.session.setEvent(op);
if (this.log.isDebugEnabled()) {
this.log.debug("{} {}: Event set {}", this.id, this.session, formatOps(op));
if (log.isDebugEnabled()) {
log.debug("{} {}: Event set {}", this.id, this.session, formatOps(op));
}
}
@Override
public void clearEvent(final int op) {
this.session.clearEvent(op);
if (this.log.isDebugEnabled()) {
this.log.debug("{} {}: Event cleared {}", this.id, this.session, formatOps(op));
if (log.isDebugEnabled()) {
log.debug("{} {}: Event cleared {}", this.id, this.session, formatOps(op));
}
}
@ -155,8 +155,8 @@ class LoggingIOSession implements IOSession {
@Override
public void close() {
if (this.log.isDebugEnabled()) {
this.log.debug("{} {}: Close", this.id, this.session);
if (log.isDebugEnabled()) {
log.debug("{} {}: Close", this.id, this.session);
}
this.session.close();
}
@ -168,8 +168,8 @@ class LoggingIOSession implements IOSession {
@Override
public void close(final CloseMode closeMode) {
if (this.log.isDebugEnabled()) {
this.log.debug("{} {}: Close {}", this.id, this.session, closeMode);
if (log.isDebugEnabled()) {
log.debug("{} {}: Close {}", this.id, this.session, closeMode);
}
this.session.close(closeMode);
}
@ -181,8 +181,8 @@ class LoggingIOSession implements IOSession {
@Override
public void setSocketTimeout(final Timeout timeout) {
if (this.log.isDebugEnabled()) {
this.log.debug("{} {}: Set timeout {}", this.id, this.session, timeout);
if (log.isDebugEnabled()) {
log.debug("{} {}: Set timeout {}", this.id, this.session, timeout);
}
this.session.setSocketTimeout(timeout);
}
@ -225,8 +225,8 @@ class LoggingIOSession implements IOSession {
@Override
public int read(final ByteBuffer dst) throws IOException {
final int bytesRead = this.session.channel().read(dst);
if (this.log.isDebugEnabled()) {
this.log.debug("{} {}: {} bytes read", this.id, this.session, bytesRead);
if (log.isDebugEnabled()) {
log.debug("{} {}: {} bytes read", this.id, this.session, bytesRead);
}
if (bytesRead > 0 && this.wireLog.isEnabled()) {
final ByteBuffer b = dst.duplicate();
@ -242,8 +242,8 @@ class LoggingIOSession implements IOSession {
@Override
public int write(final ByteBuffer src) throws IOException {
final int byteWritten = session.channel().write(src);
if (this.log.isDebugEnabled()) {
this.log.debug("{} {}: {} bytes written", this.id, this.session, byteWritten);
if (log.isDebugEnabled()) {
log.debug("{} {}: {} bytes written", this.id, this.session, byteWritten);
}
if (byteWritten > 0 && this.wireLog.isEnabled()) {
final ByteBuffer b = src.duplicate();

View File

@ -36,7 +36,7 @@ final class LoggingIOSessionDecorator implements Decorator<IOSession> {
public final static LoggingIOSessionDecorator INSTANCE = new LoggingIOSessionDecorator();
private final Logger wireLog = LoggerFactory.getLogger("org.apache.hc.client5.http.wire");
private static final Logger WIRE_LOG = LoggerFactory.getLogger("org.apache.hc.client5.http.wire");
private LoggingIOSessionDecorator() {
}
@ -44,8 +44,8 @@ final class LoggingIOSessionDecorator implements Decorator<IOSession> {
@Override
public IOSession decorate(final IOSession ioSession) {
final Logger sessionLog = LoggerFactory.getLogger(ioSession.getClass());
if (sessionLog.isDebugEnabled() || wireLog.isDebugEnabled()) {
return new LoggingIOSession(ioSession, sessionLog, wireLog);
if (sessionLog.isDebugEnabled() || WIRE_LOG.isDebugEnabled()) {
return new LoggingIOSession(ioSession, sessionLog, WIRE_LOG);
} else {
return ioSession;
}

View File

@ -74,6 +74,8 @@ 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.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Minimal implementation of HTTP/2 only {@link CloseableHttpAsyncClient}. This client
@ -91,6 +93,7 @@ import org.apache.hc.core5.util.Timeout;
@Contract(threading = ThreadingBehavior.SAFE_CONDITIONAL)
public final class MinimalH2AsyncClient extends AbstractMinimalHttpAsyncClientBase {
private static final Logger LOG = LoggerFactory.getLogger(MinimalH2AsyncClient.class);
private final H2ConnPool connPool;
private final ConnectionInitiator connectionInitiator;
@ -230,12 +233,12 @@ public final class MinimalH2AsyncClient extends AbstractMinimalHttpAsyncClientBa
}
};
if (log.isDebugEnabled()) {
if (LOG.isDebugEnabled()) {
final String exchangeId = ExecSupport.getNextExchangeId();
log.debug("{}: executing message exchange {}", ConnPoolSupport.getId(session), exchangeId);
LOG.debug("{}: executing message exchange {}", ConnPoolSupport.getId(session), exchangeId);
session.enqueue(
new RequestExecutionCommand(
new LoggingAsyncClientExchangeHandler(log, exchangeId, internalExchangeHandler),
new LoggingAsyncClientExchangeHandler(LOG, exchangeId, internalExchangeHandler),
pushHandlerFactory,
cancellable,
clientContext),

View File

@ -83,6 +83,8 @@ import org.apache.hc.core5.util.Args;
import org.apache.hc.core5.util.Asserts;
import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Minimal implementation of {@link CloseableHttpAsyncClient}. This client is
@ -99,6 +101,7 @@ import org.apache.hc.core5.util.Timeout;
@Contract(threading = ThreadingBehavior.SAFE_CONDITIONAL)
public final class MinimalHttpAsyncClient extends AbstractMinimalHttpAsyncClientBase {
private static final Logger LOG = LoggerFactory.getLogger(MinimalHttpAsyncClient.class);
private final AsyncClientConnectionManager manager;
private final SchemePortResolver schemePortResolver;
private final HttpVersionPolicy versionPolicy;
@ -465,11 +468,11 @@ public final class MinimalHttpAsyncClient extends AbstractMinimalHttpAsyncClient
Asserts.check(!released.get(), "Endpoint has already been released");
final String exchangeId = ExecSupport.getNextExchangeId();
if (log.isDebugEnabled()) {
log.debug("{}: executing message exchange {}", ConnPoolSupport.getId(connectionEndpoint), exchangeId);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: executing message exchange {}", ConnPoolSupport.getId(connectionEndpoint), exchangeId);
connectionEndpoint.execute(
exchangeId,
new LoggingAsyncClientExchangeHandler(log, exchangeId, exchangeHandler),
new LoggingAsyncClientExchangeHandler(LOG, exchangeId, exchangeHandler),
pushHandlerFactory,
context);
} else {

View File

@ -60,7 +60,7 @@ import org.slf4j.LoggerFactory;
@Contract(threading = ThreadingBehavior.SAFE_CONDITIONAL)
public class BasicAuthCache implements AuthCache {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(BasicAuthCache.class);
private final Map<HttpHost, byte[]> map;
private final SchemePortResolver schemePortResolver;
@ -95,13 +95,13 @@ public class BasicAuthCache implements AuthCache {
final HttpHost key = RoutingSupport.normalize(host, schemePortResolver);
this.map.put(key, buf.toByteArray());
} catch (final IOException ex) {
if (log.isWarnEnabled()) {
log.warn("Unexpected I/O error while serializing auth scheme", ex);
if (LOG.isWarnEnabled()) {
LOG.warn("Unexpected I/O error while serializing auth scheme", ex);
}
}
} else {
if (log.isDebugEnabled()) {
log.debug("Auth scheme {} is not serializable", authScheme.getClass());
if (LOG.isDebugEnabled()) {
LOG.debug("Auth scheme {} is not serializable", authScheme.getClass());
}
}
}
@ -118,13 +118,13 @@ public class BasicAuthCache implements AuthCache {
return (AuthScheme) in.readObject();
}
} catch (final IOException ex) {
if (log.isWarnEnabled()) {
log.warn("Unexpected I/O error while de-serializing auth scheme", ex);
if (LOG.isWarnEnabled()) {
LOG.warn("Unexpected I/O error while de-serializing auth scheme", ex);
}
return null;
} catch (final ClassNotFoundException ex) {
if (log.isWarnEnabled()) {
log.warn("Unexpected error while de-serializing auth scheme", ex);
if (LOG.isWarnEnabled()) {
LOG.warn("Unexpected error while de-serializing auth scheme", ex);
}
return null;
}

View File

@ -71,7 +71,7 @@ public abstract class GGSSchemeBase implements AuthScheme {
FAILED,
}
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(GGSSchemeBase.class);
private final KerberosConfig config;
private final DnsResolver dnsResolver;
@ -115,7 +115,7 @@ public abstract class GGSSchemeBase implements AuthScheme {
token = Base64.decodeBase64(challenge.getBytes());
state = State.CHALLENGE_RECEIVED;
} else {
log.debug("Authentication already attempted");
LOG.debug("Authentication already attempted");
state = State.FAILED;
}
}
@ -219,8 +219,8 @@ public abstract class GGSSchemeBase implements AuthScheme {
}
final String serviceName = host.getSchemeName().toUpperCase(Locale.ROOT);
if (log.isDebugEnabled()) {
log.debug("init {}", authServer);
if (LOG.isDebugEnabled()) {
LOG.debug("init {}", authServer);
}
token = generateToken(token, serviceName, authServer);
state = State.TOKEN_GENERATED;
@ -244,8 +244,8 @@ public abstract class GGSSchemeBase implements AuthScheme {
case TOKEN_GENERATED:
final Base64 codec = new Base64(0);
final String tokenstr = new String(codec.encode(token));
if (log.isDebugEnabled()) {
log.debug("Sending response '{}' back to the auth server", tokenstr);
if (LOG.isDebugEnabled()) {
LOG.debug("Sending response '{}' back to the auth server", tokenstr);
}
return StandardAuthScheme.SPNEGO + " " + tokenstr;
default:

View File

@ -72,13 +72,15 @@ import org.slf4j.LoggerFactory;
@Contract(threading = ThreadingBehavior.STATELESS)
public final class HttpAuthenticator {
private static final Logger DEFAULT_LOGGER = LoggerFactory.getLogger(HttpAuthenticator.class);
private final Logger log;
private final AuthChallengeParser parser;
@Internal
public HttpAuthenticator(final Logger log) {
super();
this.log = log != null ? log : LoggerFactory.getLogger(getClass());
this.log = log != null ? log : DEFAULT_LOGGER;
this.parser = new AuthChallengeParser();
}
@ -118,7 +120,7 @@ public final class HttpAuthenticator {
final HttpClientContext clientContext = HttpClientContext.adapt(context);
if (response.getCode() == challengeCode) {
this.log.debug("Authentication required");
log.debug("Authentication required");
if (authExchange.getState() == AuthExchange.State.SUCCESS) {
clearCache(host, clientContext);
}
@ -127,7 +129,7 @@ public final class HttpAuthenticator {
switch (authExchange.getState()) {
case CHALLENGED:
case HANDSHAKE:
this.log.debug("Authentication succeeded");
log.debug("Authentication succeeded");
authExchange.setState(AuthExchange.State.SUCCESS);
updateCache(host, authExchange.getAuthScheme(), clientContext);
break;
@ -160,8 +162,8 @@ public final class HttpAuthenticator {
final AuthExchange authExchange,
final HttpContext context) {
if (this.log.isDebugEnabled()) {
this.log.debug("{} requested authentication", host.toHostString());
if (log.isDebugEnabled()) {
log.debug("{} requested authentication", host.toHostString());
}
final HttpClientContext clientContext = HttpClientContext.adapt(context);
@ -189,8 +191,8 @@ public final class HttpAuthenticator {
try {
authChallenges = parser.parse(challengeType, buffer, cursor);
} catch (final ParseException ex) {
if (this.log.isWarnEnabled()) {
this.log.warn("Malformed challenge: {}", header.getValue());
if (log.isWarnEnabled()) {
log.warn("Malformed challenge: {}", header.getValue());
}
continue;
}
@ -202,7 +204,7 @@ public final class HttpAuthenticator {
}
}
if (challengeMap.isEmpty()) {
this.log.debug("Response contains no valid authentication challenges");
log.debug("Response contains no valid authentication challenges");
clearCache(host, clientContext);
authExchange.reset();
return false;
@ -223,19 +225,19 @@ public final class HttpAuthenticator {
final String schemeName = authScheme.getName();
final AuthChallenge challenge = challengeMap.get(schemeName.toLowerCase(Locale.ROOT));
if (challenge != null) {
this.log.debug("Authorization challenge processed");
log.debug("Authorization challenge processed");
try {
authScheme.processChallenge(challenge, context);
} catch (final MalformedChallengeException ex) {
if (this.log.isWarnEnabled()) {
this.log.warn(ex.getMessage());
if (log.isWarnEnabled()) {
log.warn(ex.getMessage());
}
clearCache(host, clientContext);
authExchange.reset();
return false;
}
if (authScheme.isChallengeComplete()) {
this.log.debug("Authentication failed");
log.debug("Authentication failed");
clearCache(host, clientContext);
authExchange.reset();
authExchange.setState(AuthExchange.State.FAILURE);
@ -252,12 +254,12 @@ public final class HttpAuthenticator {
final List<AuthScheme> preferredSchemes = authStrategy.select(challengeType, challengeMap, context);
final CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
if (credsProvider == null) {
this.log.debug("Credentials provider not set in the context");
log.debug("Credentials provider not set in the context");
return false;
}
final Queue<AuthScheme> authOptions = new LinkedList<>();
this.log.debug("Selecting authentication options");
log.debug("Selecting authentication options");
for (final AuthScheme authScheme: preferredSchemes) {
try {
final String schemeName = authScheme.getName();
@ -267,14 +269,14 @@ public final class HttpAuthenticator {
authOptions.add(authScheme);
}
} catch (final AuthenticationException | MalformedChallengeException ex) {
if (this.log.isWarnEnabled()) {
this.log.warn(ex.getMessage());
if (log.isWarnEnabled()) {
log.warn(ex.getMessage());
}
}
}
if (!authOptions.isEmpty()) {
if (this.log.isDebugEnabled()) {
this.log.debug("Selected authentication options: {}", authOptions);
if (log.isDebugEnabled()) {
log.debug("Selected authentication options: {}", authOptions);
}
authExchange.reset();
authExchange.setState(AuthExchange.State.CHALLENGED);
@ -319,8 +321,8 @@ public final class HttpAuthenticator {
while (!authOptions.isEmpty()) {
authScheme = authOptions.remove();
authExchange.select(authScheme);
if (this.log.isDebugEnabled()) {
this.log.debug("Generating response to an authentication challenge using {} scheme", authScheme.getName());
if (log.isDebugEnabled()) {
log.debug("Generating response to an authentication challenge using {} scheme", authScheme.getName());
}
try {
final String authResponse = authScheme.generateAuthResponse(host, request, context);
@ -330,8 +332,8 @@ public final class HttpAuthenticator {
request.addHeader(header);
break;
} catch (final AuthenticationException ex) {
if (this.log.isWarnEnabled()) {
this.log.warn("{} authentication error: {}", authScheme, ex.getMessage());
if (log.isWarnEnabled()) {
log.warn("{} authentication error: {}", authScheme, ex.getMessage());
}
}
}
@ -348,8 +350,8 @@ public final class HttpAuthenticator {
authResponse);
request.addHeader(header);
} catch (final AuthenticationException ex) {
if (this.log.isErrorEnabled()) {
this.log.error("{} authentication error: {}", authScheme, ex.getMessage());
if (log.isErrorEnabled()) {
log.error("{} authentication error: {}", authScheme, ex.getMessage());
}
}
}
@ -363,8 +365,8 @@ public final class HttpAuthenticator {
authCache = new BasicAuthCache();
clientContext.setAuthCache(authCache);
}
if (this.log.isDebugEnabled()) {
this.log.debug("Caching '{}' auth scheme for {}", authScheme.getName(), host);
if (log.isDebugEnabled()) {
log.debug("Caching '{}' auth scheme for {}", authScheme.getName(), host);
}
authCache.put(host, authScheme);
}
@ -374,8 +376,8 @@ public final class HttpAuthenticator {
final AuthCache authCache = clientContext.getAuthCache();
if (authCache != null) {
if (this.log.isDebugEnabled()) {
this.log.debug("Clearing cached auth scheme for {}", host);
if (log.isDebugEnabled()) {
log.debug("Clearing cached auth scheme for {}", host);
}
authCache.remove(host);
}

View File

@ -54,7 +54,7 @@ import org.slf4j.LoggerFactory;
@Contract(threading = ThreadingBehavior.SAFE)
public abstract class CloseableHttpClient implements HttpClient, ModalCloseable {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(CloseableHttpClient.class);
protected abstract CloseableHttpResponse doExecute(HttpHost target, ClassicHttpRequest request,
HttpContext context) throws IOException;
@ -211,7 +211,7 @@ public abstract class CloseableHttpClient implements HttpClient, ModalCloseable
} catch (final Exception t2) {
// Log this exception. The original exception is more
// important and will be thrown to the caller.
this.log.warn("Error consuming content after an exception.", t2);
LOG.warn("Error consuming content after an exception.", t2);
}
throw new ClientProtocolException(t);
}

View File

@ -75,7 +75,7 @@ import org.slf4j.LoggerFactory;
@Internal
public final class ConnectExec implements ExecChainHandler {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(ConnectExec.class);
private final ConnectionReuseStrategy reuseStrategy;
private final HttpProcessor proxyHttpProcessor;
@ -93,7 +93,7 @@ public final class ConnectExec implements ExecChainHandler {
this.reuseStrategy = reuseStrategy;
this.proxyHttpProcessor = proxyHttpProcessor;
this.proxyAuthStrategy = proxyAuthStrategy;
this.authenticator = new HttpAuthenticator(log);
this.authenticator = new HttpAuthenticator(LOG);
this.routeDirector = new BasicRouteDirector();
}
@ -112,15 +112,15 @@ public final class ConnectExec implements ExecChainHandler {
if (!execRuntime.isEndpointAcquired()) {
final Object userToken = context.getUserToken();
if (log.isDebugEnabled()) {
log.debug("{}: acquiring connection with route {}", exchangeId, route);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: acquiring connection with route {}", exchangeId, route);
}
execRuntime.acquireEndpoint(exchangeId, route, userToken, context);
}
try {
if (!execRuntime.isEndpointConnected()) {
if (log.isDebugEnabled()) {
log.debug("{}: opening connection {}", exchangeId, route);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: opening connection {}", exchangeId, route);
}
final RouteTracker tracker = new RouteTracker(route);
@ -142,8 +142,8 @@ public final class ConnectExec implements ExecChainHandler {
break;
case HttpRouteDirector.TUNNEL_TARGET: {
final boolean secure = createTunnelToTarget(exchangeId, route, request, execRuntime, context);
if (log.isDebugEnabled()) {
log.debug("{}: tunnel to target created.", exchangeId);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: tunnel to target created.", exchangeId);
}
tracker.tunnelTarget(secure);
} break;
@ -155,8 +155,8 @@ public final class ConnectExec implements ExecChainHandler {
// fact: Source -> P1 -> Target (2 hops)
final int hop = fact.getHopCount()-1; // the hop to establish
final boolean secure = createTunnelToProxy(route, hop, context);
if (log.isDebugEnabled()) {
log.debug("{}: tunnel to proxy created.", exchangeId);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: tunnel to proxy created.", exchangeId);
}
tracker.tunnelProxy(route.getHopTarget(hop), secure);
} break;
@ -233,8 +233,8 @@ public final class ConnectExec implements ExecChainHandler {
this.proxyAuthStrategy, proxyAuthExchange, context)) {
// Retry request
if (this.reuseStrategy.keepAlive(request, response, context)) {
if (log.isDebugEnabled()) {
log.debug("{}: connection kept alive", exchangeId);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: connection kept alive", exchangeId);
}
// Consume response content
final HttpEntity entity = response.getEntity();

View File

@ -65,7 +65,7 @@ import org.slf4j.LoggerFactory;
@Internal
public class HttpRequestRetryExec implements ExecChainHandler {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(HttpRequestRetryExec.class);
private final HttpRequestRetryStrategy retryStrategy;
@ -97,17 +97,17 @@ public class HttpRequestRetryExec implements ExecChainHandler {
}
final HttpEntity requestEntity = request.getEntity();
if (requestEntity != null && !requestEntity.isRepeatable()) {
if (log.isDebugEnabled()) {
log.debug("{}: cannot retry non-repeatable request", exchangeId);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: cannot retry non-repeatable request", exchangeId);
}
throw ex;
}
if (retryStrategy.retryRequest(request, ex, execCount, context)) {
if (log.isDebugEnabled()) {
log.debug("{}: {}", exchangeId, ex.getMessage(), ex);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: {}", exchangeId, ex.getMessage(), ex);
}
if (log.isInfoEnabled()) {
log.info("Recoverable I/O exception ({}) caught when processing request to {}",
if (LOG.isInfoEnabled()) {
LOG.info("Recoverable I/O exception ({}) caught when processing request to {}",
ex.getClass().getName(), route);
}
currentRequest = ClassicRequestCopier.INSTANCE.copy(scope.originalRequest);
@ -126,8 +126,8 @@ public class HttpRequestRetryExec implements ExecChainHandler {
try {
final HttpEntity entity = request.getEntity();
if (entity != null && !entity.isRepeatable()) {
if (log.isDebugEnabled()) {
log.debug("{}: cannot retry non-repeatable request", exchangeId);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: cannot retry non-repeatable request", exchangeId);
}
return response;
}
@ -137,8 +137,8 @@ public class HttpRequestRetryExec implements ExecChainHandler {
retryStrategy.getRetryInterval(response, execCount, context);
if (TimeValue.isPositive(nextInterval)) {
try {
if (log.isDebugEnabled()) {
log.debug("{}: wait for {}", exchangeId, nextInterval);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: wait for {}", exchangeId, nextInterval);
}
nextInterval.sleep();
} catch (final InterruptedException e) {

View File

@ -80,7 +80,7 @@ import org.slf4j.LoggerFactory;
@Internal
class InternalHttpClient extends CloseableHttpClient implements Configurable {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(InternalHttpClient.class);
private final HttpClientConnectionManager connManager;
private final HttpRequestExecutor requestExecutor;
@ -168,11 +168,11 @@ class InternalHttpClient extends CloseableHttpClient implements Configurable {
setupContext(localcontext);
final HttpRoute route = determineRoute(target, request, localcontext);
final String exchangeId = ExecSupport.getNextExchangeId();
if (log.isDebugEnabled()) {
log.debug("{}: preparing request execution", exchangeId);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: preparing request execution", exchangeId);
}
final ExecRuntime execRuntime = new InternalExecRuntime(log, connManager, requestExecutor,
final ExecRuntime execRuntime = new InternalExecRuntime(LOG, connManager, requestExecutor,
request instanceof CancellableDependency ? (CancellableDependency) request : null);
final ExecChain.Scope scope = new ExecChain.Scope(exchangeId, route, request, execRuntime, localcontext);
final ClassicHttpResponse response = this.execChain.execute(ClassicRequestCopier.INSTANCE.copy(request), scope);
@ -204,7 +204,7 @@ class InternalHttpClient extends CloseableHttpClient implements Configurable {
closeable.close();
}
} catch (final IOException ex) {
this.log.error(ex.getMessage(), ex);
LOG.error(ex.getMessage(), ex);
}
}
}

View File

@ -65,7 +65,7 @@ import org.slf4j.LoggerFactory;
@Internal
public final class MainClientExec implements ExecChainHandler {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(MainClientExec.class);
private final HttpClientConnectionManager connectionManager;
private final ConnectionReuseStrategy reuseStrategy;
@ -98,8 +98,8 @@ public final class MainClientExec implements ExecChainHandler {
final HttpClientContext context = scope.clientContext;
final ExecRuntime execRuntime = scope.execRuntime;
if (log.isDebugEnabled()) {
log.debug("{}: executing {}", exchangeId, new RequestLine(request));
if (LOG.isDebugEnabled()) {
LOG.debug("{}: executing {}", exchangeId, new RequestLine(request));
}
try {
RequestEntityProxy.enhance(request);
@ -116,14 +116,14 @@ public final class MainClientExec implements ExecChainHandler {
if (reuseStrategy.keepAlive(request, response, context)) {
// Set the idle duration of this connection
final TimeValue duration = keepAliveStrategy.getKeepAliveDuration(response, context);
if (this.log.isDebugEnabled()) {
if (LOG.isDebugEnabled()) {
final String s;
if (duration != null) {
s = "for " + duration;
} else {
s = "indefinitely";
}
this.log.debug("{}: connection can be kept alive {}", exchangeId, s);
LOG.debug("{}: connection can be kept alive {}", exchangeId, s);
}
execRuntime.markConnectionReusable(userToken, duration);
} else {

View File

@ -85,7 +85,7 @@ import org.slf4j.LoggerFactory;
@Contract(threading = ThreadingBehavior.SAFE_CONDITIONAL)
public class MinimalHttpClient extends CloseableHttpClient {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(MinimalHttpClient.class);
private final HttpClientConnectionManager connManager;
private final ConnectionReuseStrategy reuseStrategy;
@ -132,7 +132,7 @@ public class MinimalHttpClient extends CloseableHttpClient {
final HttpRoute route = new HttpRoute(RoutingSupport.normalize(target, schemePortResolver));
final String exchangeId = ExecSupport.getNextExchangeId();
final ExecRuntime execRuntime = new InternalExecRuntime(log, connManager, requestExecutor,
final ExecRuntime execRuntime = new InternalExecRuntime(LOG, connManager, requestExecutor,
request instanceof CancellableDependency ? (CancellableDependency) request : null);
try {
if (!execRuntime.isEndpointAcquired()) {

View File

@ -82,7 +82,7 @@ import org.slf4j.LoggerFactory;
@Internal
public final class ProtocolExec implements ExecChainHandler {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(ProtocolExec.class);
private final HttpProcessor httpProcessor;
private final AuthenticationStrategy targetAuthStrategy;
@ -154,14 +154,14 @@ public final class ProtocolExec implements ExecChainHandler {
httpProcessor.process(request, request.getEntity(), context);
if (!request.containsHeader(HttpHeaders.AUTHORIZATION)) {
if (log.isDebugEnabled()) {
log.debug("{}: target auth state: {}", exchangeId, targetAuthExchange.getState());
if (LOG.isDebugEnabled()) {
LOG.debug("{}: target auth state: {}", exchangeId, targetAuthExchange.getState());
}
authenticator.addAuthResponse(target, ChallengeType.TARGET, request, targetAuthExchange, context);
}
if (!request.containsHeader(HttpHeaders.PROXY_AUTHORIZATION) && !route.isTunnelled()) {
if (log.isDebugEnabled()) {
log.debug("{}: proxy auth state: {}", exchangeId, proxyAuthExchange.getState());
if (LOG.isDebugEnabled()) {
LOG.debug("{}: proxy auth state: {}", exchangeId, proxyAuthExchange.getState());
}
authenticator.addAuthResponse(proxy, ChallengeType.PROXY, request, proxyAuthExchange, context);
}
@ -177,8 +177,8 @@ public final class ProtocolExec implements ExecChainHandler {
}
final HttpEntity requestEntity = request.getEntity();
if (requestEntity != null && !requestEntity.isRepeatable()) {
if (log.isDebugEnabled()) {
log.debug("{}: Cannot retry non-repeatable request", exchangeId);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: Cannot retry non-repeatable request", exchangeId);
}
return response;
}
@ -191,15 +191,15 @@ public final class ProtocolExec implements ExecChainHandler {
execRuntime.disconnectEndpoint();
if (proxyAuthExchange.getState() == AuthExchange.State.SUCCESS
&& proxyAuthExchange.isConnectionBased()) {
if (log.isDebugEnabled()) {
log.debug("{}: resetting proxy auth state", exchangeId);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: resetting proxy auth state", exchangeId);
}
proxyAuthExchange.reset();
}
if (targetAuthExchange.getState() == AuthExchange.State.SUCCESS
&& targetAuthExchange.isConnectionBased()) {
if (log.isDebugEnabled()) {
log.debug("{}: resetting target auth state", exchangeId);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: resetting target auth state", exchangeId);
}
targetAuthExchange.reset();
}

View File

@ -76,7 +76,7 @@ import org.slf4j.LoggerFactory;
@Internal
public final class RedirectExec implements ExecChainHandler {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(RedirectExec.class);
private final RedirectStrategy redirectStrategy;
private final HttpRoutePlanner routePlanner;
@ -118,8 +118,8 @@ public final class RedirectExec implements ExecChainHandler {
if (config.isRedirectsEnabled() && this.redirectStrategy.isRedirected(request, response, context)) {
final HttpEntity requestEntity = request.getEntity();
if (requestEntity != null && !requestEntity.isRepeatable()) {
if (log.isDebugEnabled()) {
log.debug("{}: cannot redirect non-repeatable request", exchangeId);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: cannot redirect non-repeatable request", exchangeId);
}
return response;
}
@ -129,8 +129,8 @@ public final class RedirectExec implements ExecChainHandler {
redirectCount++;
final URI redirectUri = this.redirectStrategy.getLocationURI(currentRequest, response, context);
if (log.isDebugEnabled()) {
log.debug("{}: redirect requested to location '{}'", exchangeId, redirectUri);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: redirect requested to location '{}'", exchangeId, redirectUri);
}
if (!config.isCircularRedirectsAllowed()) {
if (redirectLocations.contains(redirectUri)) {
@ -170,19 +170,19 @@ public final class RedirectExec implements ExecChainHandler {
if (!LangUtils.equals(currentRoute.getTargetHost(), newTarget)) {
final HttpRoute newRoute = this.routePlanner.determineRoute(newTarget, context);
if (!LangUtils.equals(currentRoute, newRoute)) {
if (log.isDebugEnabled()) {
log.debug("{}: new route required", exchangeId);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: new route required", exchangeId);
}
final AuthExchange targetAuthExchange = context.getAuthExchange(currentRoute.getTargetHost());
if (log.isDebugEnabled()) {
log.debug("{}: resetting target auth state", exchangeId);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: resetting target auth state", exchangeId);
}
targetAuthExchange.reset();
if (currentRoute.getProxyHost() != null) {
final AuthExchange proxyAuthExchange = context.getAuthExchange(currentRoute.getProxyHost());
if (proxyAuthExchange.isConnectionBased()) {
if (log.isDebugEnabled()) {
log.debug("{}: resetting proxy auth state", exchangeId);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: resetting proxy auth state", exchangeId);
}
proxyAuthExchange.reset();
}
@ -196,8 +196,8 @@ public final class RedirectExec implements ExecChainHandler {
}
}
if (log.isDebugEnabled()) {
log.debug("{}: redirecting to '{}' via {}", exchangeId, redirectUri, currentRoute);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: redirecting to '{}' via {}", exchangeId, redirectUri, currentRoute);
}
currentRequest = redirect;
RequestEntityProxy.enhance(currentRequest);
@ -216,8 +216,8 @@ public final class RedirectExec implements ExecChainHandler {
try {
EntityUtils.consume(response.getEntity());
} catch (final IOException ioex) {
if (log.isDebugEnabled()) {
log.debug("{}: I/O error while releasing connection", exchangeId, ioex);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: I/O error while releasing connection", exchangeId, ioex);
}
} finally {
response.close();

View File

@ -90,7 +90,7 @@ import org.slf4j.LoggerFactory;
@Contract(threading = ThreadingBehavior.SAFE)
public class BasicHttpClientConnectionManager implements HttpClientConnectionManager {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(BasicHttpClientConnectionManager.class);
private final HttpClientConnectionOperator connectionOperator;
private final HttpConnectionFactory<ManagedHttpClientConnection> connFactory;
@ -206,7 +206,7 @@ public class BasicHttpClientConnectionManager implements HttpClientConnectionMan
private synchronized void closeConnection(final CloseMode closeMode) {
if (this.conn != null) {
this.log.debug("Closing connection {}", closeMode);
LOG.debug("Closing connection {}", closeMode);
this.conn.close(closeMode);
this.conn = null;
}
@ -214,8 +214,8 @@ public class BasicHttpClientConnectionManager implements HttpClientConnectionMan
private void checkExpiry() {
if (this.conn != null && System.currentTimeMillis() >= this.expiry) {
if (this.log.isDebugEnabled()) {
this.log.debug("Connection expired @ {}", new Date(this.expiry));
if (LOG.isDebugEnabled()) {
LOG.debug("Connection expired @ {}", new Date(this.expiry));
}
closeConnection(CloseMode.GRACEFUL);
}
@ -223,8 +223,8 @@ public class BasicHttpClientConnectionManager implements HttpClientConnectionMan
synchronized ManagedHttpClientConnection getConnection(final HttpRoute route, final Object state) throws IOException {
Asserts.check(!this.closed.get(), "Connection manager has been shut down");
if (this.log.isDebugEnabled()) {
this.log.debug("Get connection for route {}", route);
if (LOG.isDebugEnabled()) {
LOG.debug("Get connection for route {}", route);
}
Asserts.check(!this.leased, "Connection is still allocated");
if (!LangUtils.equals(this.route, route) || !LangUtils.equals(this.state, state)) {
@ -254,8 +254,8 @@ public class BasicHttpClientConnectionManager implements HttpClientConnectionMan
Args.notNull(endpoint, "Managed endpoint");
final InternalConnectionEndpoint internalEndpoint = cast(endpoint);
final ManagedHttpClientConnection conn = internalEndpoint.detach();
if (conn != null && this.log.isDebugEnabled()) {
this.log.debug("Releasing connection {}", conn);
if (conn != null && LOG.isDebugEnabled()) {
LOG.debug("Releasing connection {}", conn);
}
if (this.closed.get()) {
return;
@ -270,20 +270,20 @@ public class BasicHttpClientConnectionManager implements HttpClientConnectionMan
this.route = null;
this.conn = null;
this.expiry = Long.MAX_VALUE;
if (this.log.isDebugEnabled()) {
this.log.debug("Connection is not kept alive");
if (LOG.isDebugEnabled()) {
LOG.debug("Connection is not kept alive");
}
} else {
this.state = state;
conn.passivate();
if (TimeValue.isPositive(keepAlive)) {
if (this.log.isDebugEnabled()) {
this.log.debug("Connection can be kept alive for {}", keepAlive);
if (LOG.isDebugEnabled()) {
LOG.debug("Connection can be kept alive for {}", keepAlive);
}
this.expiry = this.updated + keepAlive.toMilliseconds();
} else {
if (this.log.isDebugEnabled()) {
this.log.debug("Connection can be kept alive indefinitely");
if (LOG.isDebugEnabled()) {
LOG.debug("Connection can be kept alive indefinitely");
}
this.expiry = Long.MAX_VALUE;
}

View File

@ -69,7 +69,7 @@ public class DefaultHttpClientConnectionOperator implements HttpClientConnection
static final String SOCKET_FACTORY_REGISTRY = "http.socket-factory-registry";
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(DefaultHttpClientConnectionOperator.class);
private final Lookup<ConnectionSocketFactory> socketFactoryRegistry;
private final SchemePortResolver schemePortResolver;
@ -141,14 +141,14 @@ public class DefaultHttpClientConnectionOperator implements HttpClientConnection
conn.bind(sock);
final InetSocketAddress remoteAddress = new InetSocketAddress(address, port);
if (this.log.isDebugEnabled()) {
this.log.debug("{}: connecting to {}", ConnPoolSupport.getId(conn), remoteAddress);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: connecting to {}", ConnPoolSupport.getId(conn), remoteAddress);
}
try {
sock = sf.connectSocket(connectTimeout, sock, host, remoteAddress, localAddress, context);
conn.bind(sock);
if (this.log.isDebugEnabled()) {
this.log.debug("{}: connection established {}", ConnPoolSupport.getId(conn), conn);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: connection established {}", ConnPoolSupport.getId(conn), conn);
}
return;
} catch (final IOException ex) {
@ -156,8 +156,8 @@ public class DefaultHttpClientConnectionOperator implements HttpClientConnection
throw ConnectExceptionSupport.enhance(ex, host, addresses);
}
}
if (this.log.isDebugEnabled()) {
this.log.debug("{}: connect to {} timed out. Connection will be retried using another IP address", ConnPoolSupport.getId(conn), remoteAddress);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: connect to {} timed out. Connection will be retried using another IP address", ConnPoolSupport.getId(conn), remoteAddress);
}
}
}

View File

@ -58,9 +58,9 @@ import org.slf4j.LoggerFactory;
final class DefaultManagedHttpClientConnection
extends DefaultBHttpClientConnection implements ManagedHttpClientConnection, Identifiable {
private final Logger log = LoggerFactory.getLogger(DefaultManagedHttpClientConnection.class);
private final Logger headerLog = LoggerFactory.getLogger("org.apache.hc.client5.http.headers");
private final Logger wireLog = LoggerFactory.getLogger("org.apache.hc.client5.http.wire");
private static final Logger LOG = LoggerFactory.getLogger(DefaultManagedHttpClientConnection.class);
private static final Logger HEADER_LOG = LoggerFactory.getLogger("org.apache.hc.client5.http.headers");
private static final Logger WIRE_LOG = LoggerFactory.getLogger("org.apache.hc.client5.http.wire");
private final String id;
private final AtomicBoolean closed;
@ -121,8 +121,8 @@ final class DefaultManagedHttpClientConnection
@Override
public void close() throws IOException {
if (this.closed.compareAndSet(false, true)) {
if (this.log.isDebugEnabled()) {
this.log.debug("{}: Close connection", this.id);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: Close connection", this.id);
}
super.close();
}
@ -130,8 +130,8 @@ final class DefaultManagedHttpClientConnection
@Override
public void setSocketTimeout(final Timeout timeout) {
if (this.log.isDebugEnabled()) {
this.log.debug("{}: set socket timeout to {}", this.id, timeout);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: set socket timeout to {}", this.id, timeout);
}
super.setSocketTimeout(timeout);
}
@ -139,8 +139,8 @@ final class DefaultManagedHttpClientConnection
@Override
public void close(final CloseMode closeMode) {
if (this.closed.compareAndSet(false, true)) {
if (this.log.isDebugEnabled()) {
this.log.debug("{}: close connection {}", this.id, closeMode);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: close connection {}", this.id, closeMode);
}
super.close(closeMode);
}
@ -148,28 +148,28 @@ final class DefaultManagedHttpClientConnection
@Override
public void bind(final Socket socket) throws IOException {
super.bind(this.wireLog.isDebugEnabled() ? new LoggingSocketHolder(socket, this.id, this.wireLog) : new SocketHolder(socket));
super.bind(WIRE_LOG.isDebugEnabled() ? new LoggingSocketHolder(socket, this.id, WIRE_LOG) : new SocketHolder(socket));
socketTimeout = Timeout.ofMilliseconds(socket.getSoTimeout());
}
@Override
protected void onResponseReceived(final ClassicHttpResponse response) {
if (response != null && this.headerLog.isDebugEnabled()) {
this.headerLog.debug("{} << {}", this.id, new StatusLine(response));
if (response != null && HEADER_LOG.isDebugEnabled()) {
HEADER_LOG.debug("{} << {}", this.id, new StatusLine(response));
final Header[] headers = response.getHeaders();
for (final Header header : headers) {
this.headerLog.debug("{} << {}", this.id, header);
HEADER_LOG.debug("{} << {}", this.id, header);
}
}
}
@Override
protected void onRequestSubmitted(final ClassicHttpRequest request) {
if (request != null && this.headerLog.isDebugEnabled()) {
this.headerLog.debug("{} >> {}", this.id, new RequestLine(request));
if (request != null && HEADER_LOG.isDebugEnabled()) {
HEADER_LOG.debug("{} >> {}", this.id, new RequestLine(request));
final Header[] headers = request.getHeaders();
for (final Header header : headers) {
this.headerLog.debug("{} >> {}", this.id, header);
HEADER_LOG.debug("{} >> {}", this.id, header);
}
}
}

View File

@ -47,7 +47,7 @@ import org.slf4j.LoggerFactory;
*/
public class LenientHttpResponseParser extends DefaultHttpResponseParser {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(LenientHttpResponseParser.class);
/**
* Creates new instance of DefaultHttpResponseParser.
@ -84,8 +84,8 @@ public class LenientHttpResponseParser extends DefaultHttpResponseParser {
try {
return super.createMessage(buffer);
} catch (final HttpException ex) {
if (this.log.isDebugEnabled()) {
this.log.debug("Garbage in response: {}", buffer);
if (LOG.isDebugEnabled()) {
LOG.debug("Garbage in response: {}", buffer);
}
return null;
}

View File

@ -108,7 +108,7 @@ import org.slf4j.LoggerFactory;
public class PoolingHttpClientConnectionManager
implements HttpClientConnectionManager, ConnPoolControl<HttpRoute> {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(PoolingHttpClientConnectionManager.class);
public static final int DEFAULT_MAX_TOTAL_CONNECTIONS = 25;
public static final int DEFAULT_MAX_CONNECTIONS_PER_ROUTE = 5;
@ -231,11 +231,11 @@ public class PoolingHttpClientConnectionManager
@Override
public void close(final CloseMode closeMode) {
if (this.closed.compareAndSet(false, true)) {
if (this.log.isDebugEnabled()) {
this.log.debug("Shutdown connection pool {}", closeMode);
if (LOG.isDebugEnabled()) {
LOG.debug("Shutdown connection pool {}", closeMode);
}
this.pool.close(closeMode);
this.log.debug("Connection pool shut down");
LOG.debug("Connection pool shut down");
}
}
@ -257,8 +257,8 @@ public class PoolingHttpClientConnectionManager
final Timeout requestTimeout,
final Object state) {
Args.notNull(route, "HTTP route");
if (log.isDebugEnabled()) {
log.debug("{}: endpoint lease request ({}) {}", id, requestTimeout, ConnPoolSupport.formatStats(route, state, pool));
if (LOG.isDebugEnabled()) {
LOG.debug("{}: endpoint lease request ({}) {}", id, requestTimeout, ConnPoolSupport.formatStats(route, state, pool));
}
final Future<PoolEntry<HttpRoute, ManagedHttpClientConnection>> leaseFuture = this.pool.lease(route, state, requestTimeout, null);
return new LeaseRequest() {
@ -282,8 +282,8 @@ public class PoolingHttpClientConnectionManager
leaseFuture.cancel(true);
throw ex;
}
if (log.isDebugEnabled()) {
log.debug("{}: endpoint leased {}", id, ConnPoolSupport.formatStats(route, state, pool));
if (LOG.isDebugEnabled()) {
LOG.debug("{}: endpoint leased {}", id, ConnPoolSupport.formatStats(route, state, pool));
}
try {
if (TimeValue.isNonNegative(validateAfterInactivity)) {
@ -297,8 +297,8 @@ public class PoolingHttpClientConnectionManager
stale = true;
}
if (stale) {
if (log.isDebugEnabled()) {
log.debug("{}: connection {} is stale", id, ConnPoolSupport.getId(conn));
if (LOG.isDebugEnabled()) {
LOG.debug("{}: connection {} is stale", id, ConnPoolSupport.getId(conn));
}
poolEntry.discardConnection(CloseMode.IMMEDIATE);
}
@ -311,20 +311,20 @@ public class PoolingHttpClientConnectionManager
poolEntry.assignConnection(connFactory.createConnection(null));
}
if (leaseFuture.isCancelled()) {
if (log.isDebugEnabled()) {
log.debug("{}: endpoint lease cancelled", id);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: endpoint lease cancelled", id);
}
pool.release(poolEntry, false);
} else {
this.endpoint = new InternalConnectionEndpoint(poolEntry);
if (log.isDebugEnabled()) {
log.debug("{}: acquired {}", id, ConnPoolSupport.getId(endpoint));
if (LOG.isDebugEnabled()) {
LOG.debug("{}: acquired {}", id, ConnPoolSupport.getId(endpoint));
}
}
return this.endpoint;
} catch (final Exception ex) {
if (log.isDebugEnabled()) {
log.debug("{}: endpoint lease failed", id);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: endpoint lease failed", id);
}
pool.release(poolEntry, false);
throw new ExecutionException(ex.getMessage(), ex);
@ -347,8 +347,8 @@ public class PoolingHttpClientConnectionManager
if (entry == null) {
return;
}
if (log.isDebugEnabled()) {
log.debug("{}: releasing endpoint", ConnPoolSupport.getId(endpoint));
if (LOG.isDebugEnabled()) {
LOG.debug("{}: releasing endpoint", ConnPoolSupport.getId(endpoint));
}
final ManagedHttpClientConnection conn = entry.getConnection();
if (conn != null && keepAlive == null) {
@ -360,18 +360,18 @@ public class PoolingHttpClientConnectionManager
entry.updateState(state);
entry.updateExpiry(keepAlive);
conn.passivate();
if (this.log.isDebugEnabled()) {
if (LOG.isDebugEnabled()) {
final String s;
if (TimeValue.isPositive(keepAlive)) {
s = "for " + keepAlive;
} else {
s = "indefinitely";
}
log.debug("{}: connection {} can be kept alive {}", ConnPoolSupport.getId(endpoint), ConnPoolSupport.getId(conn), s);
LOG.debug("{}: connection {} can be kept alive {}", ConnPoolSupport.getId(endpoint), ConnPoolSupport.getId(conn), s);
}
} else {
if (this.log.isDebugEnabled()) {
this.log.debug("{}: connection is not kept alive", ConnPoolSupport.getId(endpoint));
if (LOG.isDebugEnabled()) {
LOG.debug("{}: connection is not kept alive", ConnPoolSupport.getId(endpoint));
}
}
} catch (final RuntimeException ex) {
@ -379,8 +379,8 @@ public class PoolingHttpClientConnectionManager
throw ex;
} finally {
this.pool.release(entry, reusable);
if (this.log.isDebugEnabled()) {
log.debug("{}: connection released {}", ConnPoolSupport.getId(endpoint), ConnPoolSupport.formatStats(entry.getRoute(), entry.getState(), pool));
if (LOG.isDebugEnabled()) {
LOG.debug("{}: connection released {}", ConnPoolSupport.getId(endpoint), ConnPoolSupport.formatStats(entry.getRoute(), entry.getState(), pool));
}
}
}
@ -403,8 +403,8 @@ public class PoolingHttpClientConnectionManager
} else {
host = route.getTargetHost();
}
if (this.log.isDebugEnabled()) {
log.debug("{}: connecting endpoint to {} ({})", ConnPoolSupport.getId(endpoint), host, connectTimeout);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: connecting endpoint to {} ({})", ConnPoolSupport.getId(endpoint), host, connectTimeout);
}
final ManagedHttpClientConnection conn = poolEntry.getConnection();
this.connectionOperator.connect(
@ -414,8 +414,8 @@ public class PoolingHttpClientConnectionManager
connectTimeout,
defaultSocketConfig != null ? this.defaultSocketConfig : SocketConfig.DEFAULT,
context);
if (log.isDebugEnabled()) {
log.debug("{}: connected {}", ConnPoolSupport.getId(endpoint), ConnPoolSupport.getId(conn));
if (LOG.isDebugEnabled()) {
LOG.debug("{}: connected {}", ConnPoolSupport.getId(endpoint), ConnPoolSupport.getId(conn));
}
}
@ -431,15 +431,15 @@ public class PoolingHttpClientConnectionManager
@Override
public void closeIdle(final TimeValue idleTime) {
Args.notNull(idleTime, "Idle time");
if (this.log.isDebugEnabled()) {
this.log.debug("Closing connections idle longer than {}", idleTime);
if (LOG.isDebugEnabled()) {
LOG.debug("Closing connections idle longer than {}", idleTime);
}
this.pool.closeIdle(idleTime);
}
@Override
public void closeExpired() {
this.log.debug("Closing expired connections");
LOG.debug("Closing expired connections");
this.pool.closeExpired();
}
@ -591,8 +591,8 @@ public class PoolingHttpClientConnectionManager
Args.notNull(request, "HTTP request");
Args.notNull(requestExecutor, "Request executor");
final ManagedHttpClientConnection connection = getValidatedPoolEntry().getConnection();
if (log.isDebugEnabled()) {
log.debug("{}: executing exchange {} over {}", id, exchangeId, ConnPoolSupport.getId(connection));
if (LOG.isDebugEnabled()) {
LOG.debug("{}: executing exchange {} over {}", id, exchangeId, ConnPoolSupport.getId(connection));
}
return requestExecutor.execute(request, connection, context);
}

View File

@ -57,7 +57,7 @@ import org.slf4j.LoggerFactory;
final class DefaultManagedAsyncClientConnection implements ManagedAsyncClientConnection, Identifiable {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(DefaultManagedAsyncClientConnection.class);
private final IOSession ioSession;
private final Timeout socketTimeout;
@ -77,8 +77,8 @@ final class DefaultManagedAsyncClientConnection implements ManagedAsyncClientCon
@Override
public void close(final CloseMode closeMode) {
if (this.closed.compareAndSet(false, true)) {
if (log.isDebugEnabled()) {
log.debug("{}: Shutdown connection {}", getId(), closeMode);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: Shutdown connection {}", getId(), closeMode);
}
ioSession.close(closeMode);
}
@ -87,8 +87,8 @@ final class DefaultManagedAsyncClientConnection implements ManagedAsyncClientCon
@Override
public void close() throws IOException {
if (this.closed.compareAndSet(false, true)) {
if (log.isDebugEnabled()) {
log.debug("{}: Close connection", getId());
if (LOG.isDebugEnabled()) {
LOG.debug("{}: Close connection", getId());
}
ioSession.enqueue(new ShutdownCommand(CloseMode.GRACEFUL), Command.Priority.IMMEDIATE);
}
@ -145,8 +145,8 @@ final class DefaultManagedAsyncClientConnection implements ManagedAsyncClientCon
final SSLSessionInitializer initializer,
final SSLSessionVerifier verifier,
final Timeout handshakeTimeout) throws UnsupportedOperationException {
if (log.isDebugEnabled()) {
log.debug("{}: start TLS", getId());
if (LOG.isDebugEnabled()) {
LOG.debug("{}: start TLS", getId());
}
if (ioSession instanceof TransportSecurityLayer) {
((TransportSecurityLayer) ioSession).startTls(sslContext, endpoint, sslBufferMode, initializer, verifier,
@ -169,8 +169,8 @@ final class DefaultManagedAsyncClientConnection implements ManagedAsyncClientCon
@Override
public void submitCommand(final Command command, final Command.Priority priority) {
if (log.isDebugEnabled()) {
log.debug("{}: {} with {} priority", getId(), command.getClass().getSimpleName(), priority);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: {} with {} priority", getId(), command.getClass().getSimpleName(), priority);
}
ioSession.enqueue(command, Command.Priority.IMMEDIATE);
}

View File

@ -50,7 +50,7 @@ import org.slf4j.LoggerFactory;
final class MultihomeIOSessionRequester {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(MultihomeIOSessionRequester.class);
private final DnsResolver dnsResolver;
MultihomeIOSessionRequester(final DnsResolver dnsResolver) {
@ -67,14 +67,14 @@ final class MultihomeIOSessionRequester {
final FutureCallback<IOSession> callback) {
if (remoteAddress != null) {
if (log.isDebugEnabled()) {
log.debug("{}: connecting {} to {} ({})", remoteEndpoint, localAddress, remoteAddress, connectTimeout);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: connecting {} to {} ({})", remoteEndpoint, localAddress, remoteAddress, connectTimeout);
}
return connectionInitiator.connect(remoteEndpoint, remoteAddress, localAddress, connectTimeout, attachment, callback);
}
if (log.isDebugEnabled()) {
log.debug("{}: resolving remote address", remoteEndpoint);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: resolving remote address", remoteEndpoint);
}
final ComplexFuture<IOSession> future = new ComplexFuture<>(callback);
@ -86,8 +86,8 @@ final class MultihomeIOSessionRequester {
return future;
}
if (log.isDebugEnabled()) {
log.debug("{}: resolved to {}", remoteEndpoint, Arrays.asList(remoteAddresses));
if (LOG.isDebugEnabled()) {
LOG.debug("{}: resolved to {}", remoteEndpoint, Arrays.asList(remoteAddresses));
}
final Runnable runnable = new Runnable() {
@ -98,8 +98,8 @@ final class MultihomeIOSessionRequester {
final int index = attempt.getAndIncrement();
final InetSocketAddress remoteAddress = new InetSocketAddress(remoteAddresses[index], remoteEndpoint.getPort());
if (log.isDebugEnabled()) {
log.debug("{}: connecting {} to {} ({})", remoteEndpoint, localAddress, remoteAddress, connectTimeout);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: connecting {} to {} ({})", remoteEndpoint, localAddress, remoteAddress, connectTimeout);
}
final Future<IOSession> sessionFuture = connectionInitiator.connect(
@ -112,9 +112,9 @@ final class MultihomeIOSessionRequester {
@Override
public void completed(final IOSession session) {
if (log.isDebugEnabled()) {
if (log.isDebugEnabled()) {
log.debug("{}: connected {} {}->{}", remoteEndpoint, session.getId(), session.getLocalAddress(), session.getRemoteAddress());
if (LOG.isDebugEnabled()) {
if (LOG.isDebugEnabled()) {
LOG.debug("{}: connected {} {}->{}", remoteEndpoint, session.getId(), session.getLocalAddress(), session.getRemoteAddress());
}
}
future.completed(session);
@ -123,8 +123,8 @@ final class MultihomeIOSessionRequester {
@Override
public void failed(final Exception cause) {
if (attempt.get() >= remoteAddresses.length) {
if (log.isDebugEnabled()) {
log.debug("{}: connection to {} failed ({}); terminating operation", remoteEndpoint, remoteAddress, cause.getClass());
if (LOG.isDebugEnabled()) {
LOG.debug("{}: connection to {} failed ({}); terminating operation", remoteEndpoint, remoteAddress, cause.getClass());
}
if (cause instanceof IOException) {
future.failed(ConnectExceptionSupport.enhance((IOException) cause, remoteEndpoint, remoteAddresses));
@ -132,8 +132,8 @@ final class MultihomeIOSessionRequester {
future.failed(cause);
}
} else {
if (log.isDebugEnabled()) {
log.debug("{}: connection to {} failed ({}); retrying connection to the next address", remoteEndpoint, remoteAddress, cause.getClass());
if (LOG.isDebugEnabled()) {
LOG.debug("{}: connection to {} failed ({}); retrying connection to the next address", remoteEndpoint, remoteAddress, cause.getClass());
}
executeNext();
}

View File

@ -103,7 +103,7 @@ import org.slf4j.LoggerFactory;
@Contract(threading = ThreadingBehavior.SAFE_CONDITIONAL)
public class PoolingAsyncClientConnectionManager implements AsyncClientConnectionManager, ConnPoolControl<HttpRoute> {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(PoolingAsyncClientConnectionManager.class);
public static final int DEFAULT_MAX_TOTAL_CONNECTIONS = 25;
public static final int DEFAULT_MAX_CONNECTIONS_PER_ROUTE = 5;
@ -196,11 +196,11 @@ public class PoolingAsyncClientConnectionManager implements AsyncClientConnectio
@Override
public void close(final CloseMode closeMode) {
if (this.closed.compareAndSet(false, true)) {
if (this.log.isDebugEnabled()) {
this.log.debug("Shutdown connection pool {}", closeMode);
if (LOG.isDebugEnabled()) {
LOG.debug("Shutdown connection pool {}", closeMode);
}
this.pool.close(closeMode);
this.log.debug("Connection pool shut down");
LOG.debug("Connection pool shut down");
}
}
@ -218,8 +218,8 @@ public class PoolingAsyncClientConnectionManager implements AsyncClientConnectio
final Object state,
final Timeout requestTimeout,
final FutureCallback<AsyncConnectionEndpoint> callback) {
if (log.isDebugEnabled()) {
log.debug("{}: endpoint lease request ({}) {}", id, requestTimeout, ConnPoolSupport.formatStats(route, state, pool));
if (LOG.isDebugEnabled()) {
LOG.debug("{}: endpoint lease request ({}) {}", id, requestTimeout, ConnPoolSupport.formatStats(route, state, pool));
}
final ComplexFuture<AsyncConnectionEndpoint> resultFuture = new ComplexFuture<>(callback);
final Future<PoolEntry<HttpRoute, ManagedAsyncClientConnection>> leaseFuture = pool.lease(
@ -230,12 +230,12 @@ public class PoolingAsyncClientConnectionManager implements AsyncClientConnectio
if (connection != null) {
connection.activate();
}
if (log.isDebugEnabled()) {
log.debug("{}: endpoint leased {}", id, ConnPoolSupport.formatStats(route, state, pool));
if (LOG.isDebugEnabled()) {
LOG.debug("{}: endpoint leased {}", id, ConnPoolSupport.formatStats(route, state, pool));
}
final AsyncConnectionEndpoint endpoint = new InternalConnectionEndpoint(poolEntry);
if (log.isDebugEnabled()) {
log.debug("{}: acquired {}", id, ConnPoolSupport.getId(endpoint));
if (LOG.isDebugEnabled()) {
LOG.debug("{}: acquired {}", id, ConnPoolSupport.getId(endpoint));
}
resultFuture.completed(endpoint);
}
@ -253,8 +253,8 @@ public class PoolingAsyncClientConnectionManager implements AsyncClientConnectio
@Override
public void execute(final Boolean result) {
if (result == null || !result) {
if (log.isDebugEnabled()) {
log.debug("{}: connection {} is stale", id, ConnPoolSupport.getId(connection));
if (LOG.isDebugEnabled()) {
LOG.debug("{}: connection {} is stale", id, ConnPoolSupport.getId(connection));
}
poolEntry.discardConnection(CloseMode.IMMEDIATE);
}
@ -264,8 +264,8 @@ public class PoolingAsyncClientConnectionManager implements AsyncClientConnectio
})), Command.Priority.IMMEDIATE);
} else {
if (!connection.isOpen()) {
if (log.isDebugEnabled()) {
log.debug("{}: connection {} is closed", id, ConnPoolSupport.getId(connection));
if (LOG.isDebugEnabled()) {
LOG.debug("{}: connection {} is closed", id, ConnPoolSupport.getId(connection));
}
poolEntry.discardConnection(CloseMode.IMMEDIATE);
}
@ -278,16 +278,16 @@ public class PoolingAsyncClientConnectionManager implements AsyncClientConnectio
@Override
public void failed(final Exception ex) {
if (log.isDebugEnabled()) {
log.debug("{}: endpoint lease failed", id);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: endpoint lease failed", id);
}
resultFuture.failed(ex);
}
@Override
public void cancelled() {
if (log.isDebugEnabled()) {
log.debug("{}: endpoint lease cancelled", id);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: endpoint lease cancelled", id);
}
resultFuture.cancel();
}
@ -306,8 +306,8 @@ public class PoolingAsyncClientConnectionManager implements AsyncClientConnectio
if (entry == null) {
return;
}
if (log.isDebugEnabled()) {
log.debug("{}: releasing endpoint", ConnPoolSupport.getId(endpoint));
if (LOG.isDebugEnabled()) {
LOG.debug("{}: releasing endpoint", ConnPoolSupport.getId(endpoint));
}
final ManagedAsyncClientConnection connection = entry.getConnection();
boolean reusable = connection != null && connection.isOpen();
@ -316,14 +316,14 @@ public class PoolingAsyncClientConnectionManager implements AsyncClientConnectio
entry.updateState(state);
entry.updateExpiry(keepAlive);
connection.passivate();
if (log.isDebugEnabled()) {
if (LOG.isDebugEnabled()) {
final String s;
if (TimeValue.isPositive(keepAlive)) {
s = "for " + keepAlive;
} else {
s = "indefinitely";
}
log.debug("{}: connection {} can be kept alive {}", ConnPoolSupport.getId(endpoint), ConnPoolSupport.getId(connection), s);
LOG.debug("{}: connection {} can be kept alive {}", ConnPoolSupport.getId(endpoint), ConnPoolSupport.getId(connection), s);
}
}
} catch (final RuntimeException ex) {
@ -331,8 +331,8 @@ public class PoolingAsyncClientConnectionManager implements AsyncClientConnectio
throw ex;
} finally {
pool.release(entry, reusable);
if (log.isDebugEnabled()) {
log.debug("{}: connection released {}", ConnPoolSupport.getId(endpoint), ConnPoolSupport.formatStats(entry.getRoute(), entry.getState(), pool));
if (LOG.isDebugEnabled()) {
LOG.debug("{}: connection released {}", ConnPoolSupport.getId(endpoint), ConnPoolSupport.formatStats(entry.getRoute(), entry.getState(), pool));
}
}
}
@ -363,8 +363,8 @@ public class PoolingAsyncClientConnectionManager implements AsyncClientConnectio
host = route.getTargetHost();
}
final InetSocketAddress localAddress = route.getLocalSocketAddress();
if (this.log.isDebugEnabled()) {
log.debug("{}: connecting endpoint to {} ({})", ConnPoolSupport.getId(endpoint), host, connectTimeout);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: connecting endpoint to {} ({})", ConnPoolSupport.getId(endpoint), host, connectTimeout);
}
final Future<ManagedAsyncClientConnection> connectFuture = connectionOperator.connect(
connectionInitiator, host, localAddress, connectTimeout, attachment, new FutureCallback<ManagedAsyncClientConnection>() {
@ -372,8 +372,8 @@ public class PoolingAsyncClientConnectionManager implements AsyncClientConnectio
@Override
public void completed(final ManagedAsyncClientConnection connection) {
try {
if (log.isDebugEnabled()) {
log.debug("{}: connected {}", ConnPoolSupport.getId(endpoint), ConnPoolSupport.getId(connection));
if (LOG.isDebugEnabled()) {
LOG.debug("{}: connected {}", ConnPoolSupport.getId(endpoint), ConnPoolSupport.getId(connection));
}
poolEntry.assignConnection(connection);
resultFuture.completed(internalEndpoint);
@ -408,8 +408,8 @@ public class PoolingAsyncClientConnectionManager implements AsyncClientConnectio
final HttpRoute route = poolEntry.getRoute();
final ManagedAsyncClientConnection connection = poolEntry.getConnection();
connectionOperator.upgrade(poolEntry.getConnection(), route.getTargetHost(), attachment);
if (log.isDebugEnabled()) {
log.debug("{}: upgraded {}", ConnPoolSupport.getId(internalEndpoint), ConnPoolSupport.getId(connection));
if (LOG.isDebugEnabled()) {
LOG.debug("{}: upgraded {}", ConnPoolSupport.getId(internalEndpoint), ConnPoolSupport.getId(connection));
}
}
@ -523,8 +523,8 @@ public class PoolingAsyncClientConnectionManager implements AsyncClientConnectio
public void close(final CloseMode closeMode) {
final PoolEntry<HttpRoute, ManagedAsyncClientConnection> poolEntry = poolEntryRef.get();
if (poolEntry != null) {
if (log.isDebugEnabled()) {
log.debug("{}: close {}", id, closeMode);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: close {}", id, closeMode);
}
poolEntry.discardConnection(closeMode);
}
@ -559,8 +559,8 @@ public class PoolingAsyncClientConnectionManager implements AsyncClientConnectio
final HandlerFactory<AsyncPushConsumer> pushHandlerFactory,
final HttpContext context) {
final ManagedAsyncClientConnection connection = getValidatedPoolEntry().getConnection();
if (log.isDebugEnabled()) {
log.debug("{}: executing exchange {} over {}", id, exchangeId, ConnPoolSupport.getId(connection));
if (LOG.isDebugEnabled()) {
LOG.debug("{}: executing exchange {} over {}", id, exchangeId, ConnPoolSupport.getId(connection));
}
connection.submitCommand(
new RequestExecutionCommand(exchangeHandler, pushHandlerFactory, context),

View File

@ -65,7 +65,7 @@ import org.slf4j.LoggerFactory;
@Contract(threading = ThreadingBehavior.STATELESS)
public class RequestAddCookies implements HttpRequestInterceptor {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(RequestAddCookies.class);
public RequestAddCookies() {
super();
@ -87,21 +87,21 @@ public class RequestAddCookies implements HttpRequestInterceptor {
// Obtain cookie store
final CookieStore cookieStore = clientContext.getCookieStore();
if (cookieStore == null) {
this.log.debug("Cookie store not specified in HTTP context");
LOG.debug("Cookie store not specified in HTTP context");
return;
}
// Obtain the registry of cookie specs
final Lookup<CookieSpecFactory> registry = clientContext.getCookieSpecRegistry();
if (registry == null) {
this.log.debug("CookieSpec registry not specified in HTTP context");
LOG.debug("CookieSpec registry not specified in HTTP context");
return;
}
// Obtain the route (required)
final RouteInfo route = clientContext.getHttpRoute();
if (route == null) {
this.log.debug("Connection route not set in the context");
LOG.debug("Connection route not set in the context");
return;
}
@ -110,8 +110,8 @@ public class RequestAddCookies implements HttpRequestInterceptor {
if (cookieSpecName == null) {
cookieSpecName = StandardCookieSpec.STRICT;
}
if (this.log.isDebugEnabled()) {
this.log.debug("Cookie spec selected: {}", cookieSpecName);
if (LOG.isDebugEnabled()) {
LOG.debug("Cookie spec selected: {}", cookieSpecName);
}
final URIAuthority authority = request.getAuthority();
@ -132,8 +132,8 @@ public class RequestAddCookies implements HttpRequestInterceptor {
// Get an instance of the selected cookie policy
final CookieSpecFactory factory = registry.lookup(cookieSpecName);
if (factory == null) {
if (this.log.isDebugEnabled()) {
this.log.debug("Unsupported cookie spec: {}", cookieSpecName);
if (LOG.isDebugEnabled()) {
LOG.debug("Unsupported cookie spec: {}", cookieSpecName);
}
return;
@ -148,14 +148,14 @@ public class RequestAddCookies implements HttpRequestInterceptor {
for (final Cookie cookie : cookies) {
if (!cookie.isExpired(now)) {
if (cookieSpec.match(cookie, cookieOrigin)) {
if (this.log.isDebugEnabled()) {
this.log.debug("Cookie {} match {}", cookie, cookieOrigin);
if (LOG.isDebugEnabled()) {
LOG.debug("Cookie {} match {}", cookie, cookieOrigin);
}
matchedCookies.add(cookie);
}
} else {
if (this.log.isDebugEnabled()) {
this.log.debug("Cookie {} expired", cookie);
if (LOG.isDebugEnabled()) {
LOG.debug("Cookie {} expired", cookie);
}
expired = true;
}

View File

@ -57,7 +57,7 @@ import org.slf4j.LoggerFactory;
@Contract(threading = ThreadingBehavior.STATELESS)
public class RequestAuthCache implements HttpRequestInterceptor {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(RequestAuthCache.class);
public RequestAuthCache() {
super();
@ -73,19 +73,19 @@ public class RequestAuthCache implements HttpRequestInterceptor {
final AuthCache authCache = clientContext.getAuthCache();
if (authCache == null) {
this.log.debug("Auth cache not set in the context");
LOG.debug("Auth cache not set in the context");
return;
}
final CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
if (credsProvider == null) {
this.log.debug("Credentials provider not set in the context");
LOG.debug("Credentials provider not set in the context");
return;
}
final RouteInfo route = clientContext.getHttpRoute();
if (route == null) {
this.log.debug("Route info not set in the context");
LOG.debug("Route info not set in the context");
return;
}
@ -103,8 +103,8 @@ public class RequestAuthCache implements HttpRequestInterceptor {
if (targetAuthExchange.getState() == AuthExchange.State.UNCHALLENGED) {
final AuthScheme authScheme = authCache.get(target);
if (authScheme != null) {
if (this.log.isDebugEnabled()) {
this.log.debug("Re-using cached '{}' auth scheme for {}", authScheme.getName(), target);
if (LOG.isDebugEnabled()) {
LOG.debug("Re-using cached '{}' auth scheme for {}", authScheme.getName(), target);
}
targetAuthExchange.select(authScheme);
}
@ -116,8 +116,8 @@ public class RequestAuthCache implements HttpRequestInterceptor {
if (proxyAuthExchange.getState() == AuthExchange.State.UNCHALLENGED) {
final AuthScheme authScheme = authCache.get(proxy);
if (authScheme != null) {
if (this.log.isDebugEnabled()) {
this.log.debug("Re-using cached '{}' auth scheme for {}", authScheme.getName(), proxy);
if (LOG.isDebugEnabled()) {
LOG.debug("Re-using cached '{}' auth scheme for {}", authScheme.getName(), proxy);
}
proxyAuthExchange.select(authScheme);
}

View File

@ -53,7 +53,7 @@ import org.slf4j.LoggerFactory;
@Contract(threading = ThreadingBehavior.STATELESS)
public class RequestClientConnControl implements HttpRequestInterceptor {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(RequestClientConnControl.class);
public RequestClientConnControl() {
super();
@ -74,7 +74,7 @@ public class RequestClientConnControl implements HttpRequestInterceptor {
// Obtain the client connection (required)
final RouteInfo route = clientContext.getHttpRoute();
if (route == null) {
this.log.debug("Connection route not set in the context");
LOG.debug("Connection route not set in the context");
return;
}

View File

@ -57,7 +57,7 @@ import org.slf4j.LoggerFactory;
@Contract(threading = ThreadingBehavior.STATELESS)
public class ResponseProcessCookies implements HttpResponseInterceptor {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(ResponseProcessCookies.class);
public ResponseProcessCookies() {
super();
@ -74,19 +74,19 @@ public class ResponseProcessCookies implements HttpResponseInterceptor {
// Obtain actual CookieSpec instance
final CookieSpec cookieSpec = clientContext.getCookieSpec();
if (cookieSpec == null) {
this.log.debug("Cookie spec not specified in HTTP context");
LOG.debug("Cookie spec not specified in HTTP context");
return;
}
// Obtain cookie store
final CookieStore cookieStore = clientContext.getCookieStore();
if (cookieStore == null) {
this.log.debug("Cookie store not specified in HTTP context");
LOG.debug("Cookie store not specified in HTTP context");
return;
}
// Obtain actual CookieOrigin instance
final CookieOrigin cookieOrigin = clientContext.getCookieOrigin();
if (cookieOrigin == null) {
this.log.debug("Cookie origin not specified in HTTP context");
LOG.debug("Cookie origin not specified in HTTP context");
return;
}
final Iterator<Header> it = response.headerIterator("Set-Cookie");
@ -107,18 +107,18 @@ public class ResponseProcessCookies implements HttpResponseInterceptor {
cookieSpec.validate(cookie, cookieOrigin);
cookieStore.addCookie(cookie);
if (this.log.isDebugEnabled()) {
this.log.debug("Cookie accepted [{}]", formatCooke(cookie));
if (LOG.isDebugEnabled()) {
LOG.debug("Cookie accepted [{}]", formatCooke(cookie));
}
} catch (final MalformedCookieException ex) {
if (this.log.isWarnEnabled()) {
this.log.warn("Cookie rejected [{}] {}", formatCooke(cookie), ex.getMessage());
if (LOG.isWarnEnabled()) {
LOG.warn("Cookie rejected [{}] {}", formatCooke(cookie), ex.getMessage());
}
}
}
} catch (final MalformedCookieException ex) {
if (this.log.isWarnEnabled()) {
this.log.warn("Invalid cookie header: \"{}\". {}", header, ex.getMessage());
if (LOG.isWarnEnabled()) {
LOG.warn("Invalid cookie header: \"{}\". {}", header, ex.getMessage());
}
}
}

View File

@ -50,6 +50,8 @@ import org.slf4j.LoggerFactory;
@Contract(threading = ThreadingBehavior.SAFE)
public final class PublicSuffixMatcherLoader {
private static final Logger LOG = LoggerFactory.getLogger(PublicSuffixMatcherLoader.class);
private static PublicSuffixMatcher load(final InputStream in) throws IOException {
final List<PublicSuffixList> lists = new PublicSuffixListParser().parseByType(
new InputStreamReader(in, StandardCharsets.UTF_8));
@ -83,10 +85,7 @@ public final class PublicSuffixMatcherLoader {
DEFAULT_INSTANCE = load(url);
} catch (final IOException ex) {
// Should never happen
final Logger log = LoggerFactory.getLogger(PublicSuffixMatcherLoader.class);
if (log.isWarnEnabled()) {
log.warn("Failure loading public suffix list from default resource", ex);
}
LOG.warn("Failure loading public suffix list from default resource", ex);
}
} else {
DEFAULT_INSTANCE = new PublicSuffixMatcher(DomainType.ICANN, Arrays.asList("com"), null);

View File

@ -61,7 +61,7 @@ import org.slf4j.LoggerFactory;
@Contract(threading = ThreadingBehavior.STATELESS)
abstract class AbstractClientTlsStrategy implements TlsStrategy {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(AbstractClientTlsStrategy.class);
private final SSLContext sslContext;
private final String[] supportedProtocols;
@ -82,7 +82,7 @@ abstract class AbstractClientTlsStrategy implements TlsStrategy {
this.supportedCipherSuites = supportedCipherSuites;
this.sslBufferManagement = sslBufferManagement != null ? sslBufferManagement : SSLBufferMode.STATIC;
this.hostnameVerifier = hostnameVerifier != null ? hostnameVerifier : HttpsSupport.getDefaultHostnameVerifier();
this.tlsSessionValidator = new TlsSessionValidator(log);
this.tlsSessionValidator = new TlsSessionValidator(LOG);
}
@Override
@ -121,9 +121,9 @@ abstract class AbstractClientTlsStrategy implements TlsStrategy {
initializeEngine(sslEngine);
if (log.isDebugEnabled()) {
log.debug("Enabled protocols: {}", Arrays.asList(sslEngine.getEnabledProtocols()));
log.debug("Enabled cipher suites:{}", Arrays.asList(sslEngine.getEnabledCipherSuites()));
if (LOG.isDebugEnabled()) {
LOG.debug("Enabled protocols: {}", Arrays.asList(sslEngine.getEnabledProtocols()));
LOG.debug("Enabled cipher suites:{}", Arrays.asList(sslEngine.getEnabledCipherSuites()));
}
}

View File

@ -73,7 +73,7 @@ public final class DefaultHostnameVerifier implements HttpClientHostnameVerifier
}
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(DefaultHostnameVerifier.class);
private final PublicSuffixMatcher publicSuffixMatcher;
@ -93,8 +93,8 @@ public final class DefaultHostnameVerifier implements HttpClientHostnameVerifier
verify(host, x509);
return true;
} catch (final SSLException ex) {
if (log.isDebugEnabled()) {
log.debug(ex.getMessage(), ex);
if (LOG.isDebugEnabled()) {
LOG.debug(ex.getMessage(), ex);
}
return false;
}

View File

@ -83,7 +83,7 @@ public class SSLConnectionSocketFactory implements LayeredConnectionSocketFactor
Pattern.compile(WEAK_KEY_EXCHANGES, Pattern.CASE_INSENSITIVE),
Pattern.compile(WEAK_CIPHERS, Pattern.CASE_INSENSITIVE)));
private final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(SSLConnectionSocketFactory.class);
/**
* Obtains default SSL socket factory with an SSL context based on the standard JSSE
@ -173,7 +173,7 @@ public class SSLConnectionSocketFactory implements LayeredConnectionSocketFactor
this.supportedProtocols = supportedProtocols;
this.supportedCipherSuites = supportedCipherSuites;
this.hostnameVerifier = hostnameVerifier != null ? hostnameVerifier : HttpsSupport.getDefaultHostnameVerifier();
this.tlsSessionValidator = new TlsSessionValidator(log);
this.tlsSessionValidator = new TlsSessionValidator(LOG);
}
/**
@ -210,8 +210,8 @@ public class SSLConnectionSocketFactory implements LayeredConnectionSocketFactor
if (TimeValue.isPositive(connectTimeout) && sock.getSoTimeout() == 0) {
sock.setSoTimeout(connectTimeout.toMillisecondsIntBound());
}
if (this.log.isDebugEnabled()) {
this.log.debug("Connecting socket to {} with timeout {}", remoteAddress, connectTimeout);
if (LOG.isDebugEnabled()) {
LOG.debug("Connecting socket to {} with timeout {}", remoteAddress, connectTimeout);
}
// Run this under a doPrivileged to support lib users that run under a SecurityManager this allows granting connect permissions
// only to this library
@ -236,7 +236,7 @@ public class SSLConnectionSocketFactory implements LayeredConnectionSocketFactor
// Setup SSL layering if necessary
if (sock instanceof SSLSocket) {
final SSLSocket sslsock = (SSLSocket) sock;
this.log.debug("Starting handshake");
LOG.debug("Starting handshake");
sslsock.startHandshake();
verifyHostname(sslsock, host.getHostName());
return sock;
@ -266,13 +266,13 @@ public class SSLConnectionSocketFactory implements LayeredConnectionSocketFactor
sslsock.setEnabledCipherSuites(TlsCiphers.excludeWeak(sslsock.getEnabledCipherSuites()));
}
if (this.log.isDebugEnabled()) {
this.log.debug("Enabled protocols: {}", Arrays.asList(sslsock.getEnabledProtocols()));
this.log.debug("Enabled cipher suites:{}", Arrays.asList(sslsock.getEnabledCipherSuites()));
if (LOG.isDebugEnabled()) {
LOG.debug("Enabled protocols: {}", (Object) sslsock.getEnabledProtocols());
LOG.debug("Enabled cipher suites: {}", (Object) sslsock.getEnabledCipherSuites());
}
prepareSocket(sslsock);
this.log.debug("Starting handshake");
LOG.debug("Starting handshake");
sslsock.startHandshake();
verifyHostname(sslsock, target);
return sslsock;