From 25f080f3079a45939b845af31acb8e7fdd48c360 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 26 Aug 2024 11:29:09 -0400 Subject: [PATCH] Private method does not throw checked exception - Remove it from the private method signatures - Remove exception handling no longer needed - Add missing @Override - No need to nest in an else clause (reduce clutter) - Use ternary expression - public methods in a package-private class can be package-private --- .../AbstractSerializingCacheStorage.java | 3 +- .../http/impl/cache/AsyncCachingExec.java | 14 +- .../http/impl/cache/BasicHttpAsyncCache.java | 58 +++---- .../http/impl/cache/BasicHttpCache.java | 40 +++-- .../cache/CacheControlHeaderGenerator.java | 3 +- .../http/impl/cache/CacheKeyGenerator.java | 45 +++-- .../client5/http/impl/cache/CacheSupport.java | 3 +- .../http/impl/cache/CacheValidityPolicy.java | 3 +- .../CachedResponseSuitabilityChecker.java | 27 ++- .../client5/http/impl/cache/CachingExec.java | 160 +++++++++--------- .../http/impl/cache/CachingExecBase.java | 3 +- .../http/impl/cache/FileResourceFactory.java | 6 +- .../client5/http/impl/cache/HeapResource.java | 6 +- .../http/impl/cache/InternalCacheStorage.java | 3 +- .../impl/cache/ResponseCachingPolicy.java | 9 +- .../async/AuthenticatingAsyncDecorator.java | 3 +- .../async/RedirectingAsyncDecorator.java | 6 +- .../ServiceUnavailableAsyncDecorator.java | 6 +- .../auth/AbstractAuthenticationHandler.java | 3 +- .../testing/BasicTestAuthenticator.java | 12 +- .../extension/async/TestAsyncServer.java | 3 +- .../client5/testing/sync/TestRedirects.java | 5 +- .../impl/DefaultHttpRequestRetryStrategy.java | 9 +- .../hc/client5/http/impl/RequestSupport.java | 15 +- .../http/impl/async/AsyncConnectExec.java | 117 ++++++------- .../async/InternalH2AsyncExecRuntime.java | 1 + .../async/InternalHttpAsyncExecRuntime.java | 1 + .../http/impl/async/LoggingIOSession.java | 2 +- .../http/impl/auth/NTLMEngineImpl.java | 94 +++++----- .../examples/AsyncClientConnectionConfig.java | 16 +- .../http/examples/ClientConfiguration.java | 3 +- .../http/examples/ClientConnectionConfig.java | 16 +- .../http/examples/ClientInterceptors.java | 3 +- .../impl/classic/MockConnPoolControl.java | 6 +- 34 files changed, 316 insertions(+), 388 deletions(-) diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/AbstractSerializingCacheStorage.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/AbstractSerializingCacheStorage.java index c0b683a01..108f9a621 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/AbstractSerializingCacheStorage.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/AbstractSerializingCacheStorage.java @@ -89,9 +89,8 @@ public abstract class AbstractSerializingCacheStorage implements HttpCac final HttpCacheStorageEntry entry = serializer.deserialize(storageObject); if (key.equals(entry.getKey())) { return entry.getContent(); - } else { - return null; } + return null; } @Override diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/AsyncCachingExec.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/AsyncCachingExec.java index 074529e41..83941c17d 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/AsyncCachingExec.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/AsyncCachingExec.java @@ -534,12 +534,11 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler exchangeId, asyncExecCallback, backendResponse, entityDetails); cachingConsumerRef.set(cachingDataConsumer); return cachingDataConsumer; - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("{} backend response is not cacheable", exchangeId); - } - return asyncExecCallback.handleResponse(backendResponse, entityDetails); } + if (LOG.isDebugEnabled()) { + LOG.debug("{} backend response is not cacheable", exchangeId); + } + return asyncExecCallback.handleResponse(backendResponse, entityDetails); } @Override @@ -1079,10 +1078,9 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler LOG.debug("{} serving stale response due to {} status and stale-if-error enabled", exchangeId, status); } return null; - } else { - committed.set(response); - return asyncExecCallback.handleResponse(response, entityDetails); } + committed.set(response); + return asyncExecCallback.handleResponse(response, entityDetails); } @Override diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/BasicHttpAsyncCache.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/BasicHttpAsyncCache.java index 7a5157e9a..7cb421795 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/BasicHttpAsyncCache.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/BasicHttpAsyncCache.java @@ -144,9 +144,8 @@ class BasicHttpAsyncCache implements HttpAsyncCache { })); return; - } else { - callback.completed(new CacheMatch(null, new CacheHit(rootKey, root))); } + callback.completed(new CacheMatch(null, new CacheHit(rootKey, root))); } else { callback.completed(new CacheMatch(new CacheHit(rootKey, root), null)); } @@ -350,39 +349,38 @@ class BasicHttpAsyncCache implements HttpAsyncCache { } }); - } else { - final String variantCacheKey = variantKey + rootKey; + } + final String variantCacheKey = variantKey + rootKey; - if (LOG.isDebugEnabled()) { - LOG.debug("Store variant entry in cache: {}", variantCacheKey); - } + if (LOG.isDebugEnabled()) { + LOG.debug("Store variant entry in cache: {}", variantCacheKey); + } - return storeInternal(variantCacheKey, entry, new CallbackContribution(callback) { + return storeInternal(variantCacheKey, entry, new CallbackContribution(callback) { - @Override - public void completed(final Boolean result) { - if (LOG.isDebugEnabled()) { - LOG.debug("Update root entry: {}", rootKey); - } - - updateInternal(rootKey, - existing -> { - final Set variantMap = existing != null ? new HashSet<>(existing.getVariants()) : new HashSet<>(); - variantMap.add(variantKey); - return cacheEntryFactory.createRoot(entry, variantMap); - }, - new CallbackContribution(callback) { - - @Override - public void completed(final Boolean result) { - callback.completed(new CacheHit(rootKey, variantCacheKey, entry)); - } - - }); + @Override + public void completed(final Boolean result) { + if (LOG.isDebugEnabled()) { + LOG.debug("Update root entry: {}", rootKey); } - }); - } + updateInternal(rootKey, + existing -> { + final Set variantMap = existing != null ? new HashSet<>(existing.getVariants()) : new HashSet<>(); + variantMap.add(variantKey); + return cacheEntryFactory.createRoot(entry, variantMap); + }, + new CallbackContribution(callback) { + + @Override + public void completed(final Boolean result) { + callback.completed(new CacheHit(rootKey, variantCacheKey, entry)); + } + + }); + } + + }); } @Override diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/BasicHttpCache.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/BasicHttpCache.java index 0d808d278..c47971fdd 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/BasicHttpCache.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/BasicHttpCache.java @@ -164,9 +164,8 @@ class BasicHttpCache implements HttpCache { } } return new CacheMatch(null, new CacheHit(rootKey, root)); - } else { - return new CacheMatch(new CacheHit(rootKey, root), null); } + return new CacheMatch(new CacheHit(rootKey, root), null); } @Override @@ -197,26 +196,25 @@ class BasicHttpCache implements HttpCache { } storeInternal(rootKey, entry); return new CacheHit(rootKey, entry); - } else { - final String variantCacheKey = variantKey + rootKey; - - if (LOG.isDebugEnabled()) { - LOG.debug("Store variant entry in cache: {}", variantCacheKey); - } - - storeInternal(variantCacheKey, entry); - - if (LOG.isDebugEnabled()) { - LOG.debug("Update root entry: {}", rootKey); - } - - updateInternal(rootKey, existing -> { - final Set variants = existing != null ? new HashSet<>(existing.getVariants()) : new HashSet<>(); - variants.add(variantKey); - return cacheEntryFactory.createRoot(entry, variants); - }); - return new CacheHit(rootKey, variantCacheKey, entry); } + final String variantCacheKey = variantKey + rootKey; + + if (LOG.isDebugEnabled()) { + LOG.debug("Store variant entry in cache: {}", variantCacheKey); + } + + storeInternal(variantCacheKey, entry); + + if (LOG.isDebugEnabled()) { + LOG.debug("Update root entry: {}", rootKey); + } + + updateInternal(rootKey, existing -> { + final Set variants = existing != null ? new HashSet<>(existing.getVariants()) : new HashSet<>(); + variants.add(variantKey); + return cacheEntryFactory.createRoot(entry, variants); + }); + return new CacheHit(rootKey, variantCacheKey, entry); } @Override diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheControlHeaderGenerator.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheControlHeaderGenerator.java index 49ebe0fbf..f9fa8ac0c 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheControlHeaderGenerator.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheControlHeaderGenerator.java @@ -92,9 +92,8 @@ class CacheControlHeaderGenerator { BasicHeaderValueFormatter.INSTANCE.formatNameValuePair(buf, params.get(i), false); } return BufferedHeader.create(buf); - } else { - return null; } + return null; } public void generate(final RequestCacheControl cacheControl, final HttpMessage message) { diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheKeyGenerator.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheKeyGenerator.java index 470a9eb4b..e15b06ca8 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheKeyGenerator.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheKeyGenerator.java @@ -237,29 +237,28 @@ public class CacheKeyGenerator implements Resolver { .map(e -> { if (e.getValue() == null && e.getParameterCount() == 0) { return e.getName().toLowerCase(Locale.ROOT); - } else { - final CharArrayBuffer buf = new CharArrayBuffer(1024); - BasicHeaderValueFormatter.INSTANCE.formatNameValuePair( - buf, - new BasicNameValuePair( - e.getName().toLowerCase(Locale.ROOT), - !TextUtils.isBlank(e.getValue()) ? e.getValue() : null), - false); - if (e.getParameterCount() > 0) { - for (final NameValuePair nvp : e.getParameters()) { - if (!TextUtils.isBlank(nvp.getName())) { - buf.append(';'); - BasicHeaderValueFormatter.INSTANCE.formatNameValuePair( - buf, - new BasicNameValuePair( - nvp.getName().toLowerCase(Locale.ROOT), - !TextUtils.isBlank(nvp.getValue()) ? nvp.getValue() : null), - false); - } + } + final CharArrayBuffer buf = new CharArrayBuffer(1024); + BasicHeaderValueFormatter.INSTANCE.formatNameValuePair( + buf, + new BasicNameValuePair( + e.getName().toLowerCase(Locale.ROOT), + !TextUtils.isBlank(e.getValue()) ? e.getValue() : null), + false); + if (e.getParameterCount() > 0) { + for (final NameValuePair nvp : e.getParameters()) { + if (!TextUtils.isBlank(nvp.getName())) { + buf.append(';'); + BasicHeaderValueFormatter.INSTANCE.formatNameValuePair( + buf, + new BasicNameValuePair( + nvp.getName().toLowerCase(Locale.ROOT), + !TextUtils.isBlank(nvp.getValue()) ? nvp.getValue() : null), + false); } } - return buf.toString(); } + return buf.toString(); }) .sorted() .distinct() @@ -311,9 +310,8 @@ public class CacheKeyGenerator implements Resolver { if (entry.containsHeader(HttpHeaders.VARY)) { final List variantNames = variantNames(entry); return generateVariantKey(request, variantNames); - } else { - return null; } + return null; } /** @@ -334,9 +332,8 @@ public class CacheKeyGenerator implements Resolver { final List variantNames = variantNames(entry); if (variantNames.isEmpty()) { return rootKey; - } else { - return generateVariantKey(request, variantNames) + rootKey; } + return generateVariantKey(request, variantNames) + rootKey; } } diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheSupport.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheSupport.java index f0cb7e7ce..2a839dad3 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheSupport.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheSupport.java @@ -55,9 +55,8 @@ public final class CacheSupport { } if (locationUri.isAbsolute()) { return locationUri; - } else { - return URIUtils.resolve(requestUri, locationUri); } + return URIUtils.resolve(requestUri, locationUri); } public static boolean isSameOrigin(final URI requestURI, final URI targetURI) { diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheValidityPolicy.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheValidityPolicy.java index a9fa16a40..74d876b43 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheValidityPolicy.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheValidityPolicy.java @@ -131,9 +131,8 @@ class CacheValidityPolicy { LOG.debug("No explicit expiration time present in the response. Using heuristic freshness lifetime calculation."); } return getHeuristicFreshnessLifetime(entry); - } else { - return TimeValue.ZERO_MILLISECONDS; } + return TimeValue.ZERO_MILLISECONDS; } TimeValue getHeuristicFreshnessLifetime(final HttpCacheEntry entry) { diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachedResponseSuitabilityChecker.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachedResponseSuitabilityChecker.java index c7c124997..6271564ae 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachedResponseSuitabilityChecker.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachedResponseSuitabilityChecker.java @@ -176,26 +176,24 @@ class CachedResponseSuitabilityChecker { if (stale >= requestCacheControl.getMaxStale()) { LOG.debug("Response from cache is not suitable due to the request max-stale requirement"); return CacheSuitability.REVALIDATION_REQUIRED; - } else { - LOG.debug("The cache entry is fresh enough"); - return CacheSuitability.FRESH_ENOUGH; } + LOG.debug("The cache entry is fresh enough"); + return CacheSuitability.FRESH_ENOUGH; } if (fresh) { LOG.debug("The cache entry is fresh"); return CacheSuitability.FRESH; - } else { - if (responseCacheControl.getStaleWhileRevalidate() > 0) { - final long stale = currentAge.compareTo(freshnessLifetime) > 0 ? currentAge.toSeconds() - freshnessLifetime.toSeconds() : 0; - if (stale < responseCacheControl.getStaleWhileRevalidate()) { - LOG.debug("The cache entry is stale but suitable while being revalidated"); - return CacheSuitability.STALE_WHILE_REVALIDATED; - } - } - LOG.debug("The cache entry is stale"); - return CacheSuitability.STALE; } + if (responseCacheControl.getStaleWhileRevalidate() > 0) { + final long stale = currentAge.compareTo(freshnessLifetime) > 0 ? currentAge.toSeconds() - freshnessLifetime.toSeconds() : 0; + if (stale < responseCacheControl.getStaleWhileRevalidate()) { + LOG.debug("The cache entry is stale but suitable while being revalidated"); + return CacheSuitability.STALE_WHILE_REVALIDATED; + } + } + LOG.debug("The cache entry is stale"); + return CacheSuitability.STALE; } boolean requestMethodMatch(final HttpRequest request, final HttpCacheEntry entry) { @@ -209,9 +207,8 @@ class CachedResponseSuitabilityChecker { final URI cacheURI = new URI(entry.getRequestURI()); if (requestURI.isAbsolute()) { return Objects.equals(requestURI, cacheURI); - } else { - return Objects.equals(requestURI.getPath(), cacheURI.getPath()) && Objects.equals(requestURI.getQuery(), cacheURI.getQuery()); } + return Objects.equals(requestURI.getPath(), cacheURI.getPath()) && Objects.equals(requestURI.getQuery(), cacheURI.getQuery()); } catch (final URISyntaxException ex) { return false; } diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingExec.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingExec.java index 185446a0e..6ab119400 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingExec.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingExec.java @@ -182,14 +182,13 @@ class CachingExec extends CachingExecBase implements ExecChainHandler { if (hit == null) { return handleCacheMiss(requestCacheControl, root, target, request, scope, chain); - } else { - final ResponseCacheControl responseCacheControl = CacheControlHeaderParser.INSTANCE.parse(hit.entry); - context.setResponseCacheControl(responseCacheControl); - if (LOG.isDebugEnabled()) { - LOG.debug("{} response cache control: {}", exchangeId, responseCacheControl); - } - return handleCacheHit(requestCacheControl, responseCacheControl, hit, target, request, scope, chain); } + final ResponseCacheControl responseCacheControl = CacheControlHeaderParser.INSTANCE.parse(hit.entry); + context.setResponseCacheControl(responseCacheControl); + if (LOG.isDebugEnabled()) { + LOG.debug("{} response cache control: {}", exchangeId, responseCacheControl); + } + return handleCacheHit(requestCacheControl, responseCacheControl, hit, target, request, scope, chain); } private static ClassicHttpResponse convert(final SimpleHttpResponse cacheResponse) { @@ -279,73 +278,71 @@ class CachingExec extends CachingExecBase implements ExecChainHandler { context.setCacheResponseStatus(CacheResponseStatus.FAILURE); return chain.proceed(request, scope); } - } else { - if (requestCacheControl.isOnlyIfCached()) { - if (LOG.isDebugEnabled()) { - LOG.debug("{} cache entry not is not fresh and only-if-cached requested", exchangeId); - } - context.setCacheResponseStatus(CacheResponseStatus.CACHE_MODULE_RESPONSE); - return convert(generateGatewayTimeout()); - } else if (cacheSuitability == CacheSuitability.MISMATCH) { - if (LOG.isDebugEnabled()) { - LOG.debug("{} cache entry does not match the request; calling backend", exchangeId); - } - return callBackend(target, request, scope, chain); - } else if (request.getEntity() != null && !request.getEntity().isRepeatable()) { - if (LOG.isDebugEnabled()) { - LOG.debug("{} request is not repeatable; calling backend", exchangeId); - } - return callBackend(target, request, scope, chain); - } else if (hit.entry.getStatus() == HttpStatus.SC_NOT_MODIFIED && !suitabilityChecker.isConditional(request)) { - if (LOG.isDebugEnabled()) { - LOG.debug("{} non-modified cache entry does not match the non-conditional request; calling backend", exchangeId); - } - return callBackend(target, request, scope, chain); - } else if (cacheSuitability == CacheSuitability.REVALIDATION_REQUIRED) { - if (LOG.isDebugEnabled()) { - LOG.debug("{} revalidation required; revalidating cache entry", exchangeId); - } - return revalidateCacheEntryWithoutFallback(responseCacheControl, hit, target, request, scope, chain); - } else if (cacheSuitability == CacheSuitability.STALE_WHILE_REVALIDATED) { - if (cacheRevalidator != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("{} serving stale with asynchronous revalidation", exchangeId); - } - final String revalidationExchangeId = ExecSupport.getNextExchangeId(); - context.setExchangeId(revalidationExchangeId); - final ExecChain.Scope fork = new ExecChain.Scope( - revalidationExchangeId, - scope.route, - scope.originalRequest, - scope.execRuntime.fork(null), - HttpCacheContext.create()); - if (LOG.isDebugEnabled()) { - LOG.debug("{} starting asynchronous revalidation exchange {}", exchangeId, revalidationExchangeId); - } - cacheRevalidator.revalidateCacheEntry( - hit.getEntryKey(), - () -> revalidateCacheEntry(responseCacheControl, hit, target, request, fork, chain)); - context.setCacheResponseStatus(CacheResponseStatus.CACHE_MODULE_RESPONSE); - final SimpleHttpResponse cacheResponse = responseGenerator.generateResponse(request, hit.entry); - context.setCacheEntry(hit.entry); - return convert(cacheResponse); - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("{} revalidating stale cache entry (asynchronous revalidation disabled)", exchangeId); - } - return revalidateCacheEntryWithFallback(requestCacheControl, responseCacheControl, hit, target, request, scope, chain); - } - } else if (cacheSuitability == CacheSuitability.STALE) { - if (LOG.isDebugEnabled()) { - LOG.debug("{} revalidating stale cache entry", exchangeId); - } - return revalidateCacheEntryWithFallback(requestCacheControl, responseCacheControl, hit, target, request, scope, chain); - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("{} cache entry not usable; calling backend", exchangeId); - } - return callBackend(target, request, scope, chain); + } + if (requestCacheControl.isOnlyIfCached()) { + if (LOG.isDebugEnabled()) { + LOG.debug("{} cache entry not is not fresh and only-if-cached requested", exchangeId); } + context.setCacheResponseStatus(CacheResponseStatus.CACHE_MODULE_RESPONSE); + return convert(generateGatewayTimeout()); + } else if (cacheSuitability == CacheSuitability.MISMATCH) { + if (LOG.isDebugEnabled()) { + LOG.debug("{} cache entry does not match the request; calling backend", exchangeId); + } + return callBackend(target, request, scope, chain); + } else if (request.getEntity() != null && !request.getEntity().isRepeatable()) { + if (LOG.isDebugEnabled()) { + LOG.debug("{} request is not repeatable; calling backend", exchangeId); + } + return callBackend(target, request, scope, chain); + } else if (hit.entry.getStatus() == HttpStatus.SC_NOT_MODIFIED && !suitabilityChecker.isConditional(request)) { + if (LOG.isDebugEnabled()) { + LOG.debug("{} non-modified cache entry does not match the non-conditional request; calling backend", exchangeId); + } + return callBackend(target, request, scope, chain); + } else if (cacheSuitability == CacheSuitability.REVALIDATION_REQUIRED) { + if (LOG.isDebugEnabled()) { + LOG.debug("{} revalidation required; revalidating cache entry", exchangeId); + } + return revalidateCacheEntryWithoutFallback(responseCacheControl, hit, target, request, scope, chain); + } else if (cacheSuitability == CacheSuitability.STALE_WHILE_REVALIDATED) { + if (cacheRevalidator != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("{} serving stale with asynchronous revalidation", exchangeId); + } + final String revalidationExchangeId = ExecSupport.getNextExchangeId(); + context.setExchangeId(revalidationExchangeId); + final ExecChain.Scope fork = new ExecChain.Scope( + revalidationExchangeId, + scope.route, + scope.originalRequest, + scope.execRuntime.fork(null), + HttpCacheContext.create()); + if (LOG.isDebugEnabled()) { + LOG.debug("{} starting asynchronous revalidation exchange {}", exchangeId, revalidationExchangeId); + } + cacheRevalidator.revalidateCacheEntry( + hit.getEntryKey(), + () -> revalidateCacheEntry(responseCacheControl, hit, target, request, fork, chain)); + context.setCacheResponseStatus(CacheResponseStatus.CACHE_MODULE_RESPONSE); + final SimpleHttpResponse cacheResponse = responseGenerator.generateResponse(request, hit.entry); + context.setCacheEntry(hit.entry); + return convert(cacheResponse); + } + if (LOG.isDebugEnabled()) { + LOG.debug("{} revalidating stale cache entry (asynchronous revalidation disabled)", exchangeId); + } + return revalidateCacheEntryWithFallback(requestCacheControl, responseCacheControl, hit, target, request, scope, chain); + } else if (cacheSuitability == CacheSuitability.STALE) { + if (LOG.isDebugEnabled()) { + LOG.debug("{} revalidating stale cache entry", exchangeId); + } + return revalidateCacheEntryWithFallback(requestCacheControl, responseCacheControl, hit, target, request, scope, chain); + } else { + if (LOG.isDebugEnabled()) { + LOG.debug("{} cache entry not usable; calling backend", exchangeId); + } + return callBackend(target, request, scope, chain); } } @@ -437,9 +434,8 @@ class CachingExec extends CachingExecBase implements ExecChainHandler { final SimpleHttpResponse cacheResponse = responseGenerator.generateResponse(request, hit.entry); context.setCacheEntry(hit.entry); return convert(cacheResponse); - } else { - return convert(generateGatewayTimeout()); } + return convert(generateGatewayTimeout()); } final int status = response.getCode(); if (staleIfErrorAppliesTo(status) && @@ -479,12 +475,11 @@ class CachingExec extends CachingExecBase implements ExecChainHandler { LOG.debug("{} caching backend response", exchangeId); } return cacheAndReturnResponse(target, request, scope, backendResponse, requestDate, responseDate); - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("{} backend response is not cacheable", exchangeId); - } - return backendResponse; } + if (LOG.isDebugEnabled()) { + LOG.debug("{} backend response is not cacheable", exchangeId); + } + return backendResponse; } ClassicHttpResponse cacheAndReturnResponse( @@ -623,10 +618,9 @@ class CachingExec extends CachingExecBase implements ExecChainHandler { if (backendResponse.getCode() != HttpStatus.SC_NOT_MODIFIED) { return handleBackendResponse(target, request, scope, requestDate, responseDate, backendResponse); - } else { - // 304 response are not expected to have an enclosed content body, but still - backendResponse.close(); } + // 304 response are not expected to have an enclosed content body, but still + backendResponse.close(); final ETag resultEtag = ETag.get(backendResponse); if (resultEtag == null) { diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingExecBase.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingExecBase.java index f886d5b3b..5cef2ec22 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingExecBase.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingExecBase.java @@ -114,9 +114,8 @@ public class CachingExecBase { final Instant now) throws ResourceIOException { if (shouldSendNotModifiedResponse(request, entry, now)) { return responseGenerator.generateNotModifiedResponse(entry); - } else { - return responseGenerator.generateResponse(request, entry); } + return responseGenerator.generateResponse(request, entry); } SimpleHttpResponse generateGatewayTimeout() { diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/FileResourceFactory.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/FileResourceFactory.java index e0842c992..9c36bfe52 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/FileResourceFactory.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/FileResourceFactory.java @@ -101,18 +101,16 @@ public class FileResourceFactory implements ResourceFactory { public Resource generate(final String requestId, final byte[] content, final int off, final int len) throws ResourceIOException { if (content != null) { return generate(requestId, null, content, off, len); - } else { - return generate(requestId, null, null, 0, 0); } + return generate(requestId, null, null, 0, 0); } @Override public Resource generate(final String requestId, final byte[] content) throws ResourceIOException { if (content != null) { return generate(requestId, null, content, 0, content.length); - } else { - return generate(requestId, null, null, 0, 0); } + return generate(requestId, null, null, 0, 0); } /** diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/HeapResource.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/HeapResource.java index a632f5266..272732dff 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/HeapResource.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/HeapResource.java @@ -62,11 +62,7 @@ public class HeapResource extends Resource { @Override public long length() { final byte[] byteArray = this.arrayRef.get(); - if (byteArray != null) { - return byteArray.length; - } else { - return -1; - } + return byteArray != null ? byteArray.length : -1; } @Override diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/InternalCacheStorage.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/InternalCacheStorage.java index efc3f1843..0f5017f43 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/InternalCacheStorage.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/InternalCacheStorage.java @@ -54,9 +54,8 @@ final public class InternalCacheStorage { evictionQueue.add(new HttpCacheStorageEntry(eldest.getKey(), eldest.getValue())); } return true; - } else { - return false; } + return false; } }; diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ResponseCachingPolicy.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ResponseCachingPolicy.java index ccbfc4fcb..e07879509 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ResponseCachingPolicy.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ResponseCachingPolicy.java @@ -231,12 +231,11 @@ class ResponseCachingPolicy { protected boolean isExplicitlyNonCacheable(final ResponseCacheControl cacheControl) { if (cacheControl == null) { return false; - } else { - // The response is considered explicitly non-cacheable if it contains - // "no-store" or (if sharedCache is true) "private" directives. - // Note that "no-cache" is considered cacheable but requires validation before use. - return cacheControl.isNoStore() || (sharedCache && cacheControl.isCachePrivate()); } + // The response is considered explicitly non-cacheable if it contains + // "no-store" or (if sharedCache is true) "private" directives. + // Note that "no-cache" is considered cacheable but requires validation before use. + return cacheControl.isNoStore() || (sharedCache && cacheControl.isCachePrivate()); } protected boolean isExplicitlyCacheable(final ResponseCacheControl cacheControl, final HttpResponse response) { diff --git a/httpclient5-testing/src/main/java/org/apache/hc/client5/testing/async/AuthenticatingAsyncDecorator.java b/httpclient5-testing/src/main/java/org/apache/hc/client5/testing/async/AuthenticatingAsyncDecorator.java index 94d2f90c8..1b3a738f9 100644 --- a/httpclient5-testing/src/main/java/org/apache/hc/client5/testing/async/AuthenticatingAsyncDecorator.java +++ b/httpclient5-testing/src/main/java/org/apache/hc/client5/testing/async/AuthenticatingAsyncDecorator.java @@ -160,9 +160,8 @@ public class AuthenticatingAsyncDecorator implements AsyncServerExchangeHandler final AsyncResponseProducer responseProducer = responseProducerRef.get(); if (responseProducer == null) { return exchangeHandler.available(); - } else { - return responseProducer.available(); } + return responseProducer.available(); } @Override diff --git a/httpclient5-testing/src/main/java/org/apache/hc/client5/testing/async/RedirectingAsyncDecorator.java b/httpclient5-testing/src/main/java/org/apache/hc/client5/testing/async/RedirectingAsyncDecorator.java index 9fe15b506..2296128ee 100644 --- a/httpclient5-testing/src/main/java/org/apache/hc/client5/testing/async/RedirectingAsyncDecorator.java +++ b/httpclient5-testing/src/main/java/org/apache/hc/client5/testing/async/RedirectingAsyncDecorator.java @@ -129,11 +129,7 @@ public class RedirectingAsyncDecorator implements AsyncServerExchangeHandler { @Override public int available() { - if (!redirecting.get()) { - return exchangeHandler.available(); - } else { - return 0; - } + return redirecting.get() ? 0 : exchangeHandler.available(); } @Override diff --git a/httpclient5-testing/src/main/java/org/apache/hc/client5/testing/async/ServiceUnavailableAsyncDecorator.java b/httpclient5-testing/src/main/java/org/apache/hc/client5/testing/async/ServiceUnavailableAsyncDecorator.java index 16d883e2f..873aa059d 100644 --- a/httpclient5-testing/src/main/java/org/apache/hc/client5/testing/async/ServiceUnavailableAsyncDecorator.java +++ b/httpclient5-testing/src/main/java/org/apache/hc/client5/testing/async/ServiceUnavailableAsyncDecorator.java @@ -109,11 +109,7 @@ public class ServiceUnavailableAsyncDecorator implements AsyncServerExchangeHand @Override public int available() { - if (!serviceUnavailable.get()) { - return exchangeHandler.available(); - } else { - return 0; - } + return serviceUnavailable.get() ? 0 : exchangeHandler.available(); } @Override diff --git a/httpclient5-testing/src/main/java/org/apache/hc/client5/testing/auth/AbstractAuthenticationHandler.java b/httpclient5-testing/src/main/java/org/apache/hc/client5/testing/auth/AbstractAuthenticationHandler.java index 5c2420bb2..538d8a8e6 100644 --- a/httpclient5-testing/src/main/java/org/apache/hc/client5/testing/auth/AbstractAuthenticationHandler.java +++ b/httpclient5-testing/src/main/java/org/apache/hc/client5/testing/auth/AbstractAuthenticationHandler.java @@ -69,9 +69,8 @@ abstract class AbstractAuthenticationHandler implements AuthenticationHandler rejectException : this.nonRetriableIOExceptionClasses) { - if (rejectException.isInstance(exception)) { - return false; - } + } + for (final Class rejectException : this.nonRetriableIOExceptionClasses) { + if (rejectException.isInstance(exception)) { + return false; } } if (request instanceof CancellableDependency && ((CancellableDependency) request).isCancelled()) { diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/RequestSupport.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/RequestSupport.java index 5bec04cd3..b11987718 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/RequestSupport.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/RequestSupport.java @@ -57,15 +57,14 @@ public final class RequestSupport { } if (pathSegments.isEmpty()) { return "/"; - } else { - final StringBuilder buf = new StringBuilder(); - buf.append('/'); - for (final String pathSegment : pathSegments) { - PercentCodec.encode(buf, pathSegment, StandardCharsets.US_ASCII); - buf.append('/'); - } - return buf.toString(); } + final StringBuilder buf = new StringBuilder(); + buf.append('/'); + for (final String pathSegment : pathSegments) { + PercentCodec.encode(buf, pathSegment, StandardCharsets.US_ASCII); + buf.append('/'); + } + return buf.toString(); } catch (final URISyntaxException ex) { return path; } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/AsyncConnectExec.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/AsyncConnectExec.java index eb85133ad..c78a7db29 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/AsyncConnectExec.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/AsyncConnectExec.java @@ -253,68 +253,61 @@ public final class AsyncConnectExec implements AsyncExecChainHandler { })); break; - case HttpRouteDirector.TUNNEL_TARGET: - try { - final HttpHost proxy = route.getProxyHost(); - final HttpHost target = route.getTargetHost(); - if (LOG.isDebugEnabled()) { - LOG.debug("{} create tunnel", exchangeId); - } - createTunnel(state, proxy, target, scope, new AsyncExecCallback() { - - @Override - public AsyncDataConsumer handleResponse( - final HttpResponse response, - final EntityDetails entityDetails) throws HttpException, IOException { - return asyncExecCallback.handleResponse(response, entityDetails); - } - - @Override - public void handleInformationResponse( - final HttpResponse response) throws HttpException, IOException { - asyncExecCallback.handleInformationResponse(response); - } - - @Override - public void completed() { - if (!execRuntime.isEndpointConnected()) { - // Remote endpoint disconnected. Need to start over - if (LOG.isDebugEnabled()) { - LOG.debug("{} proxy disconnected", exchangeId); - } - state.tracker.reset(); - } - if (state.challenged) { - if (LOG.isDebugEnabled()) { - LOG.debug("{} proxy authentication required", exchangeId); - } - proceedToNextHop(state, request, entityProducer, scope, chain, asyncExecCallback); - } else { - if (state.tunnelRefused) { - if (LOG.isDebugEnabled()) { - LOG.debug("{} tunnel refused", exchangeId); - } - asyncExecCallback.completed(); - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("{} tunnel to target created", exchangeId); - } - tracker.tunnelTarget(false); - proceedToNextHop(state, request, entityProducer, scope, chain, asyncExecCallback); - } - } - } - - @Override - public void failed(final Exception cause) { - execRuntime.markConnectionNonReusable(); - asyncExecCallback.failed(cause); - } - - }); - } catch (final HttpException | IOException ex) { - asyncExecCallback.failed(ex); + case HttpRouteDirector.TUNNEL_TARGET: + final HttpHost proxy = route.getProxyHost(); + final HttpHost target = route.getTargetHost(); + if (LOG.isDebugEnabled()) { + LOG.debug("{} create tunnel", exchangeId); } + createTunnel(state, proxy, target, scope, new AsyncExecCallback() { + + @Override + public AsyncDataConsumer handleResponse(final HttpResponse response, final EntityDetails entityDetails) throws HttpException, IOException { + return asyncExecCallback.handleResponse(response, entityDetails); + } + + @Override + public void handleInformationResponse(final HttpResponse response) throws HttpException, IOException { + asyncExecCallback.handleInformationResponse(response); + } + + @Override + public void completed() { + if (!execRuntime.isEndpointConnected()) { + // Remote endpoint disconnected. Need to start over + if (LOG.isDebugEnabled()) { + LOG.debug("{} proxy disconnected", exchangeId); + } + state.tracker.reset(); + } + if (state.challenged) { + if (LOG.isDebugEnabled()) { + LOG.debug("{} proxy authentication required", exchangeId); + } + proceedToNextHop(state, request, entityProducer, scope, chain, asyncExecCallback); + } else { + if (state.tunnelRefused) { + if (LOG.isDebugEnabled()) { + LOG.debug("{} tunnel refused", exchangeId); + } + asyncExecCallback.completed(); + } else { + if (LOG.isDebugEnabled()) { + LOG.debug("{} tunnel to target created", exchangeId); + } + tracker.tunnelTarget(false); + proceedToNextHop(state, request, entityProducer, scope, chain, asyncExecCallback); + } + } + } + + @Override + public void failed(final Exception cause) { + execRuntime.markConnectionNonReusable(); + asyncExecCallback.failed(cause); + } + + }); break; case HttpRouteDirector.TUNNEL_PROXY: @@ -372,7 +365,7 @@ public final class AsyncConnectExec implements AsyncExecChainHandler { final HttpHost proxy, final HttpHost nextHop, final AsyncExecChain.Scope scope, - final AsyncExecCallback asyncExecCallback) throws HttpException, IOException { + final AsyncExecCallback asyncExecCallback) { final CancellableDependency operation = scope.cancellableDependency; final HttpClientContext clientContext = scope.clientContext; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/InternalH2AsyncExecRuntime.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/InternalH2AsyncExecRuntime.java index a09e09a41..96d185201 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/InternalH2AsyncExecRuntime.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/InternalH2AsyncExecRuntime.java @@ -234,6 +234,7 @@ class InternalH2AsyncExecRuntime implements AsyncExecRuntime { throw new UnsupportedOperationException(); } + @Override public EndpointInfo getEndpointInfo() { final Endpoint endpoint = sessionRef.get(); if (endpoint != null && endpoint.session.isOpen()) { diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/InternalHttpAsyncExecRuntime.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/InternalHttpAsyncExecRuntime.java index a1e33e1d6..a1903dab6 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/InternalHttpAsyncExecRuntime.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/InternalHttpAsyncExecRuntime.java @@ -267,6 +267,7 @@ class InternalHttpAsyncExecRuntime implements AsyncExecRuntime { }); } + @Override public EndpointInfo getEndpointInfo() { final AsyncConnectionEndpoint endpoint = endpointRef.get(); return endpoint != null ? endpoint.getInfo() : null; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/LoggingIOSession.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/LoggingIOSession.java index ea84aa62d..4e4a5ab9e 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/LoggingIOSession.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/LoggingIOSession.java @@ -262,7 +262,7 @@ class LoggingIOSession implements IOSession { } - private void logData(final ByteBuffer data, final String prefix) throws IOException { + private void logData(final ByteBuffer data, final String prefix) { final byte[] line = new byte[16]; final StringBuilder buf = new StringBuilder(); while (data.hasRemaining()) { diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/NTLMEngineImpl.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/NTLMEngineImpl.java index 4810fc61a..d057efb64 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/NTLMEngineImpl.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/NTLMEngineImpl.java @@ -352,7 +352,7 @@ final class NTLMEngineImpl implements NTLMEngine { byte[] ntlm2SessionResponseUserSessionKey; byte[] lanManagerSessionKey; - public CipherGen(final Random random, final long currentTime, + CipherGen(final Random random, final long currentTime, final String domain, final String user, final char[] password, final byte[] challenge, final String target, final byte[] targetInformation, final byte[] clientChallenge, final byte[] clientChallenge2, @@ -372,7 +372,7 @@ final class NTLMEngineImpl implements NTLMEngine { this.timestamp = timestamp; } - public CipherGen(final Random random, final long currentTime, + CipherGen(final Random random, final long currentTime, final String domain, final String user, final char[] password, @@ -383,7 +383,7 @@ final class NTLMEngineImpl implements NTLMEngine { } /** Calculate and return client challenge */ - public byte[] getClientChallenge() { + byte[] getClientChallenge() { if (clientChallenge == null) { clientChallenge = makeRandomChallenge(random); } @@ -391,7 +391,7 @@ final class NTLMEngineImpl implements NTLMEngine { } /** Calculate and return second client challenge */ - public byte[] getClientChallenge2() { + byte[] getClientChallenge2() { if (clientChallenge2 == null) { clientChallenge2 = makeRandomChallenge(random); } @@ -399,7 +399,7 @@ final class NTLMEngineImpl implements NTLMEngine { } /** Calculate and return random secondary key */ - public byte[] getSecondaryKey() { + byte[] getSecondaryKey() { if (secondaryKey == null) { secondaryKey = makeSecondaryKey(random); } @@ -407,7 +407,7 @@ final class NTLMEngineImpl implements NTLMEngine { } /** Calculate and return the LMHash */ - public byte[] getLMHash() + byte[] getLMHash() throws NTLMEngineException { if (lmHash == null) { lmHash = lmHash(password); @@ -416,17 +416,16 @@ final class NTLMEngineImpl implements NTLMEngine { } /** Calculate and return the LMResponse */ - public byte[] getLMResponse() - throws NTLMEngineException { + byte[] getLMResponse() + throws NTLMEngineException { if (lmResponse == null) { - lmResponse = lmResponse(getLMHash(),challenge); + lmResponse = lmResponse(getLMHash(), challenge); } return lmResponse; } /** Calculate and return the NTLMHash */ - public byte[] getNTLMHash() - throws NTLMEngineException { + byte[] getNTLMHash() { if (ntlmHash == null) { ntlmHash = ntlmHash(password); } @@ -434,17 +433,16 @@ final class NTLMEngineImpl implements NTLMEngine { } /** Calculate and return the NTLMResponse */ - public byte[] getNTLMResponse() - throws NTLMEngineException { + byte[] getNTLMResponse() + throws NTLMEngineException { if (ntlmResponse == null) { - ntlmResponse = lmResponse(getNTLMHash(),challenge); + ntlmResponse = lmResponse(getNTLMHash(), challenge); } return ntlmResponse; } /** Calculate the LMv2 hash */ - public byte[] getLMv2Hash() - throws NTLMEngineException { + byte[] getLMv2Hash() { if (lmv2Hash == null) { lmv2Hash = lmv2Hash(domain, user, getNTLMHash()); } @@ -452,8 +450,7 @@ final class NTLMEngineImpl implements NTLMEngine { } /** Calculate the NTLMv2 hash */ - public byte[] getNTLMv2Hash() - throws NTLMEngineException { + byte[] getNTLMv2Hash() { if (ntlmv2Hash == null) { ntlmv2Hash = ntlmv2Hash(domain, user, getNTLMHash()); } @@ -461,7 +458,7 @@ final class NTLMEngineImpl implements NTLMEngine { } /** Calculate a timestamp */ - public byte[] getTimestamp() { + byte[] getTimestamp() { if (timestamp == null) { long time = this.currentTime; time += 11644473600000L; // milliseconds from January 1, 1601 -> epoch. @@ -477,7 +474,7 @@ final class NTLMEngineImpl implements NTLMEngine { } /** Calculate the NTLMv2Blob */ - public byte[] getNTLMv2Blob() { + byte[] getNTLMv2Blob() { if (ntlmv2Blob == null) { ntlmv2Blob = createBlob(getClientChallenge2(), targetInformation, getTimestamp()); } @@ -485,34 +482,32 @@ final class NTLMEngineImpl implements NTLMEngine { } /** Calculate the NTLMv2Response */ - public byte[] getNTLMv2Response() - throws NTLMEngineException { + byte[] getNTLMv2Response() { if (ntlmv2Response == null) { - ntlmv2Response = lmv2Response(getNTLMv2Hash(),challenge,getNTLMv2Blob()); + ntlmv2Response = lmv2Response(getNTLMv2Hash(), challenge, getNTLMv2Blob()); } return ntlmv2Response; } /** Calculate the LMv2Response */ - public byte[] getLMv2Response() - throws NTLMEngineException { + byte[] getLMv2Response() { if (lmv2Response == null) { - lmv2Response = lmv2Response(getLMv2Hash(),challenge,getClientChallenge()); + lmv2Response = lmv2Response(getLMv2Hash(), challenge, getClientChallenge()); } return lmv2Response; } /** Get NTLM2SessionResponse */ - public byte[] getNTLM2SessionResponse() - throws NTLMEngineException { + byte[] getNTLM2SessionResponse() + throws NTLMEngineException { if (ntlm2SessionResponse == null) { - ntlm2SessionResponse = ntlm2SessionResponse(getNTLMHash(),challenge,getClientChallenge()); + ntlm2SessionResponse = ntlm2SessionResponse(getNTLMHash(), challenge, getClientChallenge()); } return ntlm2SessionResponse; } /** Calculate and return LM2 session response */ - public byte[] getLM2SessionResponse() { + byte[] getLM2SessionResponse() { if (lm2SessionResponse == null) { final byte[] clntChallenge = getClientChallenge(); lm2SessionResponse = new byte[24]; @@ -523,7 +518,7 @@ final class NTLMEngineImpl implements NTLMEngine { } /** Get LMUserSessionKey */ - public byte[] getLMUserSessionKey() + byte[] getLMUserSessionKey() throws NTLMEngineException { if (lmUserSessionKey == null) { lmUserSessionKey = new byte[16]; @@ -534,8 +529,7 @@ final class NTLMEngineImpl implements NTLMEngine { } /** Get NTLMUserSessionKey */ - public byte[] getNTLMUserSessionKey() - throws NTLMEngineException { + byte[] getNTLMUserSessionKey() { if (ntlmUserSessionKey == null) { final MD4 md4 = new MD4(); md4.update(getNTLMHash()); @@ -545,8 +539,7 @@ final class NTLMEngineImpl implements NTLMEngine { } /** GetNTLMv2UserSessionKey */ - public byte[] getNTLMv2UserSessionKey() - throws NTLMEngineException { + byte[] getNTLMv2UserSessionKey() { if (ntlmv2UserSessionKey == null) { final byte[] ntlmv2hash = getNTLMv2Hash(); final byte[] truncatedResponse = new byte[16]; @@ -557,8 +550,7 @@ final class NTLMEngineImpl implements NTLMEngine { } /** Get NTLM2SessionResponseUserSessionKey */ - public byte[] getNTLM2SessionResponseUserSessionKey() - throws NTLMEngineException { + byte[] getNTLM2SessionResponseUserSessionKey() { if (ntlm2SessionResponseUserSessionKey == null) { final byte[] ntlm2SessionResponseNonce = getLM2SessionResponse(); final byte[] sessionNonce = new byte[challenge.length + ntlm2SessionResponseNonce.length]; @@ -570,7 +562,7 @@ final class NTLMEngineImpl implements NTLMEngine { } /** Get LAN Manager session key */ - public byte[] getLanManagerSessionKey() + byte[] getLanManagerSessionKey() throws NTLMEngineException { if (lanManagerSessionKey == null) { try { @@ -689,7 +681,7 @@ final class NTLMEngineImpl implements NTLMEngine { * @return The NTLM Hash of the given password, used in the calculation of * the NTLM Response and the NTLMv2 and LMv2 Hashes. */ - private static byte[] ntlmHash(final char[] password) throws NTLMEngineException { + private static byte[] ntlmHash(final char[] password) { final byte[] unicodePassword = new ByteArrayBuilder() .charset(UNICODE_LITTLE_UNMARKED).append(password).toByteArray(); final MD4 md4 = new MD4(); @@ -703,8 +695,7 @@ final class NTLMEngineImpl implements NTLMEngine { * @return The LMv2 Hash, used in the calculation of the NTLMv2 and LMv2 * Responses. */ - private static byte[] lmv2Hash(final String domain, final String user, final byte[] ntlmHash) - throws NTLMEngineException { + private static byte[] lmv2Hash(final String domain, final String user, final byte[] ntlmHash) { final HMACMD5 hmacMD5 = new HMACMD5(ntlmHash); // Upper case username, upper case domain! hmacMD5.update(user.toUpperCase(Locale.ROOT).getBytes(UNICODE_LITTLE_UNMARKED)); @@ -720,8 +711,7 @@ final class NTLMEngineImpl implements NTLMEngine { * @return The NTLMv2 Hash, used in the calculation of the NTLMv2 and LMv2 * Responses. */ - private static byte[] ntlmv2Hash(final String domain, final String user, final byte[] ntlmHash) - throws NTLMEngineException { + private static byte[] ntlmv2Hash(final String domain, final String user, final byte[] ntlmHash) { final HMACMD5 hmacMD5 = new HMACMD5(ntlmHash); // Upper case username, mixed case target!! hmacMD5.update(user.toUpperCase(Locale.ROOT).getBytes(UNICODE_LITTLE_UNMARKED)); @@ -835,13 +825,13 @@ final class NTLMEngineImpl implements NTLMEngine { rc4 = initCipher(); } - public byte[] getSigningKey() + byte[] getSigningKey() { return signingKey; } - public byte[] getSealingKey() + byte[] getSealingKey() { return sealingKey; } @@ -929,7 +919,7 @@ final class NTLMEngineImpl implements NTLMEngine { return MessageDigest.isEqual( signature, computedSignature ); } - public byte[] signAndEncryptMessage( final byte[] cleartextMessage ) throws NTLMEngineException + byte[] signAndEncryptMessage( final byte[] cleartextMessage ) throws NTLMEngineException { final byte[] encryptedMessage = encrypt( cleartextMessage ); final byte[] signature = computeSignature( cleartextMessage ); @@ -940,7 +930,7 @@ final class NTLMEngineImpl implements NTLMEngine { return outMessage; } - public byte[] decryptAndVerifySignedMessage( final byte[] inMessage ) throws NTLMEngineException + byte[] decryptAndVerifySignedMessage( final byte[] inMessage ) throws NTLMEngineException { final byte[] signature = new byte[16]; System.arraycopy( inMessage, 0, signature, 0, signature.length ); @@ -1060,7 +1050,7 @@ final class NTLMEngineImpl implements NTLMEngine { * @param flags is the flags. * @return the character set. */ - private static Charset getCharset(final int flags) throws NTLMEngineException + private static Charset getCharset(final int flags) { if ((flags & FLAG_REQUEST_UNICODE_ENCODING) == 0) { return DEFAULT_CHARSET; @@ -1217,11 +1207,11 @@ final class NTLMEngineImpl implements NTLMEngine { * * @return The response as above. */ - public String getResponse() { + String getResponse() { return new String(Base64.encodeBase64(getBytes()), StandardCharsets.US_ASCII); } - public byte[] getBytes() { + byte[] getBytes() { if (messageContents == null) { buildMessage(); } @@ -1616,11 +1606,11 @@ final class NTLMEngineImpl implements NTLMEngine { userBytes = user.getBytes(charset); } - public byte[] getEncryptedRandomSessionKey() { + byte[] getEncryptedRandomSessionKey() { return sessionKey; } - public byte[] getExportedSessionKey() { + byte[] getExportedSessionKey() { return exportedSessionKey; } diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/examples/AsyncClientConnectionConfig.java b/httpclient5/src/test/java/org/apache/hc/client5/http/examples/AsyncClientConnectionConfig.java index 7f2dd3a7b..2cf9ed2e7 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/examples/AsyncClientConnectionConfig.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/examples/AsyncClientConnectionConfig.java @@ -66,14 +66,13 @@ public class AsyncClientConnectionConfig { .setValidateAfterInactivity(TimeValue.ofMinutes(1)) .setTimeToLive(TimeValue.ofHours(1)) .build(); - } else { - return ConnectionConfig.custom() - .setConnectTimeout(Timeout.ofMinutes(1)) - .setSocketTimeout(Timeout.ofMinutes(1)) - .setValidateAfterInactivity(TimeValue.ofSeconds(15)) - .setTimeToLive(TimeValue.ofMinutes(15)) - .build(); } + return ConnectionConfig.custom() + .setConnectTimeout(Timeout.ofMinutes(1)) + .setSocketTimeout(Timeout.ofMinutes(1)) + .setValidateAfterInactivity(TimeValue.ofSeconds(15)) + .setTimeToLive(TimeValue.ofMinutes(15)) + .build(); }) .setTlsConfigResolver(host -> { // Use different settings for specific hosts @@ -82,9 +81,8 @@ public class AsyncClientConnectionConfig { .setSupportedProtocols(TLS.V_1_3) .setHandshakeTimeout(Timeout.ofSeconds(10)) .build(); - } else { - return TlsConfig.DEFAULT; } + return TlsConfig.DEFAULT; }) .build(); try (final CloseableHttpAsyncClient client = HttpAsyncClients.custom() diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/examples/ClientConfiguration.java b/httpclient5/src/test/java/org/apache/hc/client5/http/examples/ClientConfiguration.java index 35246ff02..fe548154c 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/examples/ClientConfiguration.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/examples/ClientConfiguration.java @@ -160,9 +160,8 @@ public class ClientConfiguration { public InetAddress[] resolve(final String host) throws UnknownHostException { if (host.equalsIgnoreCase("myhost")) { return new InetAddress[] { InetAddress.getByAddress(new byte[] {127, 0, 0, 1}) }; - } else { - return super.resolve(host); } + return super.resolve(host); } }; diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/examples/ClientConnectionConfig.java b/httpclient5/src/test/java/org/apache/hc/client5/http/examples/ClientConnectionConfig.java index a72d6af1f..543a5c242 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/examples/ClientConnectionConfig.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/examples/ClientConnectionConfig.java @@ -60,14 +60,13 @@ public class ClientConnectionConfig { .setValidateAfterInactivity(TimeValue.ofMinutes(1)) .setTimeToLive(TimeValue.ofHours(1)) .build(); - } else { - return ConnectionConfig.custom() - .setConnectTimeout(Timeout.ofMinutes(1)) - .setSocketTimeout(Timeout.ofMinutes(1)) - .setValidateAfterInactivity(TimeValue.ofSeconds(15)) - .setTimeToLive(TimeValue.ofMinutes(15)) - .build(); } + return ConnectionConfig.custom() + .setConnectTimeout(Timeout.ofMinutes(1)) + .setSocketTimeout(Timeout.ofMinutes(1)) + .setValidateAfterInactivity(TimeValue.ofSeconds(15)) + .setTimeToLive(TimeValue.ofMinutes(15)) + .build(); }) .setTlsConfigResolver(host -> { // Use different settings for specific hosts @@ -76,9 +75,8 @@ public class ClientConnectionConfig { .setSupportedProtocols(TLS.V_1_3) .setHandshakeTimeout(Timeout.ofSeconds(10)) .build(); - } else { - return TlsConfig.DEFAULT; } + return TlsConfig.DEFAULT; }) .build(); try (CloseableHttpClient httpclient = HttpClients.custom() diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/examples/ClientInterceptors.java b/httpclient5/src/test/java/org/apache/hc/client5/http/examples/ClientInterceptors.java index 9d9f9a66c..0e4046942 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/examples/ClientInterceptors.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/examples/ClientInterceptors.java @@ -79,9 +79,8 @@ public class ClientInterceptors { final ClassicHttpResponse response = new BasicClassicHttpResponse(HttpStatus.SC_NOT_FOUND, "Oppsie"); response.setEntity(new StringEntity("bad luck", ContentType.TEXT_PLAIN)); return response; - } else { - return chain.proceed(request, scope); } + return chain.proceed(request, scope); }) .build()) { diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/classic/MockConnPoolControl.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/classic/MockConnPoolControl.java index 7d0fc156c..f4ed63bca 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/classic/MockConnPoolControl.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/classic/MockConnPoolControl.java @@ -88,11 +88,7 @@ public final class MockConnPoolControl implements ConnPoolControl { @Override public int getMaxPerRoute(final HttpRoute route) { final Integer max = this.maxPerHostMap.get(route); - if (max != null) { - return max; - } else { - return this.defaultMax; - } + return max != null ? max : this.defaultMax; } @Override