You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hc.apache.org by ol...@apache.org on 2023/08/21 08:20:59 UTC
[httpcomponents-client] branch 5.4.x updated (046f3453e -> 6bdd38935)
This is an automated email from the ASF dual-hosted git repository.
olegk pushed a change to branch 5.4.x
in repository https://gitbox.apache.org/repos/asf/httpcomponents-client.git
from 046f3453e Implement Cache-Control Extension in Response Caching Policy. (#462)
new 6d55e7a4b HTTPCLIENT-2277: Removal of deprecated `Warning` header support
new 5fced6400 HTTPCLIENT-2277: Removal of support for deprecated `Pragma` header
new a37d79144 HTTPCLIENT-2277: Removal of the HTTP protocol logic presently enforced in the caching layer directly related to the caching functionality. The enforcement of general protocol requirements should be implemented in the protocol layer.
new a1cc5554c HTTPCLIENT-2277: Revision of the response protocol compliance checks: the caching layer should not attempt to enforce HTTP protocol compliance beyond what it required for correct operation of the caching functionality
new 06700d0cd Fixed deprecation warnings
new 6bdd38935 Removed unused method argument
The 6 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
.../client5/http/cache/HttpCacheEntryFactory.java | 39 +-
.../client5/http/impl/cache/AsyncCachingExec.java | 20 +-
.../hc/client5/http/impl/cache/CacheConfig.java | 23 +-
.../http/impl/cache/CacheRevalidatorBase.java | 25 -
.../http/impl/cache/CacheableRequestPolicy.java | 6 -
.../impl/cache/CachedHttpResponseGenerator.java | 27 -
.../hc/client5/http/impl/cache/CachingExec.java | 20 +-
.../client5/http/impl/cache/CachingExecBase.java | 52 +-
.../impl/cache/CachingH2AsyncClientBuilder.java | 4 +-
.../impl/cache/CachingHttpAsyncClientBuilder.java | 4 +-
.../http/impl/cache/CachingHttpClientBuilder.java | 4 +-
.../http/impl/cache/ConditionalRequestBuilder.java | 1 -
.../impl/cache/DefaultAsyncCacheRevalidator.java | 2 +-
.../http/impl/cache/DefaultCacheRevalidator.java | 2 +-
.../http/impl/cache/RequestProtocolCompliance.java | 199 ------
.../http/impl/cache/RequestProtocolError.java | 36 -
.../http/impl/cache/ResponseCachingPolicy.java | 6 -
.../impl/cache/ResponseProtocolCompliance.java | 219 +-----
.../hc/client5/http/impl/cache/WarningValue.java | 368 ----------
.../http/cache/TestHttpCacheEntryFactory.java | 32 -
.../hc/client5/http/impl/cache/HttpTestUtils.java | 18 -
.../http/impl/cache/TestCacheRevalidatorBase.java | 24 -
.../impl/cache/TestCacheableRequestPolicy.java | 34 -
.../http/impl/cache/TestCachingExecChain.java | 197 ------
.../impl/cache/TestConditionalRequestBuilder.java | 18 -
.../http/impl/cache/TestProtocolDeviations.java | 30 -
.../impl/cache/TestProtocolRecommendations.java | 217 ------
.../http/impl/cache/TestProtocolRequirements.java | 765 +--------------------
.../http/impl/cache/TestRFC5861Compliance.java | 390 -----------
.../impl/cache/TestRequestProtocolCompliance.java | 187 -----
.../http/impl/cache/TestResponseCachingPolicy.java | 6 -
.../impl/cache/TestResponseProtocolCompliance.java | 60 +-
.../client5/http/impl/cache/TestWarningValue.java | 230 -------
33 files changed, 123 insertions(+), 3142 deletions(-)
delete mode 100644 httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/RequestProtocolCompliance.java
delete mode 100644 httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/RequestProtocolError.java
delete mode 100644 httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/WarningValue.java
delete mode 100644 httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestRequestProtocolCompliance.java
delete mode 100644 httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestWarningValue.java
[httpcomponents-client] 05/06: Fixed deprecation warnings
Posted by ol...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
olegk pushed a commit to branch 5.4.x
in repository https://gitbox.apache.org/repos/asf/httpcomponents-client.git
commit 06700d0cd8e9bb9eb0a9452f76533494f54514b4
Author: Oleg Kalnichevski <ol...@apache.org>
AuthorDate: Sun Aug 20 12:25:31 2023 +0200
Fixed deprecation warnings
---
.../apache/hc/client5/http/impl/cache/CachingH2AsyncClientBuilder.java | 3 +--
.../hc/client5/http/impl/cache/CachingHttpAsyncClientBuilder.java | 3 +--
.../apache/hc/client5/http/impl/cache/CachingHttpClientBuilder.java | 3 +--
3 files changed, 3 insertions(+), 6 deletions(-)
diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingH2AsyncClientBuilder.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingH2AsyncClientBuilder.java
index 7b8646b82..108beb9f3 100644
--- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingH2AsyncClientBuilder.java
+++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingH2AsyncClientBuilder.java
@@ -31,7 +31,6 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import org.apache.hc.client5.http.async.AsyncExecChainHandler;
-import org.apache.hc.client5.http.cache.HttpAsyncCacheInvalidator;
import org.apache.hc.client5.http.cache.HttpAsyncCacheStorage;
import org.apache.hc.client5.http.cache.HttpAsyncCacheStorageAdaptor;
import org.apache.hc.client5.http.cache.HttpCacheEntryFactory;
@@ -104,7 +103,7 @@ public class CachingH2AsyncClientBuilder extends H2AsyncClientBuilder {
* @deprecated Do not use.
*/
@Deprecated
- public final CachingH2AsyncClientBuilder setHttpCacheInvalidator(final HttpAsyncCacheInvalidator cacheInvalidator) {
+ public final CachingH2AsyncClientBuilder setHttpCacheInvalidator(final org.apache.hc.client5.http.cache.HttpAsyncCacheInvalidator cacheInvalidator) {
return this;
}
diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingHttpAsyncClientBuilder.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingHttpAsyncClientBuilder.java
index a03ed0593..50656dff3 100644
--- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingHttpAsyncClientBuilder.java
+++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingHttpAsyncClientBuilder.java
@@ -31,7 +31,6 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import org.apache.hc.client5.http.async.AsyncExecChainHandler;
-import org.apache.hc.client5.http.cache.HttpAsyncCacheInvalidator;
import org.apache.hc.client5.http.cache.HttpAsyncCacheStorage;
import org.apache.hc.client5.http.cache.HttpAsyncCacheStorageAdaptor;
import org.apache.hc.client5.http.cache.HttpCacheEntryFactory;
@@ -104,7 +103,7 @@ public class CachingHttpAsyncClientBuilder extends HttpAsyncClientBuilder {
* @deprecated Do not use.
*/
@Deprecated
- public final CachingHttpAsyncClientBuilder setHttpCacheInvalidator(final HttpAsyncCacheInvalidator cacheInvalidator) {
+ public final CachingHttpAsyncClientBuilder setHttpCacheInvalidator(final org.apache.hc.client5.http.cache.HttpAsyncCacheInvalidator cacheInvalidator) {
return this;
}
diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingHttpClientBuilder.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingHttpClientBuilder.java
index b4fd0f331..aa9b992d4 100644
--- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingHttpClientBuilder.java
+++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingHttpClientBuilder.java
@@ -31,7 +31,6 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import org.apache.hc.client5.http.cache.HttpCacheEntryFactory;
-import org.apache.hc.client5.http.cache.HttpCacheInvalidator;
import org.apache.hc.client5.http.cache.HttpCacheStorage;
import org.apache.hc.client5.http.cache.ResourceFactory;
import org.apache.hc.client5.http.classic.ExecChainHandler;
@@ -96,7 +95,7 @@ public class CachingHttpClientBuilder extends HttpClientBuilder {
* @deprecated Do not use.
*/
@Deprecated
- public final CachingHttpClientBuilder setHttpCacheInvalidator(final HttpCacheInvalidator cacheInvalidator) {
+ public final CachingHttpClientBuilder setHttpCacheInvalidator(final org.apache.hc.client5.http.cache.HttpAsyncCacheInvalidator cacheInvalidator) {
return this;
}
[httpcomponents-client] 02/06: HTTPCLIENT-2277: Removal of support for deprecated `Pragma` header
Posted by ol...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
olegk pushed a commit to branch 5.4.x
in repository https://gitbox.apache.org/repos/asf/httpcomponents-client.git
commit 5fced64000202774460ddfa86c3b8dd24670c98a
Author: Oleg Kalnichevski <ol...@apache.org>
AuthorDate: Sun Jul 16 14:40:55 2023 +0200
HTTPCLIENT-2277: Removal of support for deprecated `Pragma` header
---
.../http/impl/cache/CacheableRequestPolicy.java | 6 ----
.../http/impl/cache/ConditionalRequestBuilder.java | 1 -
.../impl/cache/TestCacheableRequestPolicy.java | 34 ----------------------
.../impl/cache/TestConditionalRequestBuilder.java | 18 ------------
.../impl/cache/TestProtocolRecommendations.java | 7 -----
.../http/impl/cache/TestProtocolRequirements.java | 32 +++-----------------
6 files changed, 4 insertions(+), 94 deletions(-)
diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheableRequestPolicy.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheableRequestPolicy.java
index 3e6e18fec..79495feb2 100644
--- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheableRequestPolicy.java
+++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheableRequestPolicy.java
@@ -26,7 +26,6 @@
*/
package org.apache.hc.client5.http.impl.cache;
-import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.HttpRequest;
import org.apache.hc.core5.http.HttpVersion;
import org.apache.hc.core5.http.Method;
@@ -64,11 +63,6 @@ class CacheableRequestPolicy {
return false;
}
- if (request.countHeaders(HttpHeaders.PRAGMA) > 0) {
- LOG.debug("request with Pragma header is not serveable from cache");
- return false;
- }
-
if (cacheControl.isNoStore()) {
LOG.debug("Request with no-store is not serveable from cache");
return false;
diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ConditionalRequestBuilder.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ConditionalRequestBuilder.java
index 22562fbfa..bccb12aa8 100644
--- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ConditionalRequestBuilder.java
+++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ConditionalRequestBuilder.java
@@ -103,7 +103,6 @@ class ConditionalRequestBuilder<T extends HttpRequest> {
public T buildUnconditionalRequest(final T request) {
final T newRequest = messageCopier.create(request);
newRequest.addHeader(HttpHeaders.CACHE_CONTROL,HeaderConstants.CACHE_CONTROL_NO_CACHE);
- newRequest.addHeader(HttpHeaders.PRAGMA,HeaderConstants.CACHE_CONTROL_NO_CACHE);
newRequest.removeHeaders(HttpHeaders.IF_RANGE);
newRequest.removeHeaders(HttpHeaders.IF_MATCH);
newRequest.removeHeaders(HttpHeaders.IF_NONE_MATCH);
diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCacheableRequestPolicy.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCacheableRequestPolicy.java
index bf15db608..2d68671b4 100644
--- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCacheableRequestPolicy.java
+++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCacheableRequestPolicy.java
@@ -65,22 +65,6 @@ public class TestCacheableRequestPolicy {
Assertions.assertFalse(policy.isServableFromCache(cacheControl2, request));
}
- @Test
- public void testIsGetWithPragmaServableFromCache() {
- final BasicHttpRequest request = new BasicHttpRequest("GET", "someUri");
- request.addHeader("Pragma", "no-cache");
- final RequestCacheControl cacheControl = RequestCacheControl.builder()
- .build();
-
- Assertions.assertFalse(policy.isServableFromCache(cacheControl, request));
-
- final BasicHttpRequest request2 = new BasicHttpRequest("GET", "someUri");
- request2.addHeader("Pragma", "value1");
- request2.addHeader("Pragma", "value2");
-
- Assertions.assertFalse(policy.isServableFromCache(cacheControl, request2));
- }
-
@Test
public void testIsHeadServableFromCache() {
final BasicHttpRequest request = new BasicHttpRequest("HEAD", "someUri");
@@ -114,24 +98,6 @@ public class TestCacheableRequestPolicy {
Assertions.assertFalse(policy.isServableFromCache(cacheControl2, request));
}
- @Test
- public void testIsHeadWithPragmaServableFromCache() {
- final BasicHttpRequest request = new BasicHttpRequest("HEAD", "someUri");
- final RequestCacheControl cacheControl = RequestCacheControl.builder()
- .setNoCache(true)
- .build();
-
- Assertions.assertFalse(policy.isServableFromCache(cacheControl, request));
-
- final BasicHttpRequest request2 = new BasicHttpRequest("HEAD", "someUri");
- request2.addHeader("Pragma", "value1");
- request2.addHeader("Pragma", "value2");
- final RequestCacheControl cacheControl2 = RequestCacheControl.builder()
- .build();
-
- Assertions.assertFalse(policy.isServableFromCache(cacheControl2, request2));
- }
-
@Test
public void testIsArbitraryMethodServableFromCache() {
final BasicHttpRequest request = new BasicHttpRequest("TRACE", "someUri");
diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestConditionalRequestBuilder.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestConditionalRequestBuilder.java
index beb0f0dd9..1aadcac96 100644
--- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestConditionalRequestBuilder.java
+++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestConditionalRequestBuilder.java
@@ -29,18 +29,15 @@ package org.apache.hc.client5.http.impl.cache;
import java.time.Instant;
import java.util.Arrays;
import java.util.HashSet;
-import java.util.Iterator;
import java.util.Set;
import org.apache.hc.client5.http.cache.HttpCacheEntry;
import org.apache.hc.client5.http.utils.DateUtils;
import org.apache.hc.core5.http.Header;
-import org.apache.hc.core5.http.HeaderElement;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.HttpRequest;
import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.http.message.BasicHttpRequest;
-import org.apache.hc.core5.http.message.MessageSupport;
import org.apache.hc.core5.http.support.BasicRequestBuilder;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
@@ -211,21 +208,6 @@ public class TestConditionalRequestBuilder {
Assertions.assertTrue(requestCacheControl.isNoCache());
}
- @Test
- public void testBuildUnconditionalRequestAddsPragmaNoCache()
- throws Exception {
- final HttpRequest result = impl.buildUnconditionalRequest(request);
- boolean ccNoCacheFound = false;
- final Iterator<HeaderElement> it = MessageSupport.iterate(result, HttpHeaders.PRAGMA);
- while (it.hasNext()) {
- final HeaderElement elt = it.next();
- if ("no-cache".equals(elt.getName())) {
- ccNoCacheFound = true;
- }
- }
- Assertions.assertTrue(ccNoCacheFound);
- }
-
@Test
public void testBuildUnconditionalRequestDoesNotUseIfRange()
throws Exception {
diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolRecommendations.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolRecommendations.java
index 9e967bc6d..e4839e59a 100644
--- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolRecommendations.java
+++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolRecommendations.java
@@ -453,13 +453,6 @@ public class TestProtocolRecommendations {
testDoesNotReturnStaleResponseOnError(req);
}
- @Test
- public void testDoesNotReturnStaleResponseIfClientExplicitlyRequestsFirstHandOneWithPragma() throws Exception {
- final ClassicHttpRequest req = new BasicClassicHttpRequest("GET", "/");
- req.setHeader("Pragma","no-cache");
- testDoesNotReturnStaleResponseOnError(req);
- }
-
@Test
public void testDoesNotReturnStaleResponseIfClientExplicitlyRequestsFreshWithMaxAge() throws Exception {
final ClassicHttpRequest req = new BasicClassicHttpRequest("GET", "/");
diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolRequirements.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolRequirements.java
index 9d5e3f9dc..e8c025795 100644
--- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolRequirements.java
+++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolRequirements.java
@@ -397,13 +397,6 @@ public class TestProtocolRequirements {
testOrderOfMultipleHeadersIsPreservedOnRequests("Expect", post);
}
- @Test
- public void testOrderOfMultiplePragmaHeadersIsPreservedOnRequests() throws Exception {
- request.addHeader("Pragma", "no-cache");
- request.addHeader("Pragma", "x-pragma-1, x-pragma-2");
- testOrderOfMultipleHeadersIsPreservedOnRequests("Pragma", request);
- }
-
@Test
public void testOrderOfMultipleViaHeadersIsPreservedOnRequests() throws Exception {
request.addHeader(HttpHeaders.VIA, "1.0 fred, 1.1 nowhere.com (Apache/1.1)");
@@ -451,13 +444,6 @@ public class TestProtocolRequirements {
testOrderOfMultipleHeadersIsPreservedOnResponses("Content-Language");
}
- @Test
- public void testOrderOfMultiplePragmaHeadersIsPreservedOnResponses() throws Exception {
- originResponse.addHeader("Pragma", "no-cache, x-pragma-2");
- originResponse.addHeader("Pragma", "x-pragma-1");
- testOrderOfMultipleHeadersIsPreservedOnResponses("Pragma");
- }
-
@Test
public void testOrderOfMultipleViaHeadersIsPreservedOnResponses() throws Exception {
originResponse.addHeader(HttpHeaders.VIA, "1.0 fred, 1.1 nowhere.com (Apache/1.1)");
@@ -2765,7 +2751,6 @@ public class TestProtocolRequirements {
r.setHeader("Expires", DateUtils.formatStandardDate(Instant.now().plusSeconds(10)));
r.setHeader("Last-Modified", DateUtils.formatStandardDate(Instant.now().minusSeconds(10)));
r.setHeader("Location", "http://foo.example.com/other2");
- r.setHeader("Pragma", "x-pragma");
r.setHeader("Retry-After","180");
}
@@ -2794,7 +2779,7 @@ public class TestProtocolRequirements {
"Cache-Control", "ETag", "Allow", "Content-Encoding",
"Content-Language", "Content-Length", "Content-Location",
"Content-MD5", "Content-Type", "Expires", "Last-Modified",
- "Location", "Pragma", "Retry-After"
+ "Location", "Retry-After"
};
for(final String h : endToEndHeaders) {
Assertions.assertEquals(HttpTestUtils.getCanonicalHeaderValue(resp1, h),
@@ -2823,7 +2808,6 @@ public class TestProtocolRequirements {
resp2.setHeader("Content-Type","text/html");
resp2.setHeader("Expires", DateUtils.formatStandardDate(Instant.now().plusSeconds(5)));
resp2.setHeader("Location", "http://foo.example.com/new2");
- resp2.setHeader("Pragma","x-new-pragma");
resp2.setHeader("Retry-After","120");
final ClassicHttpRequest req3 = new BasicClassicHttpRequest("GET", "/");
@@ -2839,7 +2823,7 @@ public class TestProtocolRequirements {
final String[] endToEndHeaders = {
"Date", "Cache-Control", "Allow", "Content-Language",
"Content-Location", "Content-Type", "Expires", "Location",
- "Pragma", "Retry-After"
+ "Retry-After"
};
for(final String h : endToEndHeaders) {
Assertions.assertEquals(HttpTestUtils.getCanonicalHeaderValue(resp2, h),
@@ -3893,9 +3877,8 @@ public class TestProtocolRequirements {
testSharedCacheMustUseNewRequestHeadersWhenRevalidatingAuthorizedResponse(resp1);
}
- /* "The request includes a "no-cache" cache-control directive or, for
- * compatibility with HTTP/1.0 clients, "Pragma: no-cache".... The
- * server MUST NOT use a cached copy when responding to such a request."
+ /* "The request includes a "no-cache" cache-control directive...
+ * The server MUST NOT use a cached copy when responding to such a request."
*
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.4
*/
@@ -3933,13 +3916,6 @@ public class TestProtocolRequirements {
testCacheIsNotUsedWhenRespondingToRequest(req);
}
- @Test
- public void testCacheIsNotUsedWhenRespondingToRequestWithPragmaNoCache() throws Exception {
- final ClassicHttpRequest req = new BasicClassicHttpRequest("GET", "/");
- req.setHeader("Pragma","no-cache");
- testCacheIsNotUsedWhenRespondingToRequest(req);
- }
-
/* "When the must-revalidate directive is present in a response received
* by a cache, that cache MUST NOT use the entry after it becomes stale
* to respond to a subsequent request without first revalidating it with
[httpcomponents-client] 04/06: HTTPCLIENT-2277: Revision of the response protocol compliance checks: the caching layer should not attempt to enforce HTTP protocol compliance beyond what it required for correct operation of the caching functionality
Posted by ol...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
olegk pushed a commit to branch 5.4.x
in repository https://gitbox.apache.org/repos/asf/httpcomponents-client.git
commit a1cc5554c01fadda97ea12e268e62670f9227651
Author: Oleg Kalnichevski <ol...@apache.org>
AuthorDate: Mon Jul 24 10:59:01 2023 +0200
HTTPCLIENT-2277: Revision of the response protocol compliance checks: the caching layer should not attempt to enforce HTTP protocol compliance beyond what it required for correct operation of the caching functionality
---
.../client5/http/cache/HttpCacheEntryFactory.java | 33 ++--
.../client5/http/impl/cache/AsyncCachingExec.java | 5 +-
.../hc/client5/http/impl/cache/CachingExec.java | 6 +-
.../client5/http/impl/cache/CachingExecBase.java | 4 -
.../impl/cache/CachingH2AsyncClientBuilder.java | 1 +
.../impl/cache/CachingHttpAsyncClientBuilder.java | 1 +
.../http/impl/cache/CachingHttpClientBuilder.java | 1 +
.../http/impl/cache/ResponseCachingPolicy.java | 6 -
.../impl/cache/ResponseProtocolCompliance.java | 184 ++++-----------------
.../http/cache/TestHttpCacheEntryFactory.java | 18 --
.../http/impl/cache/TestProtocolDeviations.java | 30 ----
.../impl/cache/TestProtocolRecommendations.java | 102 ------------
.../http/impl/cache/TestProtocolRequirements.java | 46 ------
.../http/impl/cache/TestResponseCachingPolicy.java | 6 -
.../impl/cache/TestResponseProtocolCompliance.java | 60 ++++---
15 files changed, 98 insertions(+), 405 deletions(-)
diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/cache/HttpCacheEntryFactory.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/cache/HttpCacheEntryFactory.java
index 2cb033c14..8553bb6d8 100644
--- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/cache/HttpCacheEntryFactory.java
+++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/cache/HttpCacheEntryFactory.java
@@ -36,6 +36,7 @@ import java.util.Set;
import java.util.TreeSet;
import org.apache.hc.client5.http.impl.cache.DateSupport;
+import org.apache.hc.client5.http.utils.DateUtils;
import org.apache.hc.core5.annotation.Contract;
import org.apache.hc.core5.annotation.Internal;
import org.apache.hc.core5.annotation.ThreadingBehavior;
@@ -47,6 +48,7 @@ import org.apache.hc.core5.http.HttpRequest;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.MessageHeaders;
+import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.http.message.HeaderGroup;
import org.apache.hc.core5.http.message.MessageSupport;
import org.apache.hc.core5.util.Args;
@@ -107,22 +109,15 @@ public class HttpCacheEntryFactory {
for (final Iterator<Header> it = entry.headerIterator(); it.hasNext(); ) {
final Header entryHeader = it.next();
final String headerName = entryHeader.getName();
- // Since we do not expect a content in a 304 response, should retain the original Content-Encoding header
- if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_ENCODING)) {
+ if (!response.containsHeader(headerName)) {
headerGroup.addHeader(entryHeader);
- } else {
- if (!response.containsHeader(headerName)) {
- headerGroup.addHeader(entryHeader);
- }
}
}
final Set<String> responseHopByHop = HttpCacheEntryFactory.hopByHopConnectionSpecific(response);
for (final Iterator<Header> it = response.headerIterator(); it.hasNext(); ) {
final Header responseHeader = it.next();
final String headerName = responseHeader.getName();
- // Since we do not expect a content in a 304 response, should update the cache entry with Content-Encoding
- if (!headerName.equalsIgnoreCase(HttpHeaders.CONTENT_ENCODING) &&
- !responseHopByHop.contains(headerName.toLowerCase(Locale.ROOT))) {
+ if (!responseHopByHop.contains(headerName.toLowerCase(Locale.ROOT))) {
headerGroup.addHeader(responseHeader);
}
}
@@ -160,6 +155,12 @@ public class HttpCacheEntryFactory {
return headerGroup;
}
+ static void ensureDate(final HeaderGroup headers, final Instant instant) {
+ if (!headers.containsHeader(HttpHeaders.DATE)) {
+ headers.addHeader(new BasicHeader(HttpHeaders.DATE, DateUtils.formatStandardDate(instant)));
+ }
+ }
+
/**
* Creates a new root {@link HttpCacheEntry} (parent of multiple variants).
*
@@ -180,14 +181,17 @@ public class HttpCacheEntryFactory {
Args.notNull(responseInstant, "Response instant");
Args.notNull(request, "Request");
Args.notNull(response, "Origin response");
+ final HeaderGroup requestHeaders = filterHopByHopHeaders(request);
+ final HeaderGroup responseHeaders = filterHopByHopHeaders(response);
+ ensureDate(responseHeaders, responseInstant);
return new HttpCacheEntry(
requestInstant,
responseInstant,
request.getMethod(),
request.getRequestUri(),
- filterHopByHopHeaders(request),
+ requestHeaders,
response.getCode(),
- filterHopByHopHeaders(response),
+ responseHeaders,
null,
variantMap);
}
@@ -210,14 +214,17 @@ public class HttpCacheEntryFactory {
Args.notNull(responseInstant, "Response instant");
Args.notNull(request, "Request");
Args.notNull(response, "Origin response");
+ final HeaderGroup requestHeaders = filterHopByHopHeaders(request);
+ final HeaderGroup responseHeaders = filterHopByHopHeaders(response);
+ ensureDate(responseHeaders, responseInstant);
return new HttpCacheEntry(
requestInstant,
responseInstant,
request.getMethod(),
request.getRequestUri(),
- filterHopByHopHeaders(request),
+ requestHeaders,
response.getCode(),
- filterHopByHopHeaders(response),
+ responseHeaders,
resource,
null);
}
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 1cda6c85d..38562f30f 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
@@ -111,12 +111,10 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
final CachedHttpResponseGenerator responseGenerator,
final CacheableRequestPolicy cacheableRequestPolicy,
final CachedResponseSuitabilityChecker suitabilityChecker,
- final ResponseProtocolCompliance responseCompliance,
final DefaultAsyncCacheRevalidator cacheRevalidator,
final ConditionalRequestBuilder<HttpRequest> conditionalRequestBuilder,
final CacheConfig config) {
- super(validityPolicy, responseCachingPolicy, responseGenerator, cacheableRequestPolicy,
- suitabilityChecker, responseCompliance, config);
+ super(validityPolicy, responseCachingPolicy, responseGenerator, cacheableRequestPolicy, suitabilityChecker, config);
this.responseCache = responseCache;
this.cacheRevalidator = cacheRevalidator;
this.conditionalRequestBuilder = conditionalRequestBuilder;
@@ -452,7 +450,6 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
public AsyncDataConsumer handleResponse(
final HttpResponse backendResponse,
final EntityDetails entityDetails) throws HttpException, IOException {
- responseCompliance.ensureProtocolCompliance(scope.originalRequest, request, backendResponse);
responseCache.evictInvalidatedEntries(target, request, backendResponse, new FutureCallback<Boolean>() {
@Override
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 3e2963bef..b79b218a2 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
@@ -119,12 +119,10 @@ class CachingExec extends CachingExecBase implements ExecChainHandler {
final CachedHttpResponseGenerator responseGenerator,
final CacheableRequestPolicy cacheableRequestPolicy,
final CachedResponseSuitabilityChecker suitabilityChecker,
- final ResponseProtocolCompliance responseCompliance,
final DefaultCacheRevalidator cacheRevalidator,
final ConditionalRequestBuilder<ClassicHttpRequest> conditionalRequestBuilder,
final CacheConfig config) {
- super(validityPolicy, responseCachingPolicy, responseGenerator, cacheableRequestPolicy,
- suitabilityChecker, responseCompliance, config);
+ super(validityPolicy, responseCachingPolicy, responseGenerator, cacheableRequestPolicy, suitabilityChecker, config);
this.responseCache = responseCache;
this.cacheRevalidator = cacheRevalidator;
this.conditionalRequestBuilder = conditionalRequestBuilder;
@@ -374,8 +372,6 @@ class CachingExec extends CachingExecBase implements ExecChainHandler {
final Instant responseDate,
final ClassicHttpResponse backendResponse) throws IOException {
- responseCompliance.ensureProtocolCompliance(scope.originalRequest, request, backendResponse);
-
responseCache.evictInvalidatedEntries(target, request, backendResponse);
final ResponseCacheControl responseCacheControl = CacheControlHeaderParser.INSTANCE.parse(backendResponse);
final boolean cacheable = responseCachingPolicy.isResponseCacheable(responseCacheControl, request, backendResponse);
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 b29d28a87..16ac29aec 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
@@ -68,7 +68,6 @@ public class CachingExecBase {
final CachedHttpResponseGenerator responseGenerator;
final CacheableRequestPolicy cacheableRequestPolicy;
final CachedResponseSuitabilityChecker suitabilityChecker;
- final ResponseProtocolCompliance responseCompliance;
final CacheConfig cacheConfig;
private static final Logger LOG = LoggerFactory.getLogger(CachingExecBase.class);
@@ -79,14 +78,12 @@ public class CachingExecBase {
final CachedHttpResponseGenerator responseGenerator,
final CacheableRequestPolicy cacheableRequestPolicy,
final CachedResponseSuitabilityChecker suitabilityChecker,
- final ResponseProtocolCompliance responseCompliance,
final CacheConfig config) {
this.responseCachingPolicy = responseCachingPolicy;
this.validityPolicy = validityPolicy;
this.responseGenerator = responseGenerator;
this.cacheableRequestPolicy = cacheableRequestPolicy;
this.suitabilityChecker = suitabilityChecker;
- this.responseCompliance = responseCompliance;
this.cacheConfig = config != null ? config : CacheConfig.DEFAULT;
}
@@ -97,7 +94,6 @@ public class CachingExecBase {
this.responseGenerator = new CachedHttpResponseGenerator(this.validityPolicy);
this.cacheableRequestPolicy = new CacheableRequestPolicy();
this.suitabilityChecker = new CachedResponseSuitabilityChecker(this.validityPolicy, this.cacheConfig);
- this.responseCompliance = new ResponseProtocolCompliance();
this.responseCachingPolicy = new ResponseCachingPolicy(
this.cacheConfig.getMaxObjectSize(),
this.cacheConfig.isSharedCache(),
diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingH2AsyncClientBuilder.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingH2AsyncClientBuilder.java
index 38d96d002..7b8646b82 100644
--- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingH2AsyncClientBuilder.java
+++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingH2AsyncClientBuilder.java
@@ -66,6 +66,7 @@ public class CachingH2AsyncClientBuilder extends H2AsyncClientBuilder {
protected CachingH2AsyncClientBuilder() {
super();
+ addResponseInterceptorFirst(ResponseProtocolCompliance.INSTANCE);
this.deleteCache = true;
}
diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingHttpAsyncClientBuilder.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingHttpAsyncClientBuilder.java
index ee951ef49..a03ed0593 100644
--- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingHttpAsyncClientBuilder.java
+++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingHttpAsyncClientBuilder.java
@@ -66,6 +66,7 @@ public class CachingHttpAsyncClientBuilder extends HttpAsyncClientBuilder {
protected CachingHttpAsyncClientBuilder() {
super();
+ addResponseInterceptorFirst(ResponseProtocolCompliance.INSTANCE);
this.deleteCache = true;
}
diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingHttpClientBuilder.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingHttpClientBuilder.java
index f13c186db..b4fd0f331 100644
--- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingHttpClientBuilder.java
+++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingHttpClientBuilder.java
@@ -62,6 +62,7 @@ public class CachingHttpClientBuilder extends HttpClientBuilder {
protected CachingHttpClientBuilder() {
super();
+ addResponseInterceptorFirst(ResponseProtocolCompliance.INSTANCE);
this.deleteCache = true;
}
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 8237927fc..521683af6 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
@@ -210,12 +210,6 @@ class ResponseCachingPolicy {
return false;
}
- final Instant date = DateUtils.parseStandardDate(response, HttpHeaders.DATE);
- if (date == null) {
- LOG.debug("Invalid / missing Date header");
- return false;
- }
-
final Iterator<HeaderElement> it = MessageSupport.iterate(response, HttpHeaders.VARY);
while (it.hasNext()) {
final HeaderElement elem = it.next();
diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ResponseProtocolCompliance.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ResponseProtocolCompliance.java
index e9c0e229c..79fa549cf 100644
--- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ResponseProtocolCompliance.java
+++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ResponseProtocolCompliance.java
@@ -28,163 +28,51 @@ package org.apache.hc.client5.http.impl.cache;
import java.io.IOException;
import java.time.Instant;
-import java.util.ArrayList;
-import java.util.List;
-import org.apache.hc.client5.http.ClientProtocolException;
-import org.apache.hc.client5.http.utils.DateUtils;
-import org.apache.hc.core5.http.Header;
-import org.apache.hc.core5.http.HeaderElement;
-import org.apache.hc.core5.http.HeaderElements;
+import org.apache.hc.core5.annotation.Contract;
+import org.apache.hc.core5.annotation.ThreadingBehavior;
+import org.apache.hc.core5.http.EntityDetails;
+import org.apache.hc.core5.http.HttpException;
import org.apache.hc.core5.http.HttpHeaders;
-import org.apache.hc.core5.http.HttpRequest;
import org.apache.hc.core5.http.HttpResponse;
+import org.apache.hc.core5.http.HttpResponseInterceptor;
import org.apache.hc.core5.http.HttpStatus;
-import org.apache.hc.core5.http.HttpVersion;
-import org.apache.hc.core5.http.Method;
-import org.apache.hc.core5.http.ProtocolVersion;
import org.apache.hc.core5.http.message.BasicHeader;
-import org.apache.hc.core5.http.message.MessageSupport;
-
-class ResponseProtocolCompliance {
-
- private static final String UNEXPECTED_100_CONTINUE = "The incoming request did not contain a "
- + "100-continue header, but the response was a Status 100, continue.";
- private static final String UNEXPECTED_PARTIAL_CONTENT = "partial content was returned for a request that did not ask for it";
-
- /**
- * When we get a response from a down stream server (Origin Server)
- * we attempt to see if it is HTTP 1.1 Compliant and if not, attempt to
- * make it so.
- *
- * @param originalRequest The original {@link HttpRequest}
- * @param request The {@link HttpRequest} that generated an origin hit and response
- * @param response The {@link HttpResponse} from the origin server
- * @throws IOException Bad things happened
- */
- public void ensureProtocolCompliance(
- final HttpRequest originalRequest,
- final HttpRequest request,
- final HttpResponse response) throws IOException {
- requestDidNotExpect100ContinueButResponseIsOne(originalRequest, response);
-
- transferEncodingIsNotReturnedTo1_0Client(originalRequest, response);
-
- ensurePartialContentIsNotSentToAClientThatDidNotRequestIt(request, response);
-
- ensure200ForOPTIONSRequestWithNoBodyHasContentLengthZero(request, response);
-
- ensure206ContainsDateHeader(response);
-
- ensure304DoesNotContainExtraEntityHeaders(response);
-
- identityIsNotUsedInContentEncoding(response);
- }
-
- private void identityIsNotUsedInContentEncoding(final HttpResponse response) {
- final Header[] hdrs = response.getHeaders(HttpHeaders.CONTENT_ENCODING);
- if (hdrs == null || hdrs.length == 0) {
- return;
- }
- final List<Header> newHeaders = new ArrayList<>();
- boolean modified = false;
- for (final Header h : hdrs) {
- final StringBuilder buf = new StringBuilder();
- boolean first = true;
- for (final HeaderElement elt : MessageSupport.parse(h)) {
- if ("identity".equalsIgnoreCase(elt.getName())) {
- modified = true;
- } else {
- if (!first) {
- buf.append(",");
- }
- buf.append(elt);
- first = false;
- }
- }
- final String newHeaderValue = buf.toString();
- if (!newHeaderValue.isEmpty()) {
- newHeaders.add(new BasicHeader(HttpHeaders.CONTENT_ENCODING, newHeaderValue));
- }
- }
- if (!modified) {
- return;
- }
- response.removeHeaders(HttpHeaders.CONTENT_ENCODING);
- for (final Header h : newHeaders) {
- response.addHeader(h);
- }
- }
-
- private void ensure206ContainsDateHeader(final HttpResponse response) {
- if (response.getFirstHeader(HttpHeaders.DATE) == null) {
- response.addHeader(HttpHeaders.DATE, DateUtils.formatStandardDate(Instant.now()));
- }
-
- }
-
- private void ensurePartialContentIsNotSentToAClientThatDidNotRequestIt(final HttpRequest request,
- final HttpResponse response) throws IOException {
- if (request.getFirstHeader(HttpHeaders.RANGE) != null
- || response.getCode() != HttpStatus.SC_PARTIAL_CONTENT) {
- return;
- }
- throw new ClientProtocolException(UNEXPECTED_PARTIAL_CONTENT);
- }
-
- private void ensure200ForOPTIONSRequestWithNoBodyHasContentLengthZero(final HttpRequest request,
- final HttpResponse response) {
- if (!Method.OPTIONS.isSame(request.getMethod())) {
- return;
- }
-
- if (response.getCode() != HttpStatus.SC_OK) {
- return;
- }
-
- if (response.getFirstHeader(HttpHeaders.CONTENT_LENGTH) == null) {
- response.addHeader(HttpHeaders.CONTENT_LENGTH, "0");
- }
- }
-
- private void ensure304DoesNotContainExtraEntityHeaders(final HttpResponse response) {
- final String[] disallowedEntityHeaders = { HttpHeaders.ALLOW, HttpHeaders.CONTENT_ENCODING,
- "Content-Language", HttpHeaders.CONTENT_LENGTH, "Content-MD5",
- "Content-Range", HttpHeaders.CONTENT_TYPE, HttpHeaders.LAST_MODIFIED
- };
+import org.apache.hc.core5.http.protocol.HttpContext;
+
+/**
+ * This response interceptor removes common {@literal Content-} headers from the 304
+ * response messages based on the provision of the HTTP specification that 304
+ * status code represents a confirmation that the requested resource content has
+ * not changed since its retrieval or the last update and adds {@literal Date}
+ * header if it is not present in the response message..
+ */
+@Contract(threading = ThreadingBehavior.IMMUTABLE)
+class ResponseProtocolCompliance implements HttpResponseInterceptor {
+
+ public static final ResponseProtocolCompliance INSTANCE = new ResponseProtocolCompliance();
+
+ private final static String[] DISALLOWED_ENTITY_HEADERS = {
+ HttpHeaders.CONTENT_ENCODING,
+ HttpHeaders.CONTENT_LANGUAGE,
+ HttpHeaders.CONTENT_LENGTH,
+ HttpHeaders.CONTENT_MD5,
+ HttpHeaders.CONTENT_RANGE,
+ HttpHeaders.CONTENT_TYPE
+ };
+
+ @Override
+ public void process(final HttpResponse response,
+ final EntityDetails entity,
+ final HttpContext context) throws HttpException, IOException {
if (response.getCode() == HttpStatus.SC_NOT_MODIFIED) {
- for(final String hdr : disallowedEntityHeaders) {
- response.removeHeaders(hdr);
+ for (final String headerName : DISALLOWED_ENTITY_HEADERS) {
+ response.removeHeaders(headerName);
}
}
- }
-
- private void requestDidNotExpect100ContinueButResponseIsOne(
- final HttpRequest originalRequest, final HttpResponse response) throws IOException {
- if (response.getCode() != HttpStatus.SC_CONTINUE) {
- return;
- }
-
- final Header header = originalRequest.getFirstHeader(HttpHeaders.EXPECT);
- if (header != null && header.getValue().equalsIgnoreCase(HeaderElements.CONTINUE)) {
- return;
+ if (!response.containsHeader(HttpHeaders.DATE)) {
+ response.addHeader(new BasicHeader(HttpHeaders.DATE, Instant.now()));
}
- throw new ClientProtocolException(UNEXPECTED_100_CONTINUE);
- }
-
- private void transferEncodingIsNotReturnedTo1_0Client(
- final HttpRequest originalRequest, final HttpResponse response) {
- final ProtocolVersion version = originalRequest.getVersion() != null ? originalRequest.getVersion() : HttpVersion.DEFAULT;
- if (version.compareToVersion(HttpVersion.HTTP_1_1) >= 0) {
- return;
- }
-
- removeResponseTransferEncoding(response);
- }
-
- private void removeResponseTransferEncoding(final HttpResponse response) {
- response.removeHeaders("TE");
- response.removeHeaders(HttpHeaders.TRANSFER_ENCODING);
}
}
diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/cache/TestHttpCacheEntryFactory.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/cache/TestHttpCacheEntryFactory.java
index 0c35cd130..5a7f94ccf 100644
--- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/cache/TestHttpCacheEntryFactory.java
+++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/cache/TestHttpCacheEntryFactory.java
@@ -49,7 +49,6 @@ import org.apache.hc.core5.http.message.BasicHttpResponse;
import org.apache.hc.core5.http.message.HeaderGroup;
import org.apache.hc.core5.http.support.BasicResponseBuilder;
import org.hamcrest.MatcherAssert;
-import org.hamcrest.Matchers;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -207,23 +206,6 @@ public class TestHttpCacheEntryFactory {
MatcherAssert.assertThat(mergedHeaders, ContainsHeaderMatcher.contains("ETag", "\"new\""));
}
- @Test
- public void testContentEncodingHeaderIsNotUpdatedByMerge() {
- entry = HttpTestUtils.makeCacheEntry(
- new BasicHeader("Date", DateUtils.formatStandardDate(requestDate)),
- new BasicHeader("ETag", "\"etag\""),
- new BasicHeader("Content-Encoding", "identity"));
- response.setHeaders(
- new BasicHeader("Last-Modified", DateUtils.formatStandardDate(responseDate)),
- new BasicHeader("Cache-Control", "public"),
- new BasicHeader("Content-Encoding", "gzip"));
-
- final HeaderGroup mergedHeaders = impl.mergeHeaders(entry, response);
-
- MatcherAssert.assertThat(mergedHeaders, ContainsHeaderMatcher.contains("Content-Encoding", "identity"));
- MatcherAssert.assertThat(mergedHeaders, Matchers.not(ContainsHeaderMatcher.contains("Content-Encoding", "gzip")));
- }
-
@Test
public void testUpdateCacheEntryReturnsDifferentEntryInstance() {
entry = HttpTestUtils.makeCacheEntry();
diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolDeviations.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolDeviations.java
index 65376be99..de084a838 100644
--- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolDeviations.java
+++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolDeviations.java
@@ -30,7 +30,6 @@ import java.io.IOException;
import java.time.Instant;
import java.util.Random;
-import org.apache.hc.client5.http.ClientProtocolException;
import org.apache.hc.client5.http.HttpRoute;
import org.apache.hc.client5.http.cache.HttpCacheContext;
import org.apache.hc.client5.http.classic.ExecChain;
@@ -132,35 +131,6 @@ public class TestProtocolDeviations {
return new ByteArrayEntity(bytes, null);
}
- /*
- * "10.2.7 206 Partial Content ... The request MUST have included a Range
- * header field (section 14.35) indicating the desired range, and MAY have
- * included an If-Range header field (section 14.27) to make the request
- * conditional."
- *
- * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.7
- */
- @Test
- public void testPartialContentIsNotReturnedToAClientThatDidNotAskForIt() throws Exception {
-
- // tester's note: I don't know what the cache will *do* in
- // this situation, but it better not just pass the response
- // on.
- request.removeHeaders("Range");
- originResponse = new BasicClassicHttpResponse(HttpStatus.SC_PARTIAL_CONTENT, "Partial Content");
- originResponse.setHeader("Content-Range", "bytes 0-499/1234");
- originResponse.setEntity(makeBody(500));
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(originResponse);
-
- try {
- final HttpResponse result = execute(request);
- Assertions.assertTrue(HttpStatus.SC_PARTIAL_CONTENT != result.getCode());
- } catch (final ClientProtocolException acceptableBehavior) {
- // this is probably ok
- }
- }
-
/*
* "10.4.2 401 Unauthorized ... The response MUST include a WWW-Authenticate
* header field (section 14.47) containing a challenge applicable to the
diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolRecommendations.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolRecommendations.java
index e4839e59a..23d80e5ea 100644
--- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolRecommendations.java
+++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolRecommendations.java
@@ -133,31 +133,6 @@ public class TestProtocolRecommendations {
mockExecChain);
}
- /* "identity: The default (identity) encoding; the use of no
- * transformation whatsoever. This content-coding is used only in the
- * Accept-Encoding header, and SHOULD NOT be used in the
- * Content-Encoding header."
- *
- * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.5
- */
- @Test
- public void testIdentityCodingIsNotUsedInContentEncodingHeader() throws Exception {
- originResponse.setHeader("Content-Encoding", "identity");
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(originResponse);
-
- final ClassicHttpResponse result = execute(request);
-
- boolean foundIdentity = false;
- final Iterator<HeaderElement> it = MessageSupport.iterate(result, HttpHeaders.CONTENT_ENCODING);
- while (it.hasNext()) {
- final HeaderElement elt = it.next();
- if ("identity".equalsIgnoreCase(elt.getName())) {
- foundIdentity = true;
- }
- }
- assertFalse(foundIdentity);
- }
-
/*
* "304 Not Modified. ... If the conditional GET used a strong cache
* validator (see section 13.3.3), the response SHOULD NOT include
@@ -335,83 +310,6 @@ public class TestProtocolRecommendations {
"Last-Modified", DateUtils.formatStandardDate(twoMinutesAgo));
}
- private void shouldStripEntityHeaderFromOrigin304ResponseToStrongValidation(
- final String entityHeader, final String entityHeaderValue) throws Exception {
- final ClassicHttpRequest req = HttpTestUtils.makeDefaultRequest();
- req.setHeader("If-None-Match", "\"etag\"");
-
- final ClassicHttpResponse resp = new BasicClassicHttpResponse(HttpStatus.SC_NOT_MODIFIED, "Not Modified");
- resp.setHeader("Date", DateUtils.formatStandardDate(now));
- resp.setHeader("Etag", "\"etag\"");
- resp.setHeader(entityHeader, entityHeaderValue);
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp);
-
- final ClassicHttpResponse result = execute(req);
-
- assertFalse(result.containsHeader(entityHeader));
- }
-
- @Test
- public void shouldStripAllowFromOrigin304ResponseToStrongValidation() throws Exception {
- shouldStripEntityHeaderFromOrigin304ResponseToStrongValidation(
- "Allow", "GET,HEAD");
- }
-
- @Test
- public void shouldStripContentEncodingFromOrigin304ResponseToStrongValidation() throws Exception {
- shouldStripEntityHeaderFromOrigin304ResponseToStrongValidation(
- "Content-Encoding", "gzip");
- }
-
- @Test
- public void shouldStripContentLanguageFromOrigin304ResponseToStrongValidation() throws Exception {
- shouldStripEntityHeaderFromOrigin304ResponseToStrongValidation(
- "Content-Language", "en");
- }
-
- @Test
- public void shouldStripContentLengthFromOrigin304ResponseToStrongValidation() throws Exception {
- shouldStripEntityHeaderFromOrigin304ResponseToStrongValidation(
- "Content-Length", "128");
- }
-
- @Test
- public void shouldStripContentMD5FromOrigin304ResponseToStrongValidation() throws Exception {
- shouldStripEntityHeaderFromOrigin304ResponseToStrongValidation(
- "Content-MD5", "Q2hlY2sgSW50ZWdyaXR5IQ==");
- }
-
- @Test
- public void shouldStripContentTypeFromOrigin304ResponseToStrongValidation() throws Exception {
- shouldStripEntityHeaderFromOrigin304ResponseToStrongValidation(
- "Content-Type", "text/html;charset=utf-8");
- }
-
- @Test
- public void shouldStripContentRangeFromOrigin304ResponseToStringValidation() throws Exception {
- final ClassicHttpRequest req = HttpTestUtils.makeDefaultRequest();
- req.setHeader("If-Range","\"etag\"");
- req.setHeader("Range","bytes=0-127");
-
- final ClassicHttpResponse resp = new BasicClassicHttpResponse(HttpStatus.SC_NOT_MODIFIED, "Not Modified");
- resp.setHeader("Date", DateUtils.formatStandardDate(now));
- resp.setHeader("ETag", "\"etag\"");
- resp.setHeader("Content-Range", "bytes 0-127/256");
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp);
-
- final ClassicHttpResponse result = execute(req);
-
- assertFalse(result.containsHeader("Content-Range"));
- }
-
- @Test
- public void shouldStripLastModifiedFromOrigin304ResponseToStrongValidation() throws Exception {
- shouldStripEntityHeaderFromOrigin304ResponseToStrongValidation(
- "Last-Modified", DateUtils.formatStandardDate(twoMinutesAgo));
- }
-
/*
* "For this reason, a cache SHOULD NOT return a stale response if the
* client explicitly requests a first-hand or fresh one, unless it is
diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolRequirements.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolRequirements.java
index d75c79a72..7b10ecaf4 100644
--- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolRequirements.java
+++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolRequirements.java
@@ -40,7 +40,6 @@ import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import org.apache.hc.client5.http.ClientProtocolException;
import org.apache.hc.client5.http.HttpRoute;
import org.apache.hc.client5.http.auth.StandardAuthScheme;
import org.apache.hc.client5.http.cache.HttpCacheEntry;
@@ -619,31 +618,6 @@ public class TestProtocolRequirements {
// which is tested by the previous few tests.
}
- /*
- * "A proxy MUST NOT forward a 100 (Continue) response if the request
- * message was received from an HTTP/1.0 (or earlier) client and did not
- * include an Expect request-header field with the '100-continue'
- * expectation. This requirement overrides the general rule for forwarding
- * of 1xx responses (see section 10.1)."
- *
- * http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.2.3
- */
- @Test
- public void test100ContinueResponsesAreNotForwardedTo1_0ClientsWhoDidNotAskForThem() throws Exception {
-
- final BasicClassicHttpRequest post = new BasicClassicHttpRequest("POST", "/");
- post.setVersion(new ProtocolVersion("HTTP", 1, 0));
- post.setEntity(body);
- post.setHeader("Content-Length", "128");
-
- originResponse = new BasicClassicHttpResponse(100, "Continue");
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(originResponse);
-
- // if a 100 response gets up to us from the HttpClient
- // backend, we can't really handle it at that point
- Assertions.assertThrows(ClientProtocolException.class, () -> execute(post));
- }
-
/*
* "9.2 OPTIONS. ...Responses to this method are not cacheable.
*
@@ -981,24 +955,6 @@ public class TestProtocolRequirements {
Mockito.verify(mockExecChain, Mockito.times(1)).proceed(Mockito.any(), Mockito.any());
}
- @Test
- public void test206ResponseReturnedToClientMustHaveDateHeader() throws Exception {
- request.addHeader("Range", "bytes=0-50");
- originResponse = new BasicClassicHttpResponse(HttpStatus.SC_PARTIAL_CONTENT, "Partial Content");
- originResponse.setHeader("Date", DateUtils.formatStandardDate(Instant.now()));
- originResponse.setHeader("Server", "MockOrigin/1.0");
- originResponse.setEntity(HttpTestUtils.makeBody(500));
- originResponse.setHeader("Content-Range", "bytes 0-499/1234");
- originResponse.removeHeaders("Date");
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(originResponse);
-
- final ClassicHttpResponse result = execute(request);
- Assertions.assertTrue(result.getCode() != HttpStatus.SC_PARTIAL_CONTENT
- || result.getFirstHeader("Date") != null);
-
- }
-
@Test
public void test206ContainsETagIfA200ResponseWouldHaveIncludedIt() throws Exception {
final ClassicHttpRequest req1 = new BasicClassicHttpRequest("GET", "/");
@@ -4131,8 +4087,6 @@ public class TestProtocolRequirements {
/* "A received message that does not have a Date header field MUST be
* assigned one by the recipient if the message will be cached by that
* recipient or gatewayed via a protocol which requires a Date."
- *
- * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.18
*/
@Test
public void testCachedResponsesWithMissingDateHeadersShouldBeAssignedOne() throws Exception {
diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestResponseCachingPolicy.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestResponseCachingPolicy.java
index 7ec81cdca..3c148a380 100644
--- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestResponseCachingPolicy.java
+++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestResponseCachingPolicy.java
@@ -607,12 +607,6 @@ public class TestResponseCachingPolicy {
Assertions.assertFalse(policy.isResponseCacheable(responseCacheControl, request, response));
}
- @Test
- public void testResponsesWithoutDateHeadersAreNotCacheable() {
- response.removeHeaders("Date");
- Assertions.assertFalse(policy.isResponseCacheable(responseCacheControl, "GET", response));
- }
-
@Test
public void testResponseThatHasTooMuchContentIsNotCacheable() {
response.setHeader("Content-Length", "9000");
diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestResponseProtocolCompliance.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestResponseProtocolCompliance.java
index e25859b69..4ca1003c1 100644
--- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestResponseProtocolCompliance.java
+++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestResponseProtocolCompliance.java
@@ -26,17 +26,14 @@
*/
package org.apache.hc.client5.http.impl.cache;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+
import java.time.Instant;
-import org.apache.hc.client5.http.ClientProtocolException;
-import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.utils.DateUtils;
-import org.apache.hc.core5.http.HttpRequest;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.HttpStatus;
-import org.apache.hc.core5.http.message.BasicHttpResponse;
-import org.apache.hc.core5.http.support.BasicRequestBuilder;
-import org.junit.jupiter.api.Assertions;
+import org.apache.hc.core5.http.support.BasicResponseBuilder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -46,31 +43,48 @@ public class TestResponseProtocolCompliance {
@BeforeEach
public void setUp() {
- impl = new ResponseProtocolCompliance();
+ impl = ResponseProtocolCompliance.INSTANCE;
+ }
+
+ private void shouldStripEntityHeaderFromOrigin304ResponseToStrongValidation(
+ final String entityHeader, final String entityHeaderValue) throws Exception {
+ final HttpResponse response = BasicResponseBuilder.create(HttpStatus.SC_NOT_MODIFIED)
+ .addHeader("Date", DateUtils.formatStandardDate(Instant.now()))
+ .addHeader("Etag", "\"etag\"")
+ .addHeader(entityHeader, entityHeaderValue)
+ .build();
+ impl.process(response, null, null);
+ assertFalse(response.containsHeader(entityHeader));
+ }
+
+ @Test
+ public void shouldStripContentEncodingFromOrigin304ResponseToStrongValidation() throws Exception {
+ shouldStripEntityHeaderFromOrigin304ResponseToStrongValidation(
+ "Content-Encoding", "gzip");
}
- private void setMinimalResponseHeaders(final HttpResponse resp) {
- resp.setHeader("Date", DateUtils.formatStandardDate(Instant.now()));
- resp.setHeader("Server", "MyServer/1.0");
+ @Test
+ public void shouldStripContentLanguageFromOrigin304ResponseToStrongValidation() throws Exception {
+ shouldStripEntityHeaderFromOrigin304ResponseToStrongValidation(
+ "Content-Language", "en");
}
- private HttpResponse makePartialResponse(final int nbytes) {
- final HttpResponse resp = new BasicHttpResponse(HttpStatus.SC_PARTIAL_CONTENT, "Partial Content");
- setMinimalResponseHeaders(resp);
- resp.setHeader("Content-Length","" + nbytes);
- resp.setHeader("Content-Range","0-127/256");
- return resp;
+ @Test
+ public void shouldStripContentLengthFromOrigin304ResponseToStrongValidation() throws Exception {
+ shouldStripEntityHeaderFromOrigin304ResponseToStrongValidation(
+ "Content-Length", "128");
}
@Test
- public void throwsExceptionIfOriginReturnsPartialResponseWhenNotRequested() throws Exception {
- final HttpGet req = new HttpGet("http://foo.example.com/");
- final HttpRequest wrapper = BasicRequestBuilder.copy(req).build();
- final int nbytes = 128;
- final HttpResponse resp = makePartialResponse(nbytes);
+ public void shouldStripContentMD5FromOrigin304ResponseToStrongValidation() throws Exception {
+ shouldStripEntityHeaderFromOrigin304ResponseToStrongValidation(
+ "Content-MD5", "Q2hlY2sgSW50ZWdyaXR5IQ==");
+ }
- Assertions.assertThrows(ClientProtocolException.class, () ->
- impl.ensureProtocolCompliance(wrapper, req, resp));
+ @Test
+ public void shouldStripContentTypeFromOrigin304ResponseToStrongValidation() throws Exception {
+ shouldStripEntityHeaderFromOrigin304ResponseToStrongValidation(
+ "Content-Type", "text/html;charset=utf-8");
}
}
[httpcomponents-client] 06/06: Removed unused method argument
Posted by ol...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
olegk pushed a commit to branch 5.4.x
in repository https://gitbox.apache.org/repos/asf/httpcomponents-client.git
commit 6bdd389356f3651ff604da6d48eb12e246bc92de
Author: Oleg Kalnichevski <ol...@apache.org>
AuthorDate: Sun Aug 20 12:28:51 2023 +0200
Removed unused method argument
---
.../org/apache/hc/client5/http/impl/cache/AsyncCachingExec.java | 6 +++---
.../java/org/apache/hc/client5/http/impl/cache/CachingExec.java | 6 +++---
.../java/org/apache/hc/client5/http/impl/cache/CachingExecBase.java | 1 -
.../apache/hc/client5/http/impl/cache/CachingHttpClientBuilder.java | 2 +-
4 files changed, 7 insertions(+), 8 deletions(-)
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 38562f30f..bf99622cc 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
@@ -606,7 +606,7 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
}
LOG.debug("Cache hit");
try {
- final SimpleHttpResponse cacheResponse = generateCachedResponse(responseCacheControl, hit.entry, request, context);
+ final SimpleHttpResponse cacheResponse = generateCachedResponse(hit.entry, request, context);
triggerResponse(cacheResponse, scope, asyncExecCallback);
} catch (final ResourceIOException ex) {
recordCacheFailure(target, request);
@@ -634,7 +634,7 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
&& (validityPolicy.mayReturnStaleWhileRevalidating(responseCacheControl, hit.entry, now) || staleIfErrorEnabled)) {
LOG.debug("Serving stale with asynchronous revalidation");
try {
- final SimpleHttpResponse cacheResponse = generateCachedResponse(responseCacheControl, hit.entry, request, context);
+ final SimpleHttpResponse cacheResponse = generateCachedResponse(hit.entry, request, context);
final String exchangeId = ExecSupport.getNextExchangeId();
context.setExchangeId(exchangeId);
final AsyncExecChain.Scope fork = new AsyncExecChain.Scope(
@@ -658,7 +658,7 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
LOG.debug("Serving stale response due to IOException and stale-if-error enabled");
}
try {
- final SimpleHttpResponse cacheResponse = generateCachedResponse(responseCacheControl, hit.entry, request, context);
+ final SimpleHttpResponse cacheResponse = generateCachedResponse(hit.entry, request, context);
triggerResponse(cacheResponse, scope, asyncExecCallback);
} catch (final ResourceIOException ex2) {
if (LOG.isDebugEnabled()) {
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 b79b218a2..c42b2b844 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
@@ -256,7 +256,7 @@ class CachingExec extends CachingExecBase implements ExecChainHandler {
}
LOG.debug("Cache hit");
try {
- return convert(generateCachedResponse(responseCacheControl, hit.entry, request, context), scope);
+ return convert(generateCachedResponse(hit.entry, request, context), scope);
} catch (final ResourceIOException ex) {
recordCacheFailure(target, request);
if (!mayCallBackend(requestCacheControl)) {
@@ -284,7 +284,7 @@ class CachingExec extends CachingExecBase implements ExecChainHandler {
scope.originalRequest,
scope.execRuntime.fork(null),
HttpClientContext.create());
- final SimpleHttpResponse response = generateCachedResponse(responseCacheControl, hit.entry, request, context);
+ final SimpleHttpResponse response = generateCachedResponse(hit.entry, request, context);
cacheRevalidator.revalidateCacheEntry(
hit.getEntryKey(),
() -> revalidateCacheEntry(requestCacheControl, responseCacheControl, hit, target, request, fork, chain));
@@ -296,7 +296,7 @@ class CachingExec extends CachingExecBase implements ExecChainHandler {
if (LOG.isDebugEnabled()) {
LOG.debug("Serving stale response due to IOException and stale-if-error enabled");
}
- return convert(generateCachedResponse(responseCacheControl, hit.entry, request, context), scope);
+ return convert(generateCachedResponse(hit.entry, request, context), scope);
}
return convert(handleRevalidationFailure(requestCacheControl, responseCacheControl, hit.entry, request, context, now), scope);
}
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 16ac29aec..e9c781fa8 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
@@ -157,7 +157,6 @@ public class CachingExecBase {
}
SimpleHttpResponse generateCachedResponse(
- final ResponseCacheControl responseCacheControl,
final HttpCacheEntry entry,
final HttpRequest request,
final HttpContext context) throws ResourceIOException {
diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingHttpClientBuilder.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingHttpClientBuilder.java
index aa9b992d4..ebbd19dd9 100644
--- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingHttpClientBuilder.java
+++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingHttpClientBuilder.java
@@ -95,7 +95,7 @@ public class CachingHttpClientBuilder extends HttpClientBuilder {
* @deprecated Do not use.
*/
@Deprecated
- public final CachingHttpClientBuilder setHttpCacheInvalidator(final org.apache.hc.client5.http.cache.HttpAsyncCacheInvalidator cacheInvalidator) {
+ public final CachingHttpClientBuilder setHttpCacheInvalidator(final org.apache.hc.client5.http.cache.HttpCacheInvalidator cacheInvalidator) {
return this;
}
[httpcomponents-client] 01/06: HTTPCLIENT-2277: Removal of deprecated `Warning` header support
Posted by ol...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
olegk pushed a commit to branch 5.4.x
in repository https://gitbox.apache.org/repos/asf/httpcomponents-client.git
commit 6d55e7a4b9ee0ed9f4756354f822b090ff99c68f
Author: Oleg Kalnichevski <ol...@apache.org>
AuthorDate: Sun Jul 16 14:36:46 2023 +0200
HTTPCLIENT-2277: Removal of deprecated `Warning` header support
---
.../client5/http/cache/HttpCacheEntryFactory.java | 6 -
.../client5/http/impl/cache/AsyncCachingExec.java | 7 +-
.../http/impl/cache/CacheRevalidatorBase.java | 25 -
.../hc/client5/http/impl/cache/CachingExec.java | 7 +-
.../client5/http/impl/cache/CachingExecBase.java | 25 +-
.../impl/cache/DefaultAsyncCacheRevalidator.java | 2 +-
.../http/impl/cache/DefaultCacheRevalidator.java | 2 +-
.../impl/cache/ResponseProtocolCompliance.java | 35 --
.../hc/client5/http/impl/cache/WarningValue.java | 368 ---------------
.../http/cache/TestHttpCacheEntryFactory.java | 14 -
.../hc/client5/http/impl/cache/HttpTestUtils.java | 18 -
.../http/impl/cache/TestCacheRevalidatorBase.java | 24 -
.../http/impl/cache/TestCachingExecChain.java | 148 ------
.../impl/cache/TestProtocolRecommendations.java | 108 -----
.../http/impl/cache/TestProtocolRequirements.java | 503 ---------------------
.../http/impl/cache/TestRFC5861Compliance.java | 390 ----------------
.../client5/http/impl/cache/TestWarningValue.java | 230 ----------
17 files changed, 9 insertions(+), 1903 deletions(-)
diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/cache/HttpCacheEntryFactory.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/cache/HttpCacheEntryFactory.java
index 3ac432b6a..2cb033c14 100644
--- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/cache/HttpCacheEntryFactory.java
+++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/cache/HttpCacheEntryFactory.java
@@ -110,12 +110,6 @@ public class HttpCacheEntryFactory {
// Since we do not expect a content in a 304 response, should retain the original Content-Encoding header
if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_ENCODING)) {
headerGroup.addHeader(entryHeader);
- } else if (headerName.equalsIgnoreCase(HttpHeaders.WARNING)) {
- // remove cache entry 1xx warnings
- final String warningValue = entryHeader.getValue();
- if (warningValue != null && !warningValue.startsWith("1")) {
- headerGroup.addHeader(entryHeader);
- }
} else {
if (!response.containsHeader(headerName)) {
headerGroup.addHeader(entryHeader);
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 e6ac0f091..df410eba6 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
@@ -617,7 +617,7 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
}
LOG.debug("Cache hit");
try {
- final SimpleHttpResponse cacheResponse = generateCachedResponse(responseCacheControl, hit.entry, request, context, now);
+ final SimpleHttpResponse cacheResponse = generateCachedResponse(responseCacheControl, hit.entry, request, context);
triggerResponse(cacheResponse, scope, asyncExecCallback);
} catch (final ResourceIOException ex) {
recordCacheFailure(target, request);
@@ -645,7 +645,7 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
&& (validityPolicy.mayReturnStaleWhileRevalidating(responseCacheControl, hit.entry, now) || staleIfErrorEnabled)) {
LOG.debug("Serving stale with asynchronous revalidation");
try {
- final SimpleHttpResponse cacheResponse = generateCachedResponse(responseCacheControl, hit.entry, request, context, now);
+ final SimpleHttpResponse cacheResponse = generateCachedResponse(responseCacheControl, hit.entry, request, context);
final String exchangeId = ExecSupport.getNextExchangeId();
context.setExchangeId(exchangeId);
final AsyncExecChain.Scope fork = new AsyncExecChain.Scope(
@@ -669,7 +669,7 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
LOG.debug("Serving stale response due to IOException and stale-if-error enabled");
}
try {
- final SimpleHttpResponse cacheResponse = generateCachedResponse(responseCacheControl, hit.entry, request, context, now);
+ final SimpleHttpResponse cacheResponse = generateCachedResponse(responseCacheControl, hit.entry, request, context);
triggerResponse(cacheResponse, scope, asyncExecCallback);
} catch (final ResourceIOException ex2) {
if (LOG.isDebugEnabled()) {
@@ -752,7 +752,6 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
void triggerResponseStaleCacheEntry() {
try {
final SimpleHttpResponse cacheResponse = responseGenerator.generateResponse(request, hit.entry);
- cacheResponse.addHeader(HttpHeaders.WARNING, "110 localhost \"Response is stale\"");
triggerResponse(cacheResponse, scope, asyncExecCallback);
} catch (final ResourceIOException ex) {
asyncExecCallback.failed(ex);
diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheRevalidatorBase.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheRevalidatorBase.java
index 90465e346..6ba99d344 100644
--- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheRevalidatorBase.java
+++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheRevalidatorBase.java
@@ -29,7 +29,6 @@ package org.apache.hc.client5.http.impl.cache;
import java.io.Closeable;
import java.io.IOException;
import java.util.HashSet;
-import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
@@ -39,9 +38,6 @@ import java.util.concurrent.ScheduledThreadPoolExecutor;
import org.apache.hc.client5.http.schedule.ConcurrentCountMap;
import org.apache.hc.client5.http.schedule.SchedulingStrategy;
-import org.apache.hc.core5.http.Header;
-import org.apache.hc.core5.http.HttpHeaders;
-import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.util.Args;
import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;
@@ -167,25 +163,4 @@ class CacheRevalidatorBase implements Closeable {
}
}
- /**
- * Determines if the given response is generated from a stale cache entry.
- * @param httpResponse the response to be checked
- * @return whether the response is stale or not
- */
- boolean isStale(final HttpResponse httpResponse) {
- for (final Iterator<Header> it = httpResponse.headerIterator(HttpHeaders.WARNING); it.hasNext(); ) {
- /*
- * warn-codes
- * 110 = Response is stale
- * 111 = Revalidation failed
- */
- final Header warning = it.next();
- final String warningValue = warning.getValue();
- if (warningValue.startsWith("110") || warningValue.startsWith("111")) {
- return true;
- }
- }
- 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 ec5e6cc53..e1fecc5f2 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
@@ -265,7 +265,7 @@ class CachingExec extends CachingExecBase implements ExecChainHandler {
}
LOG.debug("Cache hit");
try {
- return convert(generateCachedResponse(responseCacheControl, hit.entry, request, context, now), scope);
+ return convert(generateCachedResponse(responseCacheControl, hit.entry, request, context), scope);
} catch (final ResourceIOException ex) {
recordCacheFailure(target, request);
if (!mayCallBackend(requestCacheControl)) {
@@ -293,7 +293,7 @@ class CachingExec extends CachingExecBase implements ExecChainHandler {
scope.originalRequest,
scope.execRuntime.fork(null),
HttpClientContext.create());
- final SimpleHttpResponse response = generateCachedResponse(responseCacheControl, hit.entry, request, context, now);
+ final SimpleHttpResponse response = generateCachedResponse(responseCacheControl, hit.entry, request, context);
cacheRevalidator.revalidateCacheEntry(
hit.getEntryKey(),
() -> revalidateCacheEntry(requestCacheControl, responseCacheControl, hit, target, request, fork, chain));
@@ -305,7 +305,7 @@ class CachingExec extends CachingExecBase implements ExecChainHandler {
if (LOG.isDebugEnabled()) {
LOG.debug("Serving stale response due to IOException and stale-if-error enabled");
}
- return convert(generateCachedResponse(responseCacheControl, hit.entry, request, context, now), scope);
+ return convert(generateCachedResponse(responseCacheControl, hit.entry, request, context), scope);
}
return convert(handleRevalidationFailure(requestCacheControl, responseCacheControl, hit.entry, request, context, now), scope);
}
@@ -361,7 +361,6 @@ class CachingExec extends CachingExecBase implements ExecChainHandler {
&& validityPolicy.mayReturnStaleIfError(requestCacheControl, responseCacheControl, hit.entry, responseDate)) {
try {
final SimpleHttpResponse cachedResponse = responseGenerator.generateResponse(request, hit.entry);
- cachedResponse.addHeader(HttpHeaders.WARNING, "110 localhost \"Response is stale\"");
return convert(cachedResponse, scope);
} finally {
backendResponse.close();
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 af8d4ea10..3531fae16 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
@@ -38,7 +38,6 @@ import org.apache.hc.client5.http.cache.CacheResponseStatus;
import org.apache.hc.client5.http.cache.HttpCacheContext;
import org.apache.hc.client5.http.cache.HttpCacheEntry;
import org.apache.hc.client5.http.cache.ResourceIOException;
-import org.apache.hc.client5.http.utils.DateUtils;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.HttpHost;
@@ -187,8 +186,7 @@ public class CachingExecBase {
final ResponseCacheControl responseCacheControl,
final HttpCacheEntry entry,
final HttpRequest request,
- final HttpContext context,
- final Instant now) throws ResourceIOException {
+ final HttpContext context) throws ResourceIOException {
final SimpleHttpResponse cachedResponse;
if (request.containsHeader(HttpHeaders.IF_NONE_MATCH)
|| request.containsHeader(HttpHeaders.IF_MODIFIED_SINCE)) {
@@ -197,26 +195,6 @@ public class CachingExecBase {
cachedResponse = responseGenerator.generateResponse(request, entry);
}
setResponseStatus(context, CacheResponseStatus.CACHE_HIT);
- if (TimeValue.isPositive(validityPolicy.getStaleness(responseCacheControl, entry, now))) {
- cachedResponse.addHeader(HttpHeaders.WARNING,"110 localhost \"Response is stale\"");
- }
-
- // Adding Warning: 113 - "Heuristic Expiration"
- if (!entry.containsHeader(HttpHeaders.WARNING)) {
- final Header header = entry.getFirstHeader(HttpHeaders.DATE);
- if (header != null) {
- final Instant responseDate = DateUtils.parseStandardDate(header.getValue());
- final TimeValue freshnessLifetime = validityPolicy.getFreshnessLifetime(responseCacheControl, entry);
- final TimeValue currentAge = validityPolicy.getCurrentAge(entry, responseDate);
- if (freshnessLifetime.compareTo(ONE_DAY) > 0 && currentAge.compareTo(ONE_DAY) > 0) {
- cachedResponse.addHeader(HttpHeaders.WARNING,"113 localhost \"Heuristic expiration\"");
- if (LOG.isDebugEnabled()) {
- LOG.debug("Added Warning 113 - Heuristic expiration to the response header.");
- }
- }
- }
- }
-
return cachedResponse;
}
@@ -246,7 +224,6 @@ public class CachingExecBase {
final HttpCacheEntry entry) throws IOException {
final SimpleHttpResponse cachedResponse = responseGenerator.generateResponse(request, entry);
setResponseStatus(context, CacheResponseStatus.CACHE_HIT);
- cachedResponse.addHeader(HttpHeaders.WARNING, "111 localhost \"Revalidation failed\"");
return cachedResponse;
}
diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/DefaultAsyncCacheRevalidator.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/DefaultAsyncCacheRevalidator.java
index 52c20a490..50c89a825 100644
--- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/DefaultAsyncCacheRevalidator.java
+++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/DefaultAsyncCacheRevalidator.java
@@ -135,7 +135,7 @@ class DefaultAsyncCacheRevalidator extends CacheRevalidatorBase {
@Override
public void completed() {
final HttpResponse httpResponse = responseRef.getAndSet(null);
- if (httpResponse != null && httpResponse.getCode() < HttpStatus.SC_SERVER_ERROR && !isStale(httpResponse)) {
+ if (httpResponse != null && httpResponse.getCode() < HttpStatus.SC_SERVER_ERROR) {
jobSuccessful(cacheKey);
} else {
jobFailed(cacheKey);
diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/DefaultCacheRevalidator.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/DefaultCacheRevalidator.java
index b4846aa50..e52ed096a 100644
--- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/DefaultCacheRevalidator.java
+++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/DefaultCacheRevalidator.java
@@ -77,7 +77,7 @@ class DefaultCacheRevalidator extends CacheRevalidatorBase {
final RevalidationCall call) {
scheduleRevalidation(cacheKey, () -> {
try (ClassicHttpResponse httpResponse = call.execute()) {
- if (httpResponse.getCode() < HttpStatus.SC_SERVER_ERROR && !isStale(httpResponse)) {
+ if (httpResponse.getCode() < HttpStatus.SC_SERVER_ERROR) {
jobSuccessful(cacheKey);
} else {
jobFailed(cacheKey);
diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ResponseProtocolCompliance.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ResponseProtocolCompliance.java
index 9454b3a7a..e9c0e229c 100644
--- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ResponseProtocolCompliance.java
+++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ResponseProtocolCompliance.java
@@ -79,41 +79,6 @@ class ResponseProtocolCompliance {
ensure304DoesNotContainExtraEntityHeaders(response);
identityIsNotUsedInContentEncoding(response);
-
- warningsWithNonMatchingWarnDatesAreRemoved(response);
- }
-
- private void warningsWithNonMatchingWarnDatesAreRemoved(
- final HttpResponse response) {
- final Instant responseDate = DateUtils.parseStandardDate(response, HttpHeaders.DATE);
- if (responseDate == null) {
- return;
- }
-
- final Header[] warningHeaders = response.getHeaders(HttpHeaders.WARNING);
-
- if (warningHeaders == null || warningHeaders.length == 0) {
- return;
- }
-
- final List<Header> newWarningHeaders = new ArrayList<>();
- boolean modified = false;
- for(final Header h : warningHeaders) {
- for(final WarningValue wv : WarningValue.getWarningValues(h)) {
- final Instant warnInstant = wv.getWarnDate();
- if (warnInstant == null || warnInstant.equals(responseDate)) {
- newWarningHeaders.add(new BasicHeader(HttpHeaders.WARNING,wv.toString()));
- } else {
- modified = true;
- }
- }
- }
- if (modified) {
- response.removeHeaders(HttpHeaders.WARNING);
- for(final Header h : newWarningHeaders) {
- response.addHeader(h);
- }
- }
}
private void identityIsNotUsedInContentEncoding(final HttpResponse response) {
diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/WarningValue.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/WarningValue.java
deleted file mode 100644
index c8efd7745..000000000
--- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/WarningValue.java
+++ /dev/null
@@ -1,368 +0,0 @@
-/*
- * ====================================================================
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
- *
- */
-package org.apache.hc.client5.http.impl.cache;
-
-import java.time.Instant;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.apache.hc.client5.http.utils.DateUtils;
-import org.apache.hc.core5.http.Header;
-
-/** This class provides for parsing and understanding Warning headers. As
- * the Warning header can be multi-valued, but the values can contain
- * separators like commas inside quoted strings, we cannot use the regular
- * {@link Header#getValue()} } call to access the values.
- */
-class WarningValue {
-
- private int offs;
- private final int init_offs;
- private final String src;
- private int warnCode;
- private String warnAgent;
- private String warnText;
- private Instant warnDate;
-
- WarningValue(final String s) {
- this(s, 0);
- }
-
- WarningValue(final String s, final int offs) {
- this.offs = this.init_offs = offs;
- this.src = s;
- consumeWarnValue();
- }
-
- /** Returns an array of the parsable warning values contained
- * in the given header value, which is assumed to be a
- * Warning header. Improperly formatted warning values will be
- * skipped, in keeping with the philosophy of "ignore what you
- * cannot understand."
- * @param h Warning {@link Header} to parse
- * @return array of {@code WarnValue} objects
- */
- public static WarningValue[] getWarningValues(final Header h) {
- final List<WarningValue> out = new ArrayList<>();
- final String src = h.getValue();
- int offs = 0;
- while(offs < src.length()) {
- try {
- final WarningValue wv = new WarningValue(src, offs);
- out.add(wv);
- offs = wv.offs;
- } catch (final IllegalArgumentException e) {
- final int nextComma = src.indexOf(',', offs);
- if (nextComma == -1) {
- break;
- }
- offs = nextComma + 1;
- }
- }
- final WarningValue[] wvs = {};
- return out.toArray(wvs);
- }
-
- /*
- * LWS = [CRLF] 1*( SP | HT )
- * CRLF = CR LF
- */
- protected void consumeLinearWhitespace() {
- while(offs < src.length()) {
- switch(src.charAt(offs)) {
- case '\r':
- if (offs+2 >= src.length()
- || src.charAt(offs+1) != '\n'
- || (src.charAt(offs+2) != ' '
- && src.charAt(offs+2) != '\t')) {
- return;
- }
- offs += 2;
- break;
- case ' ':
- case '\t':
- break;
- default:
- return;
- }
- offs++;
- }
- }
-
- /*
- * CHAR = <any US-ASCII character (octets 0 - 127)>
- */
- private boolean isChar(final char c) {
- return ((int) c >= 0 && (int) c <= 127);
- }
-
- /*
- * CTL = <any US-ASCII control character
- (octets 0 - 31) and DEL (127)>
- */
- private boolean isControl(final char c) {
- return ((int) c == 127 || ((int) c >=0 && (int) c <= 31));
- }
-
- /*
- * separators = "(" | ")" | "<" | ">" | "@"
- * | "," | ";" | ":" | "\" | <">
- * | "/" | "[" | "]" | "?" | "="
- * | "{" | "}" | SP | HT
- */
- private boolean isSeparator(final char c) {
- return (c == '(' || c == ')' || c == '<' || c == '>'
- || c == '@' || c == ',' || c == ';' || c == ':'
- || c == '\\' || c == '\"' || c == '/'
- || c == '[' || c == ']' || c == '?' || c == '='
- || c == '{' || c == '}' || c == ' ' || c == '\t');
- }
-
- /*
- * token = 1*<any CHAR except CTLs or separators>
- */
- protected void consumeToken() {
- if (!isTokenChar(src.charAt(offs))) {
- parseError();
- }
- while(offs < src.length()) {
- if (!isTokenChar(src.charAt(offs))) {
- break;
- }
- offs++;
- }
- }
-
- private boolean isTokenChar(final char c) {
- return (isChar(c) && !isControl(c) && !isSeparator(c));
- }
-
- private static final String TOPLABEL = "\\p{Alpha}([\\p{Alnum}-]*\\p{Alnum})?";
- private static final String DOMAINLABEL = "\\p{Alnum}([\\p{Alnum}-]*\\p{Alnum})?";
- private static final String HOSTNAME = "(" + DOMAINLABEL + "\\.)*" + TOPLABEL + "\\.?";
- private static final String IPV4ADDRESS = "\\d+\\.\\d+\\.\\d+\\.\\d+";
- private static final String HOST = "(" + HOSTNAME + ")|(" + IPV4ADDRESS + ")";
- private static final String PORT = "\\d*";
- private static final String HOSTPORT = "(" + HOST + ")(\\:" + PORT + ")?";
- private static final Pattern HOSTPORT_PATTERN = Pattern.compile(HOSTPORT);
-
- protected void consumeHostPort() {
- final Matcher m = HOSTPORT_PATTERN.matcher(src.substring(offs));
- if (!m.find()) {
- parseError();
- }
- if (m.start() != 0) {
- parseError();
- }
- offs += m.end();
- }
-
-
- /*
- * warn-agent = ( host [ ":" port ] ) | pseudonym
- * pseudonym = token
- */
- protected void consumeWarnAgent() {
- final int curr_offs = offs;
- try {
- consumeHostPort();
- warnAgent = src.substring(curr_offs, offs);
- consumeCharacter(' ');
- return;
- } catch (final IllegalArgumentException e) {
- offs = curr_offs;
- }
- consumeToken();
- warnAgent = src.substring(curr_offs, offs);
- consumeCharacter(' ');
- }
-
- /*
- * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
- * qdtext = <any TEXT except <">>
- */
- protected void consumeQuotedString() {
- if (src.charAt(offs) != '\"') {
- parseError();
- }
- offs++;
- boolean foundEnd = false;
- while(offs < src.length() && !foundEnd) {
- final char c = src.charAt(offs);
- if (offs + 1 < src.length() && c == '\\'
- && isChar(src.charAt(offs+1))) {
- offs += 2; // consume quoted-pair
- } else if (c == '\"') {
- foundEnd = true;
- offs++;
- } else if (!isControl(c)) {
- offs++;
- } else {
- parseError();
- }
- }
- if (!foundEnd) {
- parseError();
- }
- }
-
- /*
- * warn-text = quoted-string
- */
- protected void consumeWarnText() {
- final int curr = offs;
- consumeQuotedString();
- warnText = src.substring(curr, offs);
- }
-
- private static final String MONTH = "Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec";
- private static final String WEEKDAY = "Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday";
- private static final String WKDAY = "Mon|Tue|Wed|Thu|Fri|Sat|Sun";
- private static final String TIME = "\\d{2}:\\d{2}:\\d{2}";
- private static final String DATE3 = "(" + MONTH + ") ( |\\d)\\d";
- private static final String DATE2 = "\\d{2}-(" + MONTH + ")-\\d{2}";
- private static final String DATE1 = "\\d{2} (" + MONTH + ") \\d{4}";
- private static final String ASCTIME_DATE = "(" + WKDAY + ") (" + DATE3 + ") (" + TIME + ") \\d{4}";
- private static final String RFC850_DATE = "(" + WEEKDAY + "), (" + DATE2 + ") (" + TIME + ") GMT";
- private static final String RFC1123_DATE = "(" + WKDAY + "), (" + DATE1 + ") (" + TIME + ") GMT";
- private static final String HTTP_DATE = "(" + RFC1123_DATE + ")|(" + RFC850_DATE + ")|(" + ASCTIME_DATE + ")";
- private static final String WARN_DATE = "\"(" + HTTP_DATE + ")\"";
- private static final Pattern WARN_DATE_PATTERN = Pattern.compile(WARN_DATE);
-
- /*
- * warn-date = <"> HTTP-date <">
- */
- protected void consumeWarnDate() {
- final int curr = offs;
- final Matcher m = WARN_DATE_PATTERN.matcher(src.substring(offs));
- if (!m.lookingAt()) {
- parseError();
- }
- offs += m.end();
- warnDate = DateUtils.parseStandardDate(src.substring(curr+1,offs-1));
- }
-
- /*
- * warning-value = warn-code SP warn-agent SP warn-text [SP warn-date]
- */
- protected void consumeWarnValue() {
- consumeLinearWhitespace();
- consumeWarnCode();
- consumeWarnAgent();
- consumeWarnText();
- if (offs + 1 < src.length() && src.charAt(offs) == ' ' && src.charAt(offs+1) == '\"') {
- consumeCharacter(' ');
- consumeWarnDate();
- }
- consumeLinearWhitespace();
- if (offs != src.length()) {
- consumeCharacter(',');
- }
- }
-
- protected void consumeCharacter(final char c) {
- if (offs + 1 > src.length()
- || c != src.charAt(offs)) {
- parseError();
- }
- offs++;
- }
-
- /*
- * warn-code = 3DIGIT
- */
- protected void consumeWarnCode() {
- if (offs + 4 > src.length()
- || !Character.isDigit(src.charAt(offs))
- || !Character.isDigit(src.charAt(offs + 1))
- || !Character.isDigit(src.charAt(offs + 2))
- || src.charAt(offs + 3) != ' ') {
- parseError();
- }
- warnCode = Integer.parseInt(src.substring(offs,offs+3));
- offs += 4;
- }
-
- private void parseError() {
- final String s = src.substring(init_offs);
- throw new IllegalArgumentException("Bad warn code \"" + s + "\"");
- }
-
- /** Returns the 3-digit code associated with this warning.
- * @return {@code int}
- */
- public int getWarnCode() { return warnCode; }
-
- /** Returns the "warn-agent" string associated with this warning,
- * which is either the name or pseudonym of the server that added
- * this particular Warning header.
- * @return {@link String}
- */
- public String getWarnAgent() { return warnAgent; }
-
- /** Returns the human-readable warning text for this warning. Note
- * that the original quoted-string is returned here, including
- * escaping for any contained characters. In other words, if the
- * header was:
- * <pre>
- * Warning: 110 fred "Response is stale"
- * </pre>
- * then this method will return {@code "\"Response is stale\""}
- * (surrounding quotes included).
- * @return {@link String}
- */
- public String getWarnText() { return warnText; }
-
- /** Returns the date and time when this warning was added, or
- * {@code null} if a warning date was not supplied in the
- * header.
- * @return {@link Instant}
- */
- public Instant getWarnDate() { return warnDate; }
-
- /** Formats a {@code WarningValue} as a {@link String}
- * suitable for including in a header. For example, you can:
- * <pre>
- * WarningValue wv = ...;
- * HttpResponse resp = ...;
- * resp.addHeader("Warning", wv.toString());
- * </pre>
- * @return {@link String}
- */
- @Override
- public String toString() {
- if (warnDate != null) {
- return String.format("%d %s %s \"%s\"", warnCode,
- warnAgent, warnText, DateUtils.formatStandardDate(warnDate));
- } else {
- return String.format("%d %s %s", warnCode, warnAgent, warnText);
- }
- }
-
-}
diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/cache/TestHttpCacheEntryFactory.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/cache/TestHttpCacheEntryFactory.java
index c60ce45bd..0c35cd130 100644
--- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/cache/TestHttpCacheEntryFactory.java
+++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/cache/TestHttpCacheEntryFactory.java
@@ -181,20 +181,6 @@ public class TestHttpCacheEntryFactory {
MatcherAssert.assertThat(mergedHeaders, ContainsHeaderMatcher.contains("Cache-Control", "public"));
}
- @Test
- public void entry1xxWarningsAreRemovedOnMerge() {
- entry = HttpTestUtils.makeCacheEntry(tenSecondsAgo, eightSecondsAgo,
- new BasicHeader("Warning", "110 fred \"Response is stale\""),
- new BasicHeader("ETag", "\"old\""),
- new BasicHeader("Date", DateUtils.formatStandardDate(eightSecondsAgo)));
- response.setHeader("ETag", "\"new\"");
- response.setHeader("Date", DateUtils.formatStandardDate(twoSecondsAgo));
-
- final HeaderGroup mergedHeaders = impl.mergeHeaders(entry, response);
-
- Assertions.assertEquals(0, mergedHeaders.countHeaders("Warning"));
- }
-
@Test
public void entryWithMalformedDateIsStillUpdated() throws Exception {
entry = HttpTestUtils.makeCacheEntry(tenSecondsAgo, eightSecondsAgo,
diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/HttpTestUtils.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/HttpTestUtils.java
index 109a629d4..13cae4753 100644
--- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/HttpTestUtils.java
+++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/HttpTestUtils.java
@@ -29,7 +29,6 @@ package org.apache.hc.client5.http.impl.cache;
import java.io.InputStream;
import java.time.Duration;
import java.time.Instant;
-import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
@@ -43,9 +42,7 @@ import org.apache.hc.core5.concurrent.FutureCallback;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.Header;
-import org.apache.hc.core5.http.HeaderElement;
import org.apache.hc.core5.http.HttpEntity;
-import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.HttpMessage;
import org.apache.hc.core5.http.HttpRequest;
import org.apache.hc.core5.http.HttpResponse;
@@ -58,7 +55,6 @@ import org.apache.hc.core5.http.message.BasicClassicHttpRequest;
import org.apache.hc.core5.http.message.BasicClassicHttpResponse;
import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.http.message.HeaderGroup;
-import org.apache.hc.core5.http.message.MessageSupport;
import org.apache.hc.core5.util.ByteArrayBuffer;
import org.junit.jupiter.api.Assertions;
@@ -364,20 +360,6 @@ public class HttpTestUtils {
return new BasicClassicHttpResponse(HttpStatus.SC_NOT_MODIFIED, "Not modified");
}
- public static final void assert110WarningFound(final HttpResponse response) {
- boolean found110Warning = false;
- final Iterator<HeaderElement> it = MessageSupport.iterate(response, HttpHeaders.WARNING);
- while (it.hasNext()) {
- final HeaderElement elt = it.next();
- final String[] parts = elt.getName().split("\\s");
- if ("110".equals(parts[0])) {
- found110Warning = true;
- break;
- }
- }
- Assertions.assertTrue(found110Warning);
- }
-
public static ClassicHttpRequest makeDefaultRequest() {
return new BasicClassicHttpRequest(Method.GET.toString(), "/");
}
diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCacheRevalidatorBase.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCacheRevalidatorBase.java
index c5b43934a..9d6e974cb 100644
--- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCacheRevalidatorBase.java
+++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCacheRevalidatorBase.java
@@ -26,7 +26,6 @@
*/
package org.apache.hc.client5.http.impl.cache;
-import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -34,13 +33,8 @@ import static org.mockito.Mockito.when;
import java.util.concurrent.RejectedExecutionException;
import org.apache.hc.client5.http.schedule.SchedulingStrategy;
-import org.apache.hc.core5.http.HttpHeaders;
-import org.apache.hc.core5.http.HttpResponse;
-import org.apache.hc.core5.http.HttpStatus;
-import org.apache.hc.core5.http.message.BasicHttpResponse;
import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;
-import org.hamcrest.CoreMatchers;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -124,24 +118,6 @@ public class TestCacheRevalidatorBase {
Assertions.assertEquals(1, impl.getScheduledIdentifiers().size());
}
- @Test
- public void testStaleResponse() {
- final HttpResponse response1 = new BasicHttpResponse(HttpStatus.SC_OK);
- response1.addHeader(HttpHeaders.WARNING, "110 localhost \"Response is stale\"");
- assertThat(impl.isStale(response1), CoreMatchers.equalTo(true));
-
- final HttpResponse response2 = new BasicHttpResponse(HttpStatus.SC_OK);
- response2.addHeader(HttpHeaders.WARNING, "111 localhost \"Revalidation failed\"");
- assertThat(impl.isStale(response2), CoreMatchers.equalTo(true));
-
- final HttpResponse response3 = new BasicHttpResponse(HttpStatus.SC_OK);
- response3.addHeader(HttpHeaders.WARNING, "xxx localhost \"Huh?\"");
- assertThat(impl.isStale(response3), CoreMatchers.equalTo(false));
-
- final HttpResponse response4 = new BasicHttpResponse(HttpStatus.SC_OK);
- assertThat(impl.isStale(response4), CoreMatchers.equalTo(false));
- }
-
@Test
public void testShutdown() throws Exception {
impl.close();
diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCachingExecChain.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCachingExecChain.java
index ef39d990c..fb2b7abab 100644
--- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCachingExecChain.java
+++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCachingExecChain.java
@@ -38,11 +38,6 @@ import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Optional;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.stream.Collectors;
import org.apache.hc.client5.http.HttpRoute;
import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
@@ -52,7 +47,6 @@ import org.apache.hc.client5.http.cache.HttpCacheContext;
import org.apache.hc.client5.http.cache.HttpCacheEntry;
import org.apache.hc.client5.http.cache.HttpCacheEntryFactory;
import org.apache.hc.client5.http.cache.HttpCacheStorage;
-import org.apache.hc.client5.http.cache.ResourceIOException;
import org.apache.hc.client5.http.classic.ExecChain;
import org.apache.hc.client5.http.classic.ExecRuntime;
import org.apache.hc.client5.http.classic.methods.HttpDelete;
@@ -76,7 +70,6 @@ import org.apache.hc.core5.http.message.BasicClassicHttpRequest;
import org.apache.hc.core5.http.message.BasicClassicHttpResponse;
import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.net.URIAuthority;
-import org.apache.hc.core5.util.TimeValue;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -1472,74 +1465,6 @@ public class TestCachingExecChain {
Assertions.assertEquals(HttpStatus.SC_NOT_MODIFIED, cachedResponse.getCode());
}
- @Test
- public void testStaleIfErrorEnabledWithIOException() throws Exception {
-
- impl = new CachingExec(responseCache, validityPolicy, responseCachingPolicy,
- responseGenerator, cacheableRequestPolicy, suitabilityChecker,
- responseCompliance, requestCompliance, cacheRevalidator,
- conditionalRequestBuilder, customConfig);
- // Create the first request and response
- final BasicClassicHttpRequest req1 = new BasicClassicHttpRequest("GET", "http://foo.example.com/");
- final BasicClassicHttpRequest req2 = new BasicClassicHttpRequest("GET", "http://foo.example.com/");
- final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_GATEWAY_TIMEOUT, "OK");
- resp1.setEntity(HttpTestUtils.makeBody(128));
- resp1.setHeader("Content-Length", "128");
- resp1.setHeader("ETag", "\"etag\"");
- resp1.setHeader("Date", DateUtils.formatStandardDate(Instant.now().minus(Duration.ofHours(10))));
- resp1.setHeader("Cache-Control", "public, max-age=-1, stale-while-revalidate=1");
- final ClassicHttpResponse resp2 = HttpTestUtils.make200Response();
-
- // Set up the mock response chain
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp1);
- Mockito.when(responseCachingPolicy.isStaleIfErrorEnabled(Mockito.any(), Mockito.any())).thenReturn(true);
- Mockito.when(cacheableRequestPolicy.isServableFromCache(Mockito.any(), Mockito.any())).thenReturn(true);
- Mockito.when(validityPolicy.getStaleness(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(TimeValue.MAX_VALUE);
-
- // Assuming validityPolicy is a Mockito mock
- Mockito.when(validityPolicy.getCurrentAge(Mockito.any(), Mockito.any()))
- .thenReturn(TimeValue.ofMilliseconds(0));
-
- // Assuming validityPolicy is a Mockito mock
- Mockito.when(validityPolicy.getFreshnessLifetime(Mockito.any(), Mockito.any()))
- .thenReturn(TimeValue.ofMilliseconds(0));
-
- final SimpleHttpResponse response = SimpleHttpResponse.create(HttpStatus.SC_OK);
- final AtomicInteger callCount = new AtomicInteger(0);
-
- Mockito.doAnswer(invocation -> {
- if (callCount.getAndIncrement() == 0) {
- throw new ResourceIOException("ResourceIOException");
- } else {
- // Replace this with the actual return value for the second call
- return response;
- }
- }).when(responseGenerator).generateResponse(Mockito.any(), Mockito.any());
-
- // Execute the first request and assert the response
- final ClassicHttpResponse response1 = execute(req1);
- final HttpCacheEntry httpCacheEntry = HttpTestUtils.makeCacheEntry();
- Mockito.when(responseCache.match(Mockito.any(), Mockito.any())).thenReturn(
- new CacheMatch(new CacheHit("key", httpCacheEntry), null));
- Assertions.assertEquals(HttpStatus.SC_GATEWAY_TIMEOUT, response1.getCode());
-
- Mockito.when(mockExecRuntime.fork(Mockito.any())).thenReturn(mockExecRuntime);
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp2);
-
- final ClassicHttpResponse response2 = execute(req2);
- // Verify that the response has the expected status code (e.g., 200)
- Assertions.assertEquals(HttpStatus.SC_OK, response2.getCode());
-
- // Verify that the response has the expected headers or other properties
- // For example, you can check for the "Warning" header indicating a stale response:
- final Optional<Header> warningHeader = Arrays.stream(response.getHeaders())
- .filter(header -> header.getName().equalsIgnoreCase("Warning"))
- .findFirst();
-
- Assertions.assertTrue(warningHeader.isPresent());
- Assertions.assertTrue(warningHeader.get().getValue().contains("110"));
- }
-
@Test
public void testNoCacheFieldsRevalidation() throws Exception {
final Instant now = Instant.now();
@@ -1575,79 +1500,6 @@ public class TestCachingExecChain {
Mockito.verify(mockExecChain, Mockito.times(5)).proceed(Mockito.any(), Mockito.any());
}
- @Test
- public void testHeuristicExpirationWarning() throws Exception {
- impl = new CachingExec(responseCache, validityPolicy, responseCachingPolicy,
- responseGenerator, cacheableRequestPolicy, suitabilityChecker,
- responseCompliance, requestCompliance, cacheRevalidator,
- conditionalRequestBuilder, customConfig);
- // Create the first request and response
- final BasicClassicHttpRequest req1 = new BasicClassicHttpRequest("GET", "http://foo.example.com/");
- final BasicClassicHttpRequest req2 = new BasicClassicHttpRequest("GET", "http://foo.example.com/");
- final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_GATEWAY_TIMEOUT, "OK");
- resp1.setEntity(HttpTestUtils.makeBody(128));
- resp1.setHeader("Content-Length", "128");
- resp1.setHeader("ETag", "\"etag\"");
- resp1.setHeader("Date", DateUtils.formatStandardDate(Instant.now().minus(Duration.ofHours(10))));
- resp1.setHeader("Cache-Control", "public, max-age=-1, stale-while-revalidate=1");
- final ClassicHttpResponse resp2 = HttpTestUtils.make200Response();
-
- // Set up the mock response chain
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp1);
- Mockito.when(responseCachingPolicy.isStaleIfErrorEnabled(Mockito.any(), Mockito.any())).thenReturn(true);
- Mockito.when(cacheableRequestPolicy.isServableFromCache(Mockito.any(), Mockito.any())).thenReturn(true);
- Mockito.when(validityPolicy.getStaleness(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(TimeValue.MAX_VALUE);
-
- // Assuming validityPolicy is a Mockito mock
- Mockito.when(validityPolicy.getCurrentAge(Mockito.any(), Mockito.any()))
- .thenReturn(TimeValue.ofDays(2));
-
- // Assuming validityPolicy is a Mockito mock
- Mockito.when(validityPolicy.getFreshnessLifetime(Mockito.any(), Mockito.any()))
- .thenReturn(TimeValue.ofDays(2));
-
- final SimpleHttpResponse response = SimpleHttpResponse.create(HttpStatus.SC_OK);
- final AtomicInteger callCount = new AtomicInteger(0);
-
- Mockito.doAnswer(invocation -> {
- if (callCount.getAndIncrement() == 0) {
- throw new ResourceIOException("ResourceIOException");
- } else {
- // Replace this with the actual return value for the second call
- return response;
- }
- }).when(responseGenerator).generateResponse(Mockito.any(), Mockito.any());
-
- // Execute the first request and assert the response
- final ClassicHttpResponse response1 = execute(req1);
- final HttpCacheEntry httpCacheEntry = HttpTestUtils.makeCacheEntry();
- Mockito.when(responseCache.match(Mockito.any(), Mockito.any())).thenReturn(
- new CacheMatch(new CacheHit("key", httpCacheEntry), null));
- Assertions.assertEquals(HttpStatus.SC_GATEWAY_TIMEOUT, response1.getCode());
-
- Mockito.when(mockExecRuntime.fork(Mockito.any())).thenReturn(mockExecRuntime);
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp2);
-
- final ClassicHttpResponse response2 = execute(req2);
- // Verify that the response has the expected status code (e.g., 200)
- Assertions.assertEquals(HttpStatus.SC_OK, response2.getCode());
-
- // For example, you can check for the "Warning" header indicating a stale response:
- final List<Header> warningHeaders = Arrays.stream(response.getHeaders())
- .filter(header -> header.getName().equalsIgnoreCase("Warning"))
- .collect(Collectors.toList());
-
-
- Assertions.assertFalse(warningHeaders.isEmpty());
-
- final boolean found113 = warningHeaders.stream().anyMatch(header -> header.getValue().contains("113 localhost \"Heuristic expiration\""));
- Assertions.assertTrue(found113);
-
- final boolean found110 = warningHeaders.stream().anyMatch(header -> header.getValue().contains("110 localhost \"Response is stale\""));
- Assertions.assertTrue(found110);
- }
-
-
@Test
public void testRequestWithWeakETagAndRange() throws Exception {
final ClassicHttpRequest req1 = new HttpGet("http://foo1.example.com/");
diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolRecommendations.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolRecommendations.java
index c76258527..9e967bc6d 100644
--- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolRecommendations.java
+++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolRecommendations.java
@@ -502,118 +502,10 @@ public class TestProtocolRecommendations {
final ClassicHttpResponse result = execute(req2);
assertEquals(HttpStatus.SC_OK, result.getCode());
- assertTrue(result.containsHeader("Warning"));
Mockito.verify(mockExecChain, Mockito.atMost(1)).proceed(Mockito.any(), Mockito.any());
}
- /*
- * "A correct cache MUST respond to a request with the most up-to-date
- * response held by the cache that is appropriate to the request
- * (see sections 13.2.5, 13.2.6, and 13.12) which meets one of the
- * following conditions:
- *
- * 1. It has been checked for equivalence with what the origin server
- * would have returned by revalidating the response with the
- * origin server (section 13.3);
- *
- * 2. It is "fresh enough" (see section 13.2). In the default case,
- * this means it meets the least restrictive freshness requirement
- * of the client, origin server, and cache (see section 14.9); if
- * the origin server so specifies, it is the freshness requirement
- * of the origin server alone.
- *
- * If a stored response is not "fresh enough" by the most
- * restrictive freshness requirement of both the client and the
- * origin server, in carefully considered circumstances the cache
- * MAY still return the response with the appropriate Warning
- * header (see section 13.1.5 and 14.46), unless such a response
- * is prohibited (e.g., by a "no-store" cache-directive, or by a
- * "no-cache" cache-request-directive; see section 14.9).
- *
- * 3. It is an appropriate 304 (Not Modified), 305 (Proxy Redirect),
- * or error (4xx or 5xx) response message.
- *
- * If the cache can not communicate with the origin server, then a
- * correct cache SHOULD respond as above if the response can be
- * correctly served from the cache..."
- *
- * http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.1.1
- */
- @Test
- public void testReturnsCachedResponsesAppropriatelyWhenNoOriginCommunication() throws Exception {
- final ClassicHttpRequest req1 = new BasicClassicHttpRequest("GET", "/");
- final ClassicHttpResponse resp1 = HttpTestUtils.make200Response();
- resp1.setHeader("Cache-Control", "public, max-age=5");
- resp1.setHeader("ETag","\"etag\"");
- resp1.setHeader("Date", DateUtils.formatStandardDate(tenSecondsAgo));
-
- final ClassicHttpRequest req2 = new BasicClassicHttpRequest("GET", "/");
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp1);
-
- execute(req1);
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenThrow(new IOException());
-
- final ClassicHttpResponse result = execute(req2);
-
- Mockito.verify(mockExecChain, Mockito.times(2)).proceed(Mockito.any(), Mockito.any());
-
- assertEquals(HttpStatus.SC_OK, result.getCode());
- boolean warning111Found = false;
- for(final Header h : result.getHeaders("Warning")) {
- for(final WarningValue wv : WarningValue.getWarningValues(h)) {
- if (wv.getWarnCode() == 111) {
- warning111Found = true;
- break;
- }
- }
- }
- assertTrue(warning111Found);
- }
-
- /*
- * "If a cache receives a response (either an entire response, or a
- * 304 (Not Modified) response) that it would normally forward to the
- * requesting client, and the received response is no longer fresh,
- * the cache SHOULD forward it to the requesting client without adding
- * a new Warning (but without removing any existing Warning headers).
- * A cache SHOULD NOT attempt to revalidate a response simply because
- * that response became stale in transit; this might lead to an
- * infinite loop."
- *
- * http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.1.1
- */
- @Test
- public void testDoesNotAddNewWarningHeaderIfResponseArrivesStale() throws Exception {
- originResponse.setHeader("Date", DateUtils.formatStandardDate(tenSecondsAgo));
- originResponse.setHeader("Cache-Control","public, max-age=5");
- originResponse.setHeader("ETag","\"etag\"");
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(originResponse);
-
- final ClassicHttpResponse result = execute(request);
-
- assertFalse(result.containsHeader("Warning"));
- }
-
- @Test
- public void testForwardsExistingWarningHeadersOnResponseThatArrivesStale() throws Exception {
- originResponse.setHeader("Date", DateUtils.formatStandardDate(tenSecondsAgo));
- originResponse.setHeader("Cache-Control","public, max-age=5");
- originResponse.setHeader("ETag","\"etag\"");
- originResponse.addHeader("Age","10");
- final String warning = "110 fred \"Response is stale\"";
- originResponse.addHeader("Warning",warning);
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(originResponse);
-
- final ClassicHttpResponse result = execute(request);
-
- MatcherAssert.assertThat(result, ContainsHeaderMatcher.contains("Warning", warning));
- }
-
/*
* "A transparent proxy SHOULD NOT modify an end-to-end header unless
* the definition of that header requires or specifically allows that."
diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolRequirements.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolRequirements.java
index a727be2a9..9d5e3f9dc 100644
--- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolRequirements.java
+++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolRequirements.java
@@ -411,13 +411,6 @@ public class TestProtocolRequirements {
testOrderOfMultipleHeadersIsPreservedOnRequests(HttpHeaders.VIA, request);
}
- @Test
- public void testOrderOfMultipleWarningHeadersIsPreservedOnRequests() throws Exception {
- request.addHeader("Warning", "199 fred \"bargle\"");
- request.addHeader("Warning", "199 barney \"bungle\"");
- testOrderOfMultipleHeadersIsPreservedOnRequests("Warning", request);
- }
-
private void testOrderOfMultipleHeadersIsPreservedOnResponses(final String h) throws Exception {
Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(originResponse);
@@ -1899,199 +1892,6 @@ public class TestProtocolRequirements {
Assertions.assertEquals(200, result.getCode());
}
- /*
- * "If the cache can not communicate with the origin server, then a correct
- * cache SHOULD respond as above if the response can be correctly served
- * from the cache; if not it MUST return an error or warning indicating that
- * there was a communication failure."
- *
- * http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.1.1
- *
- * "111 Revalidation failed MUST be included if a cache returns a stale
- * response because an attempt to revalidate the response failed, due to an
- * inability to reach the server."
- *
- * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.46
- */
- @Test
- public void testMustServeAppropriateErrorOrWarningIfNoOriginCommunicationPossible() throws Exception {
-
- final Instant now = Instant.now();
- final Instant tenSecondsAgo = now.minusSeconds(10);
- final Instant nineSecondsAgo = now.plusSeconds(9);
- final Instant eightSecondsAgo = now.plusSeconds(8);
-
- final Header[] hdrs = new Header[] {
- new BasicHeader("Date", DateUtils.formatStandardDate(nineSecondsAgo)),
- new BasicHeader("Cache-Control", "max-age=0"),
- new BasicHeader("Content-Length", "128"),
- new BasicHeader("Last-Modified", DateUtils.formatStandardDate(tenSecondsAgo))
- };
-
- final byte[] bytes = new byte[128];
- new Random().nextBytes(bytes);
-
- final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(tenSecondsAgo, eightSecondsAgo, hdrs, bytes);
-
- impl = new CachingExec(mockCache, null, config);
- request = new BasicClassicHttpRequest("GET", "/thing");
-
- Mockito.when(mockCache.match(Mockito.eq(host), RequestEquivalent.eq(request))).thenReturn(
- new CacheMatch(new CacheHit("key", entry), null));
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenThrow(
- new IOException("can't talk to origin!"));
-
- final ClassicHttpResponse result = execute(request);
-
- final int status = result.getCode();
- Assertions.assertEquals(200, result.getCode());
- boolean foundWarning = false;
- for (final Header h : result.getHeaders("Warning")) {
- if (h.getValue().split(" ")[0].equals("111")) {
- foundWarning = true;
- }
- }
- Assertions.assertTrue(foundWarning);
- }
-
- /*
- * "Whenever a cache returns a response that is neither first-hand nor
- * "fresh enough" (in the sense of condition 2 in section 13.1.1), it MUST
- * attach a warning to that effect, using a Warning general-header."
- *
- * http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.1.2
- */
- @Test
- public void testAttachesWarningHeaderWhenGeneratingStaleResponse() throws Exception {
- // covered by previous test
- }
-
- /*
- * "1xx Warnings that describe the freshness or revalidation status of the
- * response, and so MUST be deleted after a successful revalidation."
- *
- * http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.1.2
- */
- @Test
- public void test1xxWarningsAreDeletedAfterSuccessfulRevalidation() throws Exception {
-
- final Instant now = Instant.now();
- final Instant twentyFiveSecondsAgo = now.minusSeconds(25);
- final ClassicHttpRequest req1 = new BasicClassicHttpRequest("GET", "/");
- final ClassicHttpResponse resp1 = HttpTestUtils.make200Response();
- resp1.setHeader("Date", DateUtils.formatStandardDate(twentyFiveSecondsAgo));
- resp1.setHeader("ETag", "\"etag\"");
- resp1.setHeader("Cache-Control", "max-age=5");
- resp1.setHeader("Warning", "110 squid \"stale stuff\"");
- resp1.setHeader(HttpHeaders.VIA, "1.1 fred");
-
- final ClassicHttpRequest req2 = new BasicClassicHttpRequest("GET", "/");
-
- final ClassicHttpRequest validate = new BasicClassicHttpRequest("GET", "/");
- validate.setHeader("If-None-Match", "\"etag\"");
-
- final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_NOT_MODIFIED,
- "Not Modified");
- resp2.setHeader("Date", DateUtils.formatStandardDate(now));
- resp2.setHeader("Server", "MockServer/1.0");
- resp2.setHeader("ETag", "\"etag\"");
- resp2.setHeader(HttpHeaders.VIA, "1.1 fred");
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp1);
- Mockito.when(mockExecChain.proceed(RequestEquivalent.eq(validate), Mockito.any())).thenReturn(resp2);
-
- final ClassicHttpRequest req3 = new BasicClassicHttpRequest("GET", "/");
-
-
- final ClassicHttpResponse stale = execute(req1);
- Assertions.assertNotNull(stale.getFirstHeader("Warning"));
-
- final ClassicHttpResponse result1 = execute(req2);
- final ClassicHttpResponse result2 = execute(req3);
-
- boolean found1xxWarning = false;
- final Iterator<HeaderElement> it = MessageSupport.iterate(result1, HttpHeaders.WARNING);
- while (it.hasNext()) {
- final HeaderElement elt = it.next();
- if (elt.getName().startsWith("1")) {
- found1xxWarning = true;
- }
- }
- final Iterator<HeaderElement> it2 = MessageSupport.iterate(result2, HttpHeaders.WARNING);
- while (it2.hasNext()) {
- final HeaderElement elt = it2.next();
- if (elt.getName().startsWith("1")) {
- found1xxWarning = true;
- }
- }
- Assertions.assertFalse(found1xxWarning);
- }
-
- /*
- * "2xx Warnings that describe some aspect of the entity body or entity
- * headers that is not rectified by a revalidation (for example, a lossy
- * compression of the entity bodies) and which MUST NOT be deleted after a
- * successful revalidation."
- * http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.1.2
- */
- @Test
- public void test2xxWarningsAreNotDeletedAfterSuccessfulRevalidation() throws Exception {
- final Instant now = Instant.now();
- final Instant tenSecondsAgo = now.minusSeconds(10);
- final ClassicHttpRequest req1 = new BasicClassicHttpRequest("GET", "/");
- final ClassicHttpResponse resp1 = HttpTestUtils.make200Response();
- resp1.setHeader("Date", DateUtils.formatStandardDate(tenSecondsAgo));
- resp1.setHeader("ETag", "\"etag\"");
- resp1.setHeader("Cache-Control", "max-age=5");
- resp1.setHeader(HttpHeaders.VIA, "1.1 xproxy");
- resp1.setHeader("Warning", "214 xproxy \"transformed stuff\"");
-
- final ClassicHttpRequest req2 = new BasicClassicHttpRequest("GET", "/");
-
- final ClassicHttpRequest validate = new BasicClassicHttpRequest("GET", "/");
- validate.setHeader("If-None-Match", "\"etag\"");
-
- final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_NOT_MODIFIED,
- "Not Modified");
- resp2.setHeader("Date", DateUtils.formatStandardDate(now));
- resp2.setHeader("Server", "MockServer/1.0");
- resp2.setHeader("ETag", "\"etag\"");
- resp1.setHeader(HttpHeaders.VIA, "1.1 xproxy");
-
- final ClassicHttpRequest req3 = new BasicClassicHttpRequest("GET", "/");
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp1);
- Mockito.when(mockExecChain.proceed(RequestEquivalent.eq(validate), Mockito.any())).thenReturn(resp2);
-
- final ClassicHttpResponse stale = execute(req1);
- Assertions.assertNotNull(stale.getFirstHeader("Warning"));
-
- final ClassicHttpResponse result1 = execute(req2);
- final ClassicHttpResponse result2 = execute(req3);
-
- boolean found214Warning = false;
- final Iterator<HeaderElement> it = MessageSupport.iterate(result1, HttpHeaders.WARNING);
- while (it.hasNext()) {
- final HeaderElement elt = it.next();
- final String[] parts = elt.getName().split(" ");
- if ("214".equals(parts[0])) {
- found214Warning = true;
- }
- }
- Assertions.assertTrue(found214Warning);
-
- found214Warning = false;
- final Iterator<HeaderElement> it2 = MessageSupport.iterate(result2, HttpHeaders.WARNING);
- while (it2.hasNext()) {
- final HeaderElement elt = it2.next();
- final String[] parts = elt.getName().split(" ");
- if ("214".equals(parts[0])) {
- found214Warning = true;
- }
- }
- Assertions.assertTrue(found214Warning);
- }
-
/*
* "When a response is generated from a cache entry, the cache MUST include
* a single Age header field in the response with a value equal to the cache
@@ -2136,96 +1936,6 @@ public class TestProtocolRequirements {
assertThat(result, ContainsHeaderMatcher.contains("Age", "10"));
}
- /*
- * "If none of Expires, Cache-Control: max-age, or Cache-Control: s-maxage
- * (see section 14.9.3) appears in the response, and the response does not
- * include other restrictions on caching, the cache MAY compute a freshness
- * lifetime using a heuristic. The cache MUST attach Warning 113 to any
- * response whose age is more than 24 hours if such warning has not already
- * been added."
- *
- * http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.2.4
- *
- * "113 Heuristic expiration MUST be included if the cache heuristically
- * chose a freshness lifetime greater than 24 hours and the response's age
- * is greater than 24 hours."
- *
- * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.46
- */
- @Test
- public void testHeuristicCacheOlderThan24HoursHasWarningAttached() throws Exception {
-
- final Instant now = Instant.now();
- final Instant thirtySixHoursAgo = now.minus(26, ChronoUnit.HOURS);
- final Instant oneYearAgo = now.minus(1, ChronoUnit.HOURS);
- final Instant requestTime = thirtySixHoursAgo.minusSeconds(1);
- final Instant responseTime = thirtySixHoursAgo.plusSeconds(1);
-
- final Header[] hdrs = new Header[] {
- new BasicHeader("Date", DateUtils.formatStandardDate(thirtySixHoursAgo)),
- new BasicHeader("Cache-Control", "public"),
- new BasicHeader("Last-Modified", DateUtils.formatStandardDate(oneYearAgo)),
- new BasicHeader("Content-Length", "128")
- };
-
- final byte[] bytes = new byte[128];
- new Random().nextBytes(bytes);
-
- final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(requestTime, responseTime, hdrs, bytes);
-
- impl = new CachingExec(mockCache, null, config);
-
- request = new BasicClassicHttpRequest("GET", "/thing");
-
- final ClassicHttpResponse validated = HttpTestUtils.make200Response();
- validated.setHeader("Cache-Control", "public");
- validated.setHeader("Last-Modified", DateUtils.formatStandardDate(oneYearAgo));
- validated.setHeader("Content-Length", "128");
- validated.setEntity(new ByteArrayEntity(bytes, null));
-
- final HttpCacheEntry cacheEntry = HttpTestUtils.makeCacheEntry();
-
- Mockito.when(mockCache.match(Mockito.eq(host), RequestEquivalent.eq(request))).thenReturn(
- new CacheMatch(new CacheHit("key", entry), null));
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(validated);
- Mockito.when(mockCache.store(
- Mockito.any(),
- Mockito.any(),
- ResponseEquivalent.eq(validated),
- Mockito.any(),
- Mockito.any(),
- Mockito.any())).thenReturn(new CacheHit("key", cacheEntry));
-
- final ClassicHttpResponse result = execute(request);
-
- Assertions.assertEquals(200, result.getCode());
-
- final ArgumentCaptor<ClassicHttpRequest> reqCapture = ArgumentCaptor.forClass(ClassicHttpRequest.class);
- Mockito.verify(mockExecChain, Mockito.atMostOnce()).proceed(reqCapture.capture(), Mockito.any());
- final List<ClassicHttpRequest> allRequests = reqCapture.getAllValues();
- if (allRequests.isEmpty()) {
- // heuristic cache hit
- boolean found113Warning = false;
- final Iterator<HeaderElement> it = MessageSupport.iterate(result, HttpHeaders.WARNING);
- while (it.hasNext()) {
- final HeaderElement elt = it.next();
- final String[] parts = elt.getName().split(" ");
- if ("113".equals(parts[0])) {
- found113Warning = true;
- break;
- }
- }
- Assertions.assertTrue(found113Warning);
- }
- Mockito.verify(mockCache).store(
- Mockito.any(),
- Mockito.any(),
- Mockito.any(),
- Mockito.any(),
- Mockito.any(),
- Mockito.any());
- }
-
/*
* "If a cache has two fresh responses for the same representation with
* different validators, it MUST use the one with the more recent Date
@@ -4183,57 +3893,6 @@ public class TestProtocolRequirements {
testSharedCacheMustUseNewRequestHeadersWhenRevalidatingAuthorizedResponse(resp1);
}
- /* "If a cache returns a stale response, either because of a max-stale
- * directive on a request, or because the cache is configured to
- * override the expiration time of a response, the cache MUST attach a
- * Warning header to the stale response, using Warning 110 (Response
- * is stale).
- *
- * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.3
- *
- * "110 Response is stale MUST be included whenever the returned
- * response is stale."
- *
- * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.46
- */
- @Test
- public void testWarning110IsAddedToStaleResponses() throws Exception {
- final Instant now = Instant.now();
- final Instant tenSecondsAgo = now.minusSeconds(10);
- final ClassicHttpRequest req1 = new BasicClassicHttpRequest("GET", "/");
- final ClassicHttpResponse resp1 = HttpTestUtils.make200Response();
- resp1.setHeader("Date", DateUtils.formatStandardDate(tenSecondsAgo));
- resp1.setHeader("Cache-Control","max-age=5");
- resp1.setHeader("Etag","\"etag\"");
-
- final ClassicHttpRequest req2 = new BasicClassicHttpRequest("GET", "/");
- req2.setHeader("Cache-Control","max-stale=60");
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp1);
-
- execute(req1);
-
- final ClassicHttpResponse result = execute(req2);
-
- final ArgumentCaptor<ClassicHttpRequest> reqCapture = ArgumentCaptor.forClass(ClassicHttpRequest.class);
- Mockito.verify(mockExecChain, Mockito.atMostOnce()).proceed(reqCapture.capture(), Mockito.any());
-
- final List<ClassicHttpRequest> allRequests = reqCapture.getAllValues();
- if (allRequests.isEmpty()) {
- boolean found110Warning = false;
- final Iterator<HeaderElement> it = MessageSupport.iterate(result, HttpHeaders.WARNING);
- while (it.hasNext()) {
- final HeaderElement elt = it.next();
- final String[] parts = elt.getName().split("\\s");
- if ("110".equals(parts[0])) {
- found110Warning = true;
- break;
- }
- }
- Assertions.assertTrue(found110Warning);
- }
- }
-
/* "The request includes a "no-cache" cache-control directive or, for
* compatibility with HTTP/1.0 clients, "Pragma: no-cache".... The
* server MUST NOT use a cached copy when responding to such a request."
@@ -4940,166 +4599,4 @@ public class TestProtocolRequirements {
Assertions.assertEquals("1.0", protoParts[protoParts.length - 1]);
}
- /* "A cache MUST NOT delete any Warning header that it received with
- * a message."
- *
- * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.46
- */
- @Test
- public void testRetainsWarningHeadersReceivedFromUpstream() throws Exception {
- originResponse.removeHeaders("Warning");
- final String warning = "199 fred \"misc\"";
- originResponse.addHeader("Warning", warning);
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(originResponse);
-
- final ClassicHttpResponse result = execute(request);
- Assertions.assertEquals(warning,
- result.getFirstHeader("Warning").getValue());
- }
-
- /* "However, if a cache successfully validates a cache entry, it
- * SHOULD remove any Warning headers previously attached to that
- * entry except as specified for specific Warning codes. It MUST
- * then add any Warning headers received in the validating response."
- *
- * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.46
- */
- @Test
- public void testUpdatesWarningHeadersOnValidation() throws Exception {
- final ClassicHttpRequest req1 = new BasicClassicHttpRequest("GET", "/");
- final ClassicHttpRequest req2 = new BasicClassicHttpRequest("GET", "/");
-
- final Instant now = Instant.now();
- final Instant twentySecondsAgo = now.plusSeconds(20);
- final ClassicHttpResponse resp1 = HttpTestUtils.make200Response();
- resp1.setHeader("Date", DateUtils.formatStandardDate(twentySecondsAgo));
- resp1.setHeader("Cache-Control","public,max-age=5");
- resp1.setHeader("ETag", "\"etag1\"");
- final String oldWarning = "113 wilma \"stale\"";
- resp1.setHeader("Warning", oldWarning);
-
- final Instant tenSecondsAgo = now.minusSeconds(10);
- final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_NOT_MODIFIED, "Not Modified");
- resp2.setHeader("Date", DateUtils.formatStandardDate(tenSecondsAgo));
- resp2.setHeader("ETag", "\"etag1\"");
- final String newWarning = "113 betty \"stale too\"";
- resp2.setHeader("Warning", newWarning);
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp1);
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp2);
-
- execute(req1);
- final ClassicHttpResponse result = execute(req2);
-
- boolean oldWarningFound = false;
- boolean newWarningFound = false;
- for(final Header h : result.getHeaders("Warning")) {
- for(final String warnValue : h.getValue().split("\\s*,\\s*")) {
- if (oldWarning.equals(warnValue)) {
- oldWarningFound = true;
- } else if (newWarning.equals(warnValue)) {
- newWarningFound = true;
- }
- }
- }
- Assertions.assertFalse(oldWarningFound);
- Assertions.assertTrue(newWarningFound);
- }
-
- /* "If an implementation sends a message with one or more Warning
- * headers whose version is HTTP/1.0 or lower, then the sender MUST
- * include in each warning-value a warn-date that matches the date
- * in the response."
- *
- * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.46
- */
- @Test
- public void testWarnDatesAreAddedToWarningsOnLowerProtocolVersions() throws Exception {
- final String dateHdr = DateUtils.formatStandardDate(Instant.now());
- final String origWarning = "110 fred \"stale\"";
- originResponse.setCode(HttpStatus.SC_OK);
- originResponse.setVersion(HttpVersion.HTTP_1_0);
- originResponse.addHeader("Warning", origWarning);
- originResponse.setHeader("Date", dateHdr);
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(originResponse);
- final ClassicHttpResponse result = execute(request);
- // note that currently the implementation acts as an HTTP/1.1 proxy,
- // which means that all the responses from the caching module should
- // be HTTP/1.1, so we won't actually be testing anything here until
- // that changes.
- if (HttpVersion.HTTP_1_0.greaterEquals(result.getVersion())) {
- Assertions.assertEquals(dateHdr, result.getFirstHeader("Date").getValue());
- boolean warningFound = false;
- final String targetWarning = origWarning + " \"" + dateHdr + "\"";
- for(final Header h : result.getHeaders("Warning")) {
- for(final String warning : h.getValue().split("\\s*,\\s*")) {
- if (targetWarning.equals(warning)) {
- warningFound = true;
- break;
- }
- }
- }
- Assertions.assertTrue(warningFound);
- }
- }
-
- /* "If an implementation receives a message with a warning-value that
- * includes a warn-date, and that warn-date is different from the Date
- * value in the response, then that warning-value MUST be deleted from
- * the message before storing, forwarding, or using it. (This prevents
- * bad consequences of naive caching of Warning header fields.) If all
- * of the warning-values are deleted for this reason, the Warning
- * header MUST be deleted as well."
- *
- * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.46
- */
- @Test
- public void testStripsBadlyDatedWarningsFromForwardedResponses() throws Exception {
- final Instant now = Instant.now();
- final Instant tenSecondsAgo = now.minusSeconds(10);
- originResponse.setHeader("Date", DateUtils.formatStandardDate(now));
- originResponse.addHeader("Warning", "110 fred \"stale\", 110 wilma \"stale\" \""
- + DateUtils.formatStandardDate(tenSecondsAgo) + "\"");
- originResponse.setHeader("Cache-Control","no-cache,no-store");
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(originResponse);
-
- final ClassicHttpResponse result = execute(request);
-
- for(final Header h : result.getHeaders("Warning")) {
- Assertions.assertFalse(h.getValue().contains("wilma"));
- }
- }
-
- @Test
- public void testStripsBadlyDatedWarningsFromStoredResponses() throws Exception {
- final Instant now = Instant.now();
- final Instant tenSecondsAgo = now.minusSeconds(10);
- originResponse.setHeader("Date", DateUtils.formatStandardDate(now));
- originResponse.addHeader("Warning", "110 fred \"stale\", 110 wilma \"stale\" \""
- + DateUtils.formatStandardDate(tenSecondsAgo) + "\"");
- originResponse.setHeader("Cache-Control","public,max-age=3600");
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(originResponse);
-
- final ClassicHttpResponse result = execute(request);
-
- for(final Header h : result.getHeaders("Warning")) {
- Assertions.assertFalse(h.getValue().contains("wilma"));
- }
- }
-
- @Test
- public void testRemovesWarningHeaderIfAllWarnValuesAreBadlyDated() throws Exception {
- final Instant now = Instant.now();
- final Instant tenSecondsAgo = now.minusSeconds(10);
- originResponse.setHeader("Date", DateUtils.formatStandardDate(now));
- originResponse.addHeader("Warning", "110 wilma \"stale\" \""
- + DateUtils.formatStandardDate(tenSecondsAgo) + "\"");
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(originResponse);
-
- final ClassicHttpResponse result = execute(request);
-
- final Header[] warningHeaders = result.getHeaders("Warning");
- Assertions.assertTrue(warningHeaders == null || warningHeaders.length == 0);
- }
-
}
diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestRFC5861Compliance.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestRFC5861Compliance.java
index 3c5934ea6..85a4f7acd 100644
--- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestRFC5861Compliance.java
+++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestRFC5861Compliance.java
@@ -28,7 +28,6 @@ package org.apache.hc.client5.http.impl.cache;
import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
@@ -40,12 +39,9 @@ import java.util.concurrent.ScheduledThreadPoolExecutor;
import org.apache.hc.client5.http.HttpRoute;
import org.apache.hc.client5.http.classic.ExecChain;
import org.apache.hc.client5.http.classic.ExecRuntime;
-import org.apache.hc.client5.http.impl.schedule.ImmediateSchedulingStrategy;
import org.apache.hc.client5.http.protocol.HttpClientContext;
-import org.apache.hc.client5.http.utils.DateUtils;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ClassicHttpResponse;
-import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpException;
import org.apache.hc.core5.http.HttpHost;
@@ -128,43 +124,6 @@ public class TestRFC5861Compliance {
mockExecChain);
}
- /*
- * "The stale-if-error Cache-Control extension indicates that when an
- * error is encountered, a cached stale response MAY be used to satisfy
- * the request, regardless of other freshness information.When used as a
- * request Cache-Control extension, its scope of application is the request
- * it appears in; when used as a response Cache-Control extension, its
- * scope is any request applicable to the cached response in which it
- * occurs.Its value indicates the upper limit to staleness; when the cached
- * response is more stale than the indicated amount, the cached response
- * SHOULD NOT be used to satisfy the request, absent other information.
- * In this context, an error is any situation that would result in a
- * 500, 502, 503, or 504 HTTP response status code being returned."
- *
- * http://tools.ietf.org/html/rfc5861
- */
- @Test
- public void testStaleIfErrorInResponseIsTrueReturnsStaleEntryWithWarning()
- throws Exception{
- final Instant tenSecondsAgo = Instant.now().minusSeconds(10);
- final ClassicHttpRequest req1 = HttpTestUtils.makeDefaultRequest();
- final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(tenSecondsAgo,
- "public, max-age=5, stale-if-error=60");
-
- final ClassicHttpRequest req2 = HttpTestUtils.makeDefaultRequest();
- final ClassicHttpResponse resp2 = HttpTestUtils.make500Response();
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp1);
-
- execute(req1);
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp2);
-
- final ClassicHttpResponse result = execute(req2);
-
- HttpTestUtils.assert110WarningFound(result);
- }
-
@Test
public void testConsumesErrorResponseWhenServingStale()
throws Exception{
@@ -237,32 +196,6 @@ public class TestRFC5861Compliance {
assertTrue(HttpStatus.SC_OK != result.getCode());
}
- @Test
- public void testStaleIfErrorInResponseNeedNotYieldToProxyRevalidateForPrivateCache()
- throws Exception{
- final CacheConfig configUnshared = CacheConfig.custom()
- .setSharedCache(false).build();
- impl = new CachingExec(new BasicHttpCache(configUnshared), null, configUnshared);
-
- final Instant tenSecondsAgo = Instant.now().minusSeconds(10);
- final ClassicHttpRequest req1 = HttpTestUtils.makeDefaultRequest();
- final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(tenSecondsAgo,
- "public, max-age=5, stale-if-error=60, proxy-revalidate");
-
- final ClassicHttpRequest req2 = HttpTestUtils.makeDefaultRequest();
- final ClassicHttpResponse resp2 = HttpTestUtils.make500Response();
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp1);
-
- execute(req1);
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp2);
-
- final ClassicHttpResponse result = execute(req2);
-
- HttpTestUtils.assert110WarningFound(result);
- }
-
@Test
public void testStaleIfErrorInResponseYieldsToExplicitFreshnessRequest()
throws Exception{
@@ -286,53 +219,6 @@ public class TestRFC5861Compliance {
assertTrue(HttpStatus.SC_OK != result.getCode());
}
- @Test
- public void testStaleIfErrorInRequestIsTrueReturnsStaleEntryWithWarning()
- throws Exception{
- final Instant tenSecondsAgo = Instant.now().minusSeconds(10);
- final ClassicHttpRequest req1 = HttpTestUtils.makeDefaultRequest();
- final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(tenSecondsAgo,
- "public, max-age=5");
-
- final ClassicHttpRequest req2 = HttpTestUtils.makeDefaultRequest();
- req2.setHeader("Cache-Control","public, stale-if-error=60");
- final ClassicHttpResponse resp2 = HttpTestUtils.make500Response();
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp1);
-
- execute(req1);
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp2);
-
- final ClassicHttpResponse result = execute(req2);
-
- HttpTestUtils.assert110WarningFound(result);
- }
-
- @Test
- public void testStaleIfErrorInRequestIsTrueReturnsStaleNonRevalidatableEntryWithWarning()
- throws Exception {
- final Instant tenSecondsAgo = Instant.now().minusSeconds(10);
- final ClassicHttpRequest req1 = HttpTestUtils.makeDefaultRequest();
- final ClassicHttpResponse resp1 = HttpTestUtils.make200Response();
- resp1.setHeader("Date", DateUtils.formatStandardDate(tenSecondsAgo));
- resp1.setHeader("Cache-Control", "public, max-age=5");
-
- final ClassicHttpRequest req2 = HttpTestUtils.makeDefaultRequest();
- req2.setHeader("Cache-Control", "public, stale-if-error=60");
- final ClassicHttpResponse resp2 = HttpTestUtils.make500Response();
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp1);
-
- execute(req1);
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp2);
-
- final ClassicHttpResponse result = execute(req2);
-
- HttpTestUtils.assert110WarningFound(result);
- }
-
@Test
public void testStaleIfErrorInResponseIsFalseReturnsError()
throws Exception{
@@ -381,280 +267,4 @@ public class TestRFC5861Compliance {
assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, result.getCode());
}
- /*
- * When present in an HTTP response, the stale-while-revalidate Cache-
- * Control extension indicates that caches MAY serve the response in
- * which it appears after it becomes stale, up to the indicated number
- * of seconds.
- *
- * http://tools.ietf.org/html/rfc5861
- */
- @Test
- public void testStaleWhileRevalidateReturnsStaleEntryWithWarning()
- throws Exception {
- config = CacheConfig.custom()
- .setMaxCacheEntries(MAX_ENTRIES)
- .setMaxObjectSize(MAX_BYTES)
- .setAsynchronousWorkers(1)
- .build();
-
- impl = new CachingExec(cache, executorService, ImmediateSchedulingStrategy.INSTANCE, config);
-
- final ClassicHttpRequest req1 = new BasicClassicHttpRequest("GET", "/");
- final ClassicHttpResponse resp1 = HttpTestUtils.make200Response();
- final Instant now = Instant.now();
- final Instant tenSecondsAgo = now.minusSeconds(10);
- resp1.setHeader("Cache-Control", "public, max-age=5, stale-while-revalidate=15");
- resp1.setHeader("ETag","\"etag\"");
- resp1.setHeader("Date", DateUtils.formatStandardDate(tenSecondsAgo));
-
- final ClassicHttpRequest req2 = new BasicClassicHttpRequest("GET", "/");
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp1);
-
- execute(req1);
- final ClassicHttpResponse result = execute(req2);
-
- assertEquals(HttpStatus.SC_OK, result.getCode());
- boolean warning110Found = false;
- for(final Header h : result.getHeaders("Warning")) {
- for(final WarningValue wv : WarningValue.getWarningValues(h)) {
- if (wv.getWarnCode() == 110) {
- warning110Found = true;
- break;
- }
- }
- }
- assertTrue(warning110Found);
-
- Mockito.verify(mockExecChain, Mockito.atLeastOnce()).proceed(Mockito.any(), Mockito.any());
- Mockito.verify(mockExecChain, Mockito.atMost(2)).proceed(Mockito.any(), Mockito.any());
- }
-
- @Test
- public void testStaleWhileRevalidateReturnsStaleNonRevalidatableEntryWithWarning()
- throws Exception {
- config = CacheConfig.custom().setMaxCacheEntries(MAX_ENTRIES).setMaxObjectSize(MAX_BYTES)
- .setAsynchronousWorkers(1).build();
-
- impl = new CachingExec(cache, executorService, ImmediateSchedulingStrategy.INSTANCE, config);
-
- final ClassicHttpRequest req1 = new BasicClassicHttpRequest("GET", "/");
- final ClassicHttpResponse resp1 = HttpTestUtils.make200Response();
- final Instant now = Instant.now();
- final Instant tenSecondsAgo = now.minusSeconds(10);
- resp1.setHeader("Cache-Control", "public, max-age=5, stale-while-revalidate=15");
- resp1.setHeader("Date", DateUtils.formatStandardDate(tenSecondsAgo));
-
- final ClassicHttpRequest req2 = new BasicClassicHttpRequest("GET", "/");
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp1);
-
- execute(req1);
- final ClassicHttpResponse result = execute(req2);
-
- assertEquals(HttpStatus.SC_OK, result.getCode());
- boolean warning110Found = false;
- for (final Header h : result.getHeaders("Warning")) {
- for (final WarningValue wv : WarningValue.getWarningValues(h)) {
- if (wv.getWarnCode() == 110) {
- warning110Found = true;
- break;
- }
- }
- }
- assertTrue(warning110Found);
-
- Mockito.verify(mockExecChain, Mockito.atLeastOnce()).proceed(Mockito.any(), Mockito.any());
- Mockito.verify(mockExecChain, Mockito.atMost(2)).proceed(Mockito.any(), Mockito.any());
- }
-
- @Test
- public void testCanAlsoServeStale304sWhileRevalidating()
- throws Exception {
-
- config = CacheConfig.custom()
- .setMaxCacheEntries(MAX_ENTRIES)
- .setMaxObjectSize(MAX_BYTES)
- .setAsynchronousWorkers(1)
- .setSharedCache(false)
- .build();
- impl = new CachingExec(cache, executorService, ImmediateSchedulingStrategy.INSTANCE, config);
-
- final ClassicHttpRequest req1 = new BasicClassicHttpRequest("GET", "/");
- final ClassicHttpResponse resp1 = HttpTestUtils.make200Response();
- final Instant now = Instant.now();
- final Instant tenSecondsAgo = now.minusSeconds(10);
- resp1.setHeader("Cache-Control", "private, stale-while-revalidate=15");
- resp1.setHeader("ETag","\"etag\"");
- resp1.setHeader("Date", DateUtils.formatStandardDate(tenSecondsAgo));
-
- final ClassicHttpRequest req2 = new BasicClassicHttpRequest("GET", "/");
- req2.setHeader("If-None-Match","\"etag\"");
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp1);
-
- execute(req1);
- final ClassicHttpResponse result = execute(req2);
-
- assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getCode());
- boolean warning110Found = false;
- for(final Header h : result.getHeaders("Warning")) {
- for(final WarningValue wv : WarningValue.getWarningValues(h)) {
- if (wv.getWarnCode() == 110) {
- warning110Found = true;
- break;
- }
- }
- }
- assertTrue(warning110Found);
-
- Mockito.verify(mockExecChain, Mockito.atLeastOnce()).proceed(Mockito.any(), Mockito.any());
- Mockito.verify(mockExecChain, Mockito.atMost(2)).proceed(Mockito.any(), Mockito.any());
- }
-
- @Test
- public void testStaleWhileRevalidateYieldsToMustRevalidate()
- throws Exception {
-
- final Instant now = Instant.now();
- final Instant tenSecondsAgo = now.minusSeconds(10);
-
- config = CacheConfig.custom()
- .setMaxCacheEntries(MAX_ENTRIES)
- .setMaxObjectSize(MAX_BYTES)
- .setAsynchronousWorkers(1)
- .build();
- impl = new CachingExec(cache, null, config);
-
- final ClassicHttpRequest req1 = new BasicClassicHttpRequest("GET", "/");
- final ClassicHttpResponse resp1 = HttpTestUtils.make200Response();
- resp1.setHeader("Cache-Control", "public, max-age=5, stale-while-revalidate=15, must-revalidate");
- resp1.setHeader("ETag","\"etag\"");
- resp1.setHeader("Date", DateUtils.formatStandardDate(tenSecondsAgo));
-
- final ClassicHttpRequest req2 = new BasicClassicHttpRequest("GET", "/");
- final ClassicHttpResponse resp2 = HttpTestUtils.make200Response();
- resp2.setHeader("Cache-Control", "public, max-age=5, stale-while-revalidate=15, must-revalidate");
- resp2.setHeader("ETag","\"etag\"");
- resp2.setHeader("Date", DateUtils.formatStandardDate(now));
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp1);
-
- execute(req1);
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp2);
-
- final ClassicHttpResponse result = execute(req2);
-
- assertEquals(HttpStatus.SC_OK, result.getCode());
- boolean warning110Found = false;
- for(final Header h : result.getHeaders("Warning")) {
- for(final WarningValue wv : WarningValue.getWarningValues(h)) {
- if (wv.getWarnCode() == 110) {
- warning110Found = true;
- break;
- }
- }
- }
- assertFalse(warning110Found);
- }
-
- @Test
- public void testStaleWhileRevalidateYieldsToProxyRevalidateForSharedCache()
- throws Exception {
-
- final Instant now = Instant.now();
- final Instant tenSecondsAgo = now.minusSeconds(10);
-
- config = CacheConfig.custom()
- .setMaxCacheEntries(MAX_ENTRIES)
- .setMaxObjectSize(MAX_BYTES)
- .setAsynchronousWorkers(1)
- .setSharedCache(true)
- .build();
- impl = new CachingExec(cache, null, config);
-
- final ClassicHttpRequest req1 = new BasicClassicHttpRequest("GET", "/");
- final ClassicHttpResponse resp1 = HttpTestUtils.make200Response();
- resp1.setHeader("Cache-Control", "public, max-age=5, stale-while-revalidate=15, proxy-revalidate");
- resp1.setHeader("ETag","\"etag\"");
- resp1.setHeader("Date", DateUtils.formatStandardDate(tenSecondsAgo));
-
- final ClassicHttpRequest req2 = new BasicClassicHttpRequest("GET", "/");
- final ClassicHttpResponse resp2 = HttpTestUtils.make200Response();
- resp2.setHeader("Cache-Control", "public, max-age=5, stale-while-revalidate=15, proxy-revalidate");
- resp2.setHeader("ETag","\"etag\"");
- resp2.setHeader("Date", DateUtils.formatStandardDate(now));
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp1);
-
- execute(req1);
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp2);
-
- final ClassicHttpResponse result = execute(req2);
-
- assertEquals(HttpStatus.SC_OK, result.getCode());
- boolean warning110Found = false;
- for(final Header h : result.getHeaders("Warning")) {
- for(final WarningValue wv : WarningValue.getWarningValues(h)) {
- if (wv.getWarnCode() == 110) {
- warning110Found = true;
- break;
- }
- }
- }
- assertFalse(warning110Found);
- }
-
- @Test
- public void testStaleWhileRevalidateYieldsToExplicitFreshnessRequest()
- throws Exception {
-
- final Instant now = Instant.now();
- final Instant tenSecondsAgo = now.minusSeconds(10);
-
- config = CacheConfig.custom()
- .setMaxCacheEntries(MAX_ENTRIES)
- .setMaxObjectSize(MAX_BYTES)
- .setAsynchronousWorkers(1)
- .setSharedCache(true)
- .build();
- impl = new CachingExec(cache, null, config);
-
- final ClassicHttpRequest req1 = new BasicClassicHttpRequest("GET", "/");
- final ClassicHttpResponse resp1 = HttpTestUtils.make200Response();
- resp1.setHeader("Cache-Control", "public, max-age=5, stale-while-revalidate=15");
- resp1.setHeader("ETag","\"etag\"");
- resp1.setHeader("Date", DateUtils.formatStandardDate(tenSecondsAgo));
-
- final ClassicHttpRequest req2 = new BasicClassicHttpRequest("GET", "/");
- req2.setHeader("Cache-Control","min-fresh=2");
- final ClassicHttpResponse resp2 = HttpTestUtils.make200Response();
- resp2.setHeader("Cache-Control", "public, max-age=5, stale-while-revalidate=15");
- resp2.setHeader("ETag","\"etag\"");
- resp2.setHeader("Date", DateUtils.formatStandardDate(now));
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp1);
-
- execute(req1);
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp2);
-
- final ClassicHttpResponse result = execute(req2);
-
- assertEquals(HttpStatus.SC_OK, result.getCode());
- boolean warning110Found = false;
- for(final Header h : result.getHeaders("Warning")) {
- for(final WarningValue wv : WarningValue.getWarningValues(h)) {
- if (wv.getWarnCode() == 110) {
- warning110Found = true;
- break;
- }
- }
- }
- assertFalse(warning110Found);
- }
-
}
diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestWarningValue.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestWarningValue.java
deleted file mode 100644
index e9b661ff7..000000000
--- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestWarningValue.java
+++ /dev/null
@@ -1,230 +0,0 @@
-/*
- * ====================================================================
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
- *
- */
-package org.apache.hc.client5.http.impl.cache;
-
-import java.time.Instant;
-
-import org.apache.hc.client5.http.utils.DateUtils;
-import org.apache.hc.core5.http.Header;
-import org.apache.hc.core5.http.message.BasicHeader;
-import org.junit.jupiter.api.Assertions;
-import org.junit.jupiter.api.Test;
-
-public class TestWarningValue {
-
- @Test
- public void testParseSingleWarnValue() {
- final Header h = new BasicHeader("Warning","110 fred \"stale\"");
- final WarningValue[] result = WarningValue.getWarningValues(h);
- Assertions.assertEquals(1, result.length);
- final WarningValue wv = result[0];
- Assertions.assertEquals(110, wv.getWarnCode());
- Assertions.assertEquals("fred", wv.getWarnAgent());
- Assertions.assertEquals("\"stale\"", wv.getWarnText());
- Assertions.assertNull(wv.getWarnDate());
- }
-
- @Test
- public void testParseMultipleWarnValues() {
- final Header h = new BasicHeader("Warning","110 fred \"stale\", 111 wilma \"other\"");
- final WarningValue[] result = WarningValue.getWarningValues(h);
- Assertions.assertEquals(2, result.length);
- WarningValue wv = result[0];
- Assertions.assertEquals(110, wv.getWarnCode());
- Assertions.assertEquals("fred", wv.getWarnAgent());
- Assertions.assertEquals("\"stale\"", wv.getWarnText());
- Assertions.assertNull(wv.getWarnDate());
- wv = result[1];
- Assertions.assertEquals(111, wv.getWarnCode());
- Assertions.assertEquals("wilma", wv.getWarnAgent());
- Assertions.assertEquals("\"other\"", wv.getWarnText());
- Assertions.assertNull(wv.getWarnDate());
- }
-
- @Test
- public void testMidHeaderParseErrorRecovery() {
- final Header h = new BasicHeader("Warning","110 fred \"stale\", bogus, 111 wilma \"other\"");
- final WarningValue[] result = WarningValue.getWarningValues(h);
- Assertions.assertEquals(2, result.length);
- WarningValue wv = result[0];
- Assertions.assertEquals(110, wv.getWarnCode());
- Assertions.assertEquals("fred", wv.getWarnAgent());
- Assertions.assertEquals("\"stale\"", wv.getWarnText());
- Assertions.assertNull(wv.getWarnDate());
- wv = result[1];
- Assertions.assertEquals(111, wv.getWarnCode());
- Assertions.assertEquals("wilma", wv.getWarnAgent());
- Assertions.assertEquals("\"other\"", wv.getWarnText());
- Assertions.assertNull(wv.getWarnDate());
- }
-
- @Test
- public void testTrickyCommaMidHeaderParseErrorRecovery() {
- final Header h = new BasicHeader("Warning","110 fred \"stale\", \"bogus, dude\", 111 wilma \"other\"");
- final WarningValue[] result = WarningValue.getWarningValues(h);
- Assertions.assertEquals(2, result.length);
- WarningValue wv = result[0];
- Assertions.assertEquals(110, wv.getWarnCode());
- Assertions.assertEquals("fred", wv.getWarnAgent());
- Assertions.assertEquals("\"stale\"", wv.getWarnText());
- Assertions.assertNull(wv.getWarnDate());
- wv = result[1];
- Assertions.assertEquals(111, wv.getWarnCode());
- Assertions.assertEquals("wilma", wv.getWarnAgent());
- Assertions.assertEquals("\"other\"", wv.getWarnText());
- Assertions.assertNull(wv.getWarnDate());
- }
-
- @Test
- public void testParseErrorRecoveryAtEndOfHeader() {
- final Header h = new BasicHeader("Warning","110 fred \"stale\", 111 wilma \"other\", \"bogus, dude\"");
- final WarningValue[] result = WarningValue.getWarningValues(h);
- Assertions.assertEquals(2, result.length);
- WarningValue wv = result[0];
- Assertions.assertEquals(110, wv.getWarnCode());
- Assertions.assertEquals("fred", wv.getWarnAgent());
- Assertions.assertEquals("\"stale\"", wv.getWarnText());
- Assertions.assertNull(wv.getWarnDate());
- wv = result[1];
- Assertions.assertEquals(111, wv.getWarnCode());
- Assertions.assertEquals("wilma", wv.getWarnAgent());
- Assertions.assertEquals("\"other\"", wv.getWarnText());
- Assertions.assertNull(wv.getWarnDate());
- }
-
- @Test
- public void testConstructSingleWarnValue() {
- final WarningValue impl = new WarningValue("110 fred \"stale\"");
- Assertions.assertEquals(110, impl.getWarnCode());
- Assertions.assertEquals("fred", impl.getWarnAgent());
- Assertions.assertEquals("\"stale\"", impl.getWarnText());
- Assertions.assertNull(impl.getWarnDate());
- }
-
- @Test
- public void testConstructWarnValueWithIPv4Address() {
- final WarningValue impl = new WarningValue("110 192.168.1.1 \"stale\"");
- Assertions.assertEquals(110, impl.getWarnCode());
- Assertions.assertEquals("192.168.1.1", impl.getWarnAgent());
- Assertions.assertEquals("\"stale\"", impl.getWarnText());
- Assertions.assertNull(impl.getWarnDate());
- }
-
- @Test
- public void testConstructWarnValueWithHostname() {
- final WarningValue impl = new WarningValue("110 foo.example.com \"stale\"");
- Assertions.assertEquals(110, impl.getWarnCode());
- Assertions.assertEquals("foo.example.com", impl.getWarnAgent());
- Assertions.assertEquals("\"stale\"", impl.getWarnText());
- Assertions.assertNull(impl.getWarnDate());
- }
-
- @Test
- public void testConstructWarnValueWithHostnameAndPort() {
- final WarningValue impl = new WarningValue("110 foo.example.com:8080 \"stale\"");
- Assertions.assertEquals(110, impl.getWarnCode());
- Assertions.assertEquals("foo.example.com:8080", impl.getWarnAgent());
- Assertions.assertEquals("\"stale\"", impl.getWarnText());
- Assertions.assertNull(impl.getWarnDate());
- }
-
- @Test
- public void testConstructWarnValueWithIPv4AddressAndPort() {
- final WarningValue impl = new WarningValue("110 192.168.1.1:8080 \"stale\"");
- Assertions.assertEquals(110, impl.getWarnCode());
- Assertions.assertEquals("192.168.1.1:8080", impl.getWarnAgent());
- Assertions.assertEquals("\"stale\"", impl.getWarnText());
- Assertions.assertNull(impl.getWarnDate());
- }
-
- @Test
- public void testConstructWarnValueWithPseudonym() {
- final WarningValue impl = new WarningValue("110 ca$hm0ney \"stale\"");
- Assertions.assertEquals(110, impl.getWarnCode());
- Assertions.assertEquals("ca$hm0ney", impl.getWarnAgent());
- Assertions.assertEquals("\"stale\"", impl.getWarnText());
- Assertions.assertNull(impl.getWarnDate());
- }
-
- @Test
- public void testConstructWarnValueWithTextWithSpaces() {
- final WarningValue impl = new WarningValue("110 fred \"stale stuff\"");
- Assertions.assertEquals(110, impl.getWarnCode());
- Assertions.assertEquals("fred", impl.getWarnAgent());
- Assertions.assertEquals("\"stale stuff\"", impl.getWarnText());
- Assertions.assertNull(impl.getWarnDate());
- }
-
- @Test
- public void testConstructWarnValueWithTextWithCommas() {
- final WarningValue impl = new WarningValue("110 fred \"stale, stuff\"");
- Assertions.assertEquals(110, impl.getWarnCode());
- Assertions.assertEquals("fred", impl.getWarnAgent());
- Assertions.assertEquals("\"stale, stuff\"", impl.getWarnText());
- Assertions.assertNull(impl.getWarnDate());
- }
-
- @Test
- public void testConstructWarnValueWithTextWithEscapedQuotes() {
- final WarningValue impl = new WarningValue("110 fred \"stale\\\" stuff\"");
- Assertions.assertEquals(110, impl.getWarnCode());
- Assertions.assertEquals("fred", impl.getWarnAgent());
- Assertions.assertEquals("\"stale\\\" stuff\"", impl.getWarnText());
- Assertions.assertNull(impl.getWarnDate());
- }
-
- @Test
- public void testConstructWarnValueWithAscTimeWarnDate() throws Exception {
- final WarningValue impl = new WarningValue("110 fred \"stale\" \"Sun Nov 6 08:49:37 1994\"");
- Assertions.assertEquals(110, impl.getWarnCode());
- Assertions.assertEquals("fred", impl.getWarnAgent());
- Assertions.assertEquals("\"stale\"", impl.getWarnText());
- final Instant target = DateUtils.parseStandardDate("Sun Nov 6 08:49:37 1994");
- Assertions.assertEquals(target, impl.getWarnDate());
- }
-
- @Test
- public void testConstructWarnValueWithRFC850WarnDate() throws Exception {
- final WarningValue impl = new WarningValue("110 fred \"stale\" \"Sunday, 06-Nov-94 08:49:37 GMT\"");
- Assertions.assertEquals(110, impl.getWarnCode());
- Assertions.assertEquals("fred", impl.getWarnAgent());
- Assertions.assertEquals("\"stale\"", impl.getWarnText());
- final Instant target = DateUtils.parseStandardDate("Sunday, 06-Nov-94 08:49:37 GMT");
- Assertions.assertEquals(target, impl.getWarnDate());
- }
-
- @Test
- public void testConstructWarnValueWithRFC1123WarnDate() throws Exception {
- final WarningValue impl = new WarningValue("110 fred \"stale\" \"Sun, 06 Nov 1994 08:49:37 GMT\"");
- Assertions.assertEquals(110, impl.getWarnCode());
- Assertions.assertEquals("fred", impl.getWarnAgent());
- Assertions.assertEquals("\"stale\"", impl.getWarnText());
- final Instant target = DateUtils.parseStandardDate("Sun, 06 Nov 1994 08:49:37 GMT");
- Assertions.assertEquals(target, impl.getWarnDate());
- }
-
-}
[httpcomponents-client] 03/06: HTTPCLIENT-2277: Removal of the HTTP protocol logic presently enforced in the caching layer directly related to the caching functionality. The enforcement of general protocol requirements should be implemented in the protocol layer.
Posted by ol...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
olegk pushed a commit to branch 5.4.x
in repository https://gitbox.apache.org/repos/asf/httpcomponents-client.git
commit a37d79144af3f7341b337afecca85c59ee709af2
Author: Oleg Kalnichevski <ol...@apache.org>
AuthorDate: Sun Jul 23 17:23:19 2023 +0200
HTTPCLIENT-2277: Removal of the HTTP protocol logic presently enforced in the caching layer directly related to the caching functionality. The enforcement of general protocol requirements should be implemented in the protocol layer.
---
.../client5/http/impl/cache/AsyncCachingExec.java | 10 +-
.../hc/client5/http/impl/cache/CacheConfig.java | 23 +--
.../impl/cache/CachedHttpResponseGenerator.java | 27 ---
.../hc/client5/http/impl/cache/CachingExec.java | 9 +-
.../client5/http/impl/cache/CachingExecBase.java | 22 ---
.../http/impl/cache/RequestProtocolCompliance.java | 199 ---------------------
.../http/impl/cache/RequestProtocolError.java | 36 ----
.../http/impl/cache/TestCachingExecChain.java | 49 -----
.../http/impl/cache/TestProtocolRequirements.java | 184 -------------------
.../impl/cache/TestRequestProtocolCompliance.java | 187 -------------------
10 files changed, 11 insertions(+), 735 deletions(-)
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 df410eba6..1cda6c85d 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
@@ -112,12 +112,11 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
final CacheableRequestPolicy cacheableRequestPolicy,
final CachedResponseSuitabilityChecker suitabilityChecker,
final ResponseProtocolCompliance responseCompliance,
- final RequestProtocolCompliance requestCompliance,
final DefaultAsyncCacheRevalidator cacheRevalidator,
final ConditionalRequestBuilder<HttpRequest> conditionalRequestBuilder,
final CacheConfig config) {
super(validityPolicy, responseCachingPolicy, responseGenerator, cacheableRequestPolicy,
- suitabilityChecker, responseCompliance, requestCompliance, config);
+ suitabilityChecker, responseCompliance, config);
this.responseCache = responseCache;
this.cacheRevalidator = cacheRevalidator;
this.conditionalRequestBuilder = conditionalRequestBuilder;
@@ -231,7 +230,6 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
return;
}
- requestCompliance.makeRequestCompliant(request);
request.addHeader(HttpHeaders.VIA,via);
final RequestCacheControl requestCacheControl = CacheControlHeaderParser.INSTANCE.parse(request);
@@ -243,12 +241,6 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
public void completed(final CacheMatch result) {
final CacheHit hit = result != null ? result.hit : null;
final CacheHit root = result != null ? result.root : null;
- final SimpleHttpResponse fatalErrorResponse = getFatallyNonCompliantResponse(request, context, hit != null);
- if (fatalErrorResponse != null) {
- triggerResponse(fatalErrorResponse, scope, asyncExecCallback);
- return;
- }
-
if (hit == null) {
LOG.debug("Cache miss");
handleCacheMiss(requestCacheControl, root, target, request, entityProducer, scope, chain, asyncExecCallback);
diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheConfig.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheConfig.java
index 87ed4dbf4..cde5b7077 100644
--- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheConfig.java
+++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheConfig.java
@@ -117,8 +117,10 @@ public class CacheConfig implements Cloneable {
*/
public final static boolean DEFAULT_303_CACHING_ENABLED = false;
- /** Default setting to allow weak tags on PUT/DELETE methods
+ /**
+ * @deprecated No longer applicable. Do not use.
*/
+ @Deprecated
public final static boolean DEFAULT_WEAK_ETAG_ON_PUTDELETE_ALLOWED = false;
/** Default setting for heuristic caching
@@ -146,7 +148,6 @@ public class CacheConfig implements Cloneable {
private final int maxCacheEntries;
private final int maxUpdateRetries;
private final boolean allow303Caching;
- private final boolean weakETagOnPutDeleteAllowed;
private final boolean heuristicCachingEnabled;
private final float heuristicCoefficient;
private final TimeValue heuristicDefaultLifetime;
@@ -168,7 +169,6 @@ public class CacheConfig implements Cloneable {
final int maxCacheEntries,
final int maxUpdateRetries,
final boolean allow303Caching,
- final boolean weakETagOnPutDeleteAllowed,
final boolean heuristicCachingEnabled,
final float heuristicCoefficient,
final TimeValue heuristicDefaultLifetime,
@@ -183,7 +183,6 @@ public class CacheConfig implements Cloneable {
this.maxCacheEntries = maxCacheEntries;
this.maxUpdateRetries = maxUpdateRetries;
this.allow303Caching = allow303Caching;
- this.weakETagOnPutDeleteAllowed = weakETagOnPutDeleteAllowed;
this.heuristicCachingEnabled = heuristicCachingEnabled;
this.heuristicCoefficient = heuristicCoefficient;
this.heuristicDefaultLifetime = heuristicDefaultLifetime;
@@ -268,9 +267,12 @@ public class CacheConfig implements Cloneable {
/**
* Returns whether weak etags is allowed with PUT/DELETE methods.
* @return {@code true} if it is allowed.
+ *
+ * @deprecated Do not use.
*/
+ @Deprecated
public boolean isWeakETagOnPutDeleteAllowed() {
- return weakETagOnPutDeleteAllowed;
+ return true;
}
/**
@@ -349,14 +351,12 @@ public class CacheConfig implements Cloneable {
.setStaleIfErrorEnabled(config.isStaleIfErrorEnabled());
}
-
public static class Builder {
private long maxObjectSize;
private int maxCacheEntries;
private int maxUpdateRetries;
private boolean allow303Caching;
- private boolean weakETagOnPutDeleteAllowed;
private boolean heuristicCachingEnabled;
private float heuristicCoefficient;
private TimeValue heuristicDefaultLifetime;
@@ -372,7 +372,6 @@ public class CacheConfig implements Cloneable {
this.maxCacheEntries = DEFAULT_MAX_CACHE_ENTRIES;
this.maxUpdateRetries = DEFAULT_MAX_UPDATE_RETRIES;
this.allow303Caching = DEFAULT_303_CACHING_ENABLED;
- this.weakETagOnPutDeleteAllowed = DEFAULT_WEAK_ETAG_ON_PUTDELETE_ALLOWED;
this.heuristicCachingEnabled = DEFAULT_HEURISTIC_CACHING_ENABLED;
this.heuristicCoefficient = DEFAULT_HEURISTIC_COEFFICIENT;
this.heuristicDefaultLifetime = DEFAULT_HEURISTIC_LIFETIME;
@@ -418,12 +417,10 @@ public class CacheConfig implements Cloneable {
}
/**
- * Allows or disallows weak etags to be used with PUT/DELETE If-Match requests.
- * @param weakETagOnPutDeleteAllowed should be {@code true} to
- * permit weak etags, {@code false} to reject them.
+ * @deprecated No longer applicable. Do not use.
*/
+ @Deprecated
public Builder setWeakETagOnPutDeleteAllowed(final boolean weakETagOnPutDeleteAllowed) {
- this.weakETagOnPutDeleteAllowed = weakETagOnPutDeleteAllowed;
return this;
}
@@ -541,7 +538,6 @@ public class CacheConfig implements Cloneable {
maxCacheEntries,
maxUpdateRetries,
allow303Caching,
- weakETagOnPutDeleteAllowed,
heuristicCachingEnabled,
heuristicCoefficient,
heuristicDefaultLifetime,
@@ -562,7 +558,6 @@ public class CacheConfig implements Cloneable {
.append(", maxCacheEntries=").append(this.maxCacheEntries)
.append(", maxUpdateRetries=").append(this.maxUpdateRetries)
.append(", 303CachingEnabled=").append(this.allow303Caching)
- .append(", weakETagOnPutDeleteAllowed=").append(this.weakETagOnPutDeleteAllowed)
.append(", heuristicCachingEnabled=").append(this.heuristicCachingEnabled)
.append(", heuristicCoefficient=").append(this.heuristicCoefficient)
.append(", heuristicDefaultLifetime=").append(this.heuristicDefaultLifetime)
diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachedHttpResponseGenerator.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachedHttpResponseGenerator.java
index 293d7e584..1cd79428a 100644
--- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachedHttpResponseGenerator.java
+++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachedHttpResponseGenerator.java
@@ -163,31 +163,4 @@ class CachedHttpResponseGenerator {
return Method.GET.isSame(request.getMethod()) && cacheEntry.getResource() != null;
}
- /**
- * Extract error information about the {@link HttpRequest} telling the 'caller'
- * that a problem occurred.
- *
- * @param errorCheck What type of error should I get
- * @return The {@link HttpResponse} that is the error generated
- */
- public SimpleHttpResponse getErrorForRequest(final RequestProtocolError errorCheck) {
- switch (errorCheck) {
- case BODY_BUT_NO_LENGTH_ERROR:
- return SimpleHttpResponse.create(HttpStatus.SC_LENGTH_REQUIRED);
-
- case WEAK_ETAG_AND_RANGE_ERROR:
- return SimpleHttpResponse.create(HttpStatus.SC_BAD_REQUEST,
- "Weak eTag not compatible with byte range", ContentType.DEFAULT_TEXT);
-
- case WEAK_ETAG_ON_PUTDELETE_METHOD_ERROR:
- return SimpleHttpResponse.create(HttpStatus.SC_PRECONDITION_FAILED,
- "Weak eTag not compatible with PUT or DELETE requests");
-
- default:
- throw new IllegalStateException(
- "The request was compliant, therefore no error can be generated for it.");
-
- }
- }
-
}
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 e1fecc5f2..3e2963bef 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
@@ -120,12 +120,11 @@ class CachingExec extends CachingExecBase implements ExecChainHandler {
final CacheableRequestPolicy cacheableRequestPolicy,
final CachedResponseSuitabilityChecker suitabilityChecker,
final ResponseProtocolCompliance responseCompliance,
- final RequestProtocolCompliance requestCompliance,
final DefaultCacheRevalidator cacheRevalidator,
final ConditionalRequestBuilder<ClassicHttpRequest> conditionalRequestBuilder,
final CacheConfig config) {
super(validityPolicy, responseCachingPolicy, responseGenerator, cacheableRequestPolicy,
- suitabilityChecker, responseCompliance, requestCompliance, config);
+ suitabilityChecker, responseCompliance, config);
this.responseCache = responseCache;
this.cacheRevalidator = cacheRevalidator;
this.conditionalRequestBuilder = conditionalRequestBuilder;
@@ -170,12 +169,6 @@ class CachingExec extends CachingExecBase implements ExecChainHandler {
final CacheHit hit = result != null ? result.hit : null;
final CacheHit root = result != null ? result.root : null;
- final SimpleHttpResponse fatalErrorResponse = getFatallyNonCompliantResponse(request, context, hit != null);
- if (fatalErrorResponse != null) {
- return convert(fatalErrorResponse, scope);
- }
-
- requestCompliance.makeRequestCompliant(request);
request.addHeader(HttpHeaders.VIA, via);
final RequestCacheControl requestCacheControl = CacheControlHeaderParser.INSTANCE.parse(request);
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 3531fae16..b29d28a87 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
@@ -28,7 +28,6 @@ package org.apache.hc.client5.http.impl.cache;
import java.io.IOException;
import java.time.Instant;
-import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
@@ -70,13 +69,10 @@ public class CachingExecBase {
final CacheableRequestPolicy cacheableRequestPolicy;
final CachedResponseSuitabilityChecker suitabilityChecker;
final ResponseProtocolCompliance responseCompliance;
- final RequestProtocolCompliance requestCompliance;
final CacheConfig cacheConfig;
private static final Logger LOG = LoggerFactory.getLogger(CachingExecBase.class);
- private static final TimeValue ONE_DAY = TimeValue.ofHours(24);
-
CachingExecBase(
final CacheValidityPolicy validityPolicy,
final ResponseCachingPolicy responseCachingPolicy,
@@ -84,14 +80,12 @@ public class CachingExecBase {
final CacheableRequestPolicy cacheableRequestPolicy,
final CachedResponseSuitabilityChecker suitabilityChecker,
final ResponseProtocolCompliance responseCompliance,
- final RequestProtocolCompliance requestCompliance,
final CacheConfig config) {
this.responseCachingPolicy = responseCachingPolicy;
this.validityPolicy = validityPolicy;
this.responseGenerator = responseGenerator;
this.cacheableRequestPolicy = cacheableRequestPolicy;
this.suitabilityChecker = suitabilityChecker;
- this.requestCompliance = requestCompliance;
this.responseCompliance = responseCompliance;
this.cacheConfig = config != null ? config : CacheConfig.DEFAULT;
}
@@ -104,7 +98,6 @@ public class CachingExecBase {
this.cacheableRequestPolicy = new CacheableRequestPolicy();
this.suitabilityChecker = new CachedResponseSuitabilityChecker(this.validityPolicy, this.cacheConfig);
this.responseCompliance = new ResponseProtocolCompliance();
- this.requestCompliance = new RequestProtocolCompliance(this.cacheConfig.isWeakETagOnPutDeleteAllowed());
this.responseCachingPolicy = new ResponseCachingPolicy(
this.cacheConfig.getMaxObjectSize(),
this.cacheConfig.isSharedCache(),
@@ -141,21 +134,6 @@ public class CachingExecBase {
return cacheUpdates.get();
}
- /**
- * @since 5.2
- */
- SimpleHttpResponse getFatallyNonCompliantResponse(
- final HttpRequest request,
- final HttpContext context,
- final boolean resourceExists) {
- final List<RequestProtocolError> fatalError = requestCompliance.requestIsFatallyNonCompliant(request, resourceExists);
- if (fatalError != null && !fatalError.isEmpty()) {
- setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE);
- return responseGenerator.getErrorForRequest(fatalError.get(0));
- }
- return null;
- }
-
void recordCacheMiss(final HttpHost target, final HttpRequest request) {
cacheMisses.getAndIncrement();
if (LOG.isDebugEnabled()) {
diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/RequestProtocolCompliance.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/RequestProtocolCompliance.java
deleted file mode 100644
index 7a60d5c42..000000000
--- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/RequestProtocolCompliance.java
+++ /dev/null
@@ -1,199 +0,0 @@
-/*
- * ====================================================================
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
- *
- */
-package org.apache.hc.client5.http.impl.cache;
-
-import static org.apache.hc.client5.http.utils.DateUtils.parseStandardDate;
-
-import java.time.Instant;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.apache.hc.core5.http.Header;
-import org.apache.hc.core5.http.HttpHeaders;
-import org.apache.hc.core5.http.HttpRequest;
-import org.apache.hc.core5.http.HttpVersion;
-import org.apache.hc.core5.http.Method;
-import org.apache.hc.core5.http.ProtocolVersion;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-class RequestProtocolCompliance {
- private final boolean weakETagOnPutDeleteAllowed;
-
- private static final Logger LOG = LoggerFactory.getLogger(RequestProtocolCompliance.class);
-
- public RequestProtocolCompliance() {
- super();
- this.weakETagOnPutDeleteAllowed = false;
- }
-
- public RequestProtocolCompliance(final boolean weakETagOnPutDeleteAllowed) {
- super();
- this.weakETagOnPutDeleteAllowed = weakETagOnPutDeleteAllowed;
- }
-
- /**
- * Test to see if the {@link HttpRequest} is HTTP1.1 compliant or not
- * and if not, we can not continue.
- *
- * @param request the HttpRequest Object
- * @return list of {@link RequestProtocolError}
- */
- public List<RequestProtocolError> requestIsFatallyNonCompliant(final HttpRequest request, final boolean resourceExists) {
- final List<RequestProtocolError> theErrors = new ArrayList<>();
-
- RequestProtocolError anError = requestHasWeakETagAndRange(request);
- if (anError != null) {
- theErrors.add(anError);
- }
-
- if (!weakETagOnPutDeleteAllowed) {
- anError = requestHasWeekETagForPUTOrDELETEIfMatch(request, resourceExists);
- if (anError != null) {
- theErrors.add(anError);
- }
- }
-
- return theErrors;
- }
-
- /**
- * If the {@link HttpRequest} is non-compliant but 'fixable' we go ahead and
- * fix the request here.
- *
- * @param request the request to check for compliance
- */
- public void makeRequestCompliant(final HttpRequest request) {
- decrementOPTIONSMaxForwardsIfGreaterThen0(request);
-
- if (requestVersionIsTooLow(request) || requestMinorVersionIsTooHighMajorVersionsMatch(request)) {
- request.setVersion(HttpVersion.HTTP_1_1);
- }
- }
-
- private void decrementOPTIONSMaxForwardsIfGreaterThen0(final HttpRequest request) {
- if (!Method.OPTIONS.isSame(request.getMethod())) {
- return;
- }
-
- final Header maxForwards = request.getFirstHeader(HttpHeaders.MAX_FORWARDS);
- if (maxForwards == null) {
- return;
- }
-
- request.removeHeaders(HttpHeaders.MAX_FORWARDS);
- final int currentMaxForwards = Integer.parseInt(maxForwards.getValue());
-
- request.setHeader(HttpHeaders.MAX_FORWARDS, Integer.toString(currentMaxForwards - 1));
- }
-
- protected boolean requestMinorVersionIsTooHighMajorVersionsMatch(final HttpRequest request) {
- final ProtocolVersion requestProtocol = request.getVersion();
- if (requestProtocol == null) {
- return false;
- }
- if (requestProtocol.getMajor() != HttpVersion.HTTP_1_1.getMajor()) {
- return false;
- }
-
- return requestProtocol.getMinor() > HttpVersion.HTTP_1_1.getMinor();
- }
-
- protected boolean requestVersionIsTooLow(final HttpRequest request) {
- final ProtocolVersion requestProtocol = request.getVersion();
- return requestProtocol != null && requestProtocol.compareToVersion(HttpVersion.HTTP_1_1) < 0;
- }
-
- private RequestProtocolError requestHasWeakETagAndRange(final HttpRequest request) {
- final String method = request.getMethod();
- if (!(Method.GET.isSame(method) || Method.HEAD.isSame(method))) {
- return null;
- }
-
- if (!request.containsHeader(HttpHeaders.RANGE)) {
- return null;
- }
-
- final Instant ifRangeInstant = parseStandardDate(request, HttpHeaders.IF_RANGE);
- final Instant lastModifiedInstant = parseStandardDate(request, HttpHeaders.LAST_MODIFIED);
-
- for (final Iterator<Header> it = request.headerIterator(HttpHeaders.IF_RANGE); it.hasNext(); ) {
- final String val = it.next().getValue();
- if (val.startsWith("W/")) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Weak ETag found in If-Range header");
- }
- return RequestProtocolError.WEAK_ETAG_AND_RANGE_ERROR;
- } else {
- // Not a strong validator or doesn't match Last-Modified
- if (ifRangeInstant != null && lastModifiedInstant != null
- && !ifRangeInstant.equals(lastModifiedInstant)) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("If-Range does not match Last-Modified");
- }
- return RequestProtocolError.WEAK_ETAG_AND_RANGE_ERROR;
- }
- }
- }
- return null;
- }
-
- private RequestProtocolError requestHasWeekETagForPUTOrDELETEIfMatch(final HttpRequest request, final boolean resourceExists) {
- final String method = request.getMethod();
- if (!(Method.PUT.isSame(method) || Method.DELETE.isSame(method) || Method.POST.isSame(method))
- ) {
- return null;
- }
-
- for (final Iterator<Header> it = request.headerIterator(HttpHeaders.IF_MATCH); it.hasNext();) {
- final String val = it.next().getValue();
- if (val.equals("*") && !resourceExists) {
- return null;
- }
- if (val.startsWith("W/")) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Weak ETag found in If-Match header");
- }
- return RequestProtocolError.WEAK_ETAG_ON_PUTDELETE_METHOD_ERROR;
- }
- }
-
- for (final Iterator<Header> it = request.headerIterator(HttpHeaders.IF_NONE_MATCH); it.hasNext();) {
- final String val = it.next().getValue();
- if (val.startsWith("W/") || (val.equals("*") && resourceExists)) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Weak ETag found in If-None-Match header");
- }
- return RequestProtocolError.WEAK_ETAG_ON_PUTDELETE_METHOD_ERROR;
- }
- }
-
- return null;
- }
-
-}
diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/RequestProtocolError.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/RequestProtocolError.java
deleted file mode 100644
index 452f2a334..000000000
--- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/RequestProtocolError.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * ====================================================================
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
- *
- */
-package org.apache.hc.client5.http.impl.cache;
-
-enum RequestProtocolError {
-
- UNKNOWN,
- BODY_BUT_NO_LENGTH_ERROR,
- WEAK_ETAG_ON_PUTDELETE_METHOD_ERROR,
- WEAK_ETAG_AND_RANGE_ERROR
-
-}
diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCachingExecChain.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCachingExecChain.java
index fb2b7abab..81303fb2f 100644
--- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCachingExecChain.java
+++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCachingExecChain.java
@@ -49,7 +49,6 @@ import org.apache.hc.client5.http.cache.HttpCacheEntryFactory;
import org.apache.hc.client5.http.cache.HttpCacheStorage;
import org.apache.hc.client5.http.classic.ExecChain;
import org.apache.hc.client5.http.classic.ExecRuntime;
-import org.apache.hc.client5.http.classic.methods.HttpDelete;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpOptions;
import org.apache.hc.client5.http.protocol.HttpClientContext;
@@ -58,7 +57,6 @@ import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpException;
-import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.HttpRequest;
import org.apache.hc.core5.http.HttpStatus;
@@ -103,8 +101,6 @@ public class TestCachingExecChain {
@Mock
ResponseProtocolCompliance responseCompliance;
@Mock
- RequestProtocolCompliance requestCompliance;
- @Mock
ConditionalRequestBuilder<ClassicHttpRequest> conditionalRequestBuilder;
@Mock
HttpCache responseCache;
@@ -249,16 +245,6 @@ public class TestCachingExecChain {
Assertions.assertEquals(CacheResponseStatus.CACHE_MODULE_RESPONSE, context.getCacheResponseStatus());
}
- @Test
- public void testSetsModuleGeneratedResponseContextForFatallyNoncompliantRequest() throws Exception {
- final ClassicHttpRequest req = new HttpGet("http://foo.example.com/");
- req.setHeader("Range", "bytes=0-50");
- req.setHeader("If-Range", "W/\"weak-etag\"");
-
- execute(req);
- Assertions.assertEquals(CacheResponseStatus.CACHE_MODULE_RESPONSE, context.getCacheResponseStatus());
- }
-
@Test
public void testRecordsClientProtocolInViaHeaderIfRequestNotServableFromCache() throws Exception {
final ClassicHttpRequest originalRequest = new BasicClassicHttpRequest("GET", "/");
@@ -1500,39 +1486,4 @@ public class TestCachingExecChain {
Mockito.verify(mockExecChain, Mockito.times(5)).proceed(Mockito.any(), Mockito.any());
}
- @Test
- public void testRequestWithWeakETagAndRange() throws Exception {
- final ClassicHttpRequest req1 = new HttpGet("http://foo1.example.com/");
- req1.addHeader(HttpHeaders.IF_MATCH, "W/\"weak1\"");
- req1.addHeader(HttpHeaders.RANGE, "bytes=0-50");
- req1.addHeader(HttpHeaders.IF_RANGE, "W/\"weak2\""); // ETag doesn't match with If-Match ETag
- final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK");
- resp1.setEntity(HttpTestUtils.makeBody(128));
- resp1.setHeader("Content-Length", "128");
- resp1.setHeader("ETag", "\"etag\"");
- resp1.setHeader("Date", DateUtils.formatStandardDate(Instant.now()));
- resp1.setHeader("Cache-Control", "public, max-age=3600");
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp1);
-
- final ClassicHttpResponse result = execute(req1);
- Assertions.assertEquals(HttpStatus.SC_BAD_REQUEST, result.getCode());
- }
-
- @Test
- public void testRequestWithWeakETagForPUTOrDELETEIfMatch() throws Exception {
- final ClassicHttpRequest req1 = new HttpDelete("http://foo1.example.com/");
- req1.addHeader(HttpHeaders.IF_MATCH, "W/\"weak1\"");
- final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK");
- resp1.setEntity(HttpTestUtils.makeBody(128));
- resp1.setHeader("Content-Length", "128");
- resp1.setHeader("ETag", "\"etag\"");
- resp1.setHeader("Date", DateUtils.formatStandardDate(Instant.now()));
- resp1.setHeader("Cache-Control", "public, max-age=3600");
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp1);
-
- final ClassicHttpResponse result = execute(req1);
- Assertions.assertEquals(HttpStatus.SC_PRECONDITION_FAILED, result.getCode());
- }
}
diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolRequirements.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolRequirements.java
index e8c025795..d75c79a72 100644
--- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolRequirements.java
+++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolRequirements.java
@@ -700,29 +700,6 @@ public class TestProtocolRequirements {
execute(request);
}
- /*
- * "If the Max-Forwards field-value is an integer greater than zero, the
- * proxy MUST decrement the field-value when it forwards the request."
- *
- * http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.2
- */
- @Test
- public void testDecrementsMaxForwardsWhenForwardingOPTIONSRequest() throws Exception {
-
- request = new BasicClassicHttpRequest("OPTIONS", "*");
- request.setHeader("Max-Forwards", "7");
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(originResponse);
-
- execute(request);
-
- final ArgumentCaptor<ClassicHttpRequest> reqCapture = ArgumentCaptor.forClass(ClassicHttpRequest.class);
- Mockito.verify(mockExecChain).proceed(reqCapture.capture(), Mockito.any());
-
- final ClassicHttpRequest captured = reqCapture.getValue();
- Assertions.assertEquals("6", captured.getFirstHeader("Max-Forwards").getValue());
- }
-
/*
* "If no Max-Forwards field is present in the request, then the forwarded
* request MUST NOT include a Max-Forwards field."
@@ -1110,51 +1087,6 @@ public class TestProtocolRequirements {
Mockito.verify(mockExecChain, Mockito.times(2)).proceed(Mockito.any(), Mockito.any());
}
- /*
- * "If the [206] response is the result of an If-Range request that used a
- * weak validator, the response MUST NOT include other entity-headers; this
- * prevents inconsistencies between cached entity-bodies and updated
- * headers."
- *
- * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.7
- */
- @Test
- public void test206ResponseToConditionalRangeRequestDoesNotIncludeOtherEntityHeaders() throws Exception {
-
- final ClassicHttpRequest req1 = new BasicClassicHttpRequest("GET", "/");
-
- final Instant now = Instant.now();
- final Instant oneHourAgo = now.minus(1, ChronoUnit.HOURS);
- originResponse = HttpTestUtils.make200Response();
- originResponse.addHeader("Allow", "GET,HEAD");
- originResponse.addHeader("Cache-Control", "max-age=3600");
- originResponse.addHeader("Content-Language", "en");
- originResponse.addHeader("Content-Encoding", "x-coding");
- originResponse.addHeader("Content-MD5", "Q2hlY2sgSW50ZWdyaXR5IQ==");
- originResponse.addHeader("Content-Length", "128");
- originResponse.addHeader("Content-Type", "application/octet-stream");
- originResponse.addHeader("Last-Modified", DateUtils.formatStandardDate(oneHourAgo));
- originResponse.addHeader("ETag", "W/\"weak-tag\"");
-
- final ClassicHttpRequest req2 = new BasicClassicHttpRequest("GET", "/");
- req2.addHeader("If-Range", "W/\"weak-tag\"");
- req2.addHeader("Range", "bytes=0-50");
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(originResponse);
-
- execute(req1);
- final ClassicHttpResponse result = execute(req2);
-
- if (result.getCode() == HttpStatus.SC_PARTIAL_CONTENT) {
- Assertions.assertNull(result.getFirstHeader("Allow"));
- Assertions.assertNull(result.getFirstHeader("Content-Encoding"));
- Assertions.assertNull(result.getFirstHeader("Content-Language"));
- Assertions.assertNull(result.getFirstHeader("Content-MD5"));
- Assertions.assertNull(result.getFirstHeader("Last-Modified"));
- }
- Mockito.verify(mockExecChain, Mockito.times(1)).proceed(Mockito.any(), Mockito.any());
- }
-
/*
* "Otherwise, the [206] response MUST include all of the entity-headers
* that would have been returned with a 200 (OK) response to the same
@@ -1967,122 +1899,6 @@ public class TestProtocolRequirements {
Assertions.assertEquals("\"etag1\"", result.getFirstHeader("ETag").getValue());
}
- /*
- * "Clients MAY issue simple (non-subrange) GET requests with either weak
- * validators or strong validators. Clients MUST NOT use weak validators in
- * other forms of request."
- *
- * http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3
- *
- * Note that we can't determine a priori whether a given HTTP-date is a weak
- * or strong validator, because that might depend on an upstream client
- * having a cache with a Last-Modified and Date entry that allows the date
- * to be a strong validator. We can tell when *we* are generating a request
- * for validation, but we can't tell if we receive a conditional request
- * from upstream.
- */
- private ClassicHttpResponse testRequestWithWeakETagValidatorIsNotAllowed(final String header) throws Exception {
- final ClassicHttpResponse response = execute(request);
-
- // it's probably ok to return a 400 (Bad Request) to this client
- final ArgumentCaptor<ClassicHttpRequest> reqCapture = ArgumentCaptor.forClass(ClassicHttpRequest.class);
- Mockito.verify(mockExecChain, Mockito.atMostOnce()).proceed(reqCapture.capture(), Mockito.any());
- final List<ClassicHttpRequest> allRequests = reqCapture.getAllValues();
- if (!allRequests.isEmpty()) {
- final ClassicHttpRequest forwarded = reqCapture.getValue();
- if (forwarded != null) {
- final Header h = forwarded.getFirstHeader(header);
- if (h != null) {
- Assertions.assertFalse(h.getValue().startsWith("W/"));
- }
- }
- }
- return response;
- }
-
- @Test
- public void testSubrangeGETWithWeakETagIsNotAllowed() throws Exception {
- request = new BasicClassicHttpRequest("GET", "/");
- request.setHeader("Range", "bytes=0-500");
- request.setHeader("If-Range", "W/\"etag\"");
-
- final ClassicHttpResponse response = testRequestWithWeakETagValidatorIsNotAllowed("If-Range");
- Assertions.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getCode());
- }
-
- @Test
- public void testPUTWithIfMatchWeakETagIsNotAllowed() throws Exception {
- final ClassicHttpRequest put = new BasicClassicHttpRequest("PUT", "/");
- put.setEntity(HttpTestUtils.makeBody(128));
- put.setHeader("Content-Length", "128");
- put.setHeader("If-Match", "W/\"etag\"");
- request = put;
-
- testRequestWithWeakETagValidatorIsNotAllowed("If-Match");
- }
-
- @Test
- public void testPUTWithIfNoneMatchWeakETagIsNotAllowed() throws Exception {
- final ClassicHttpRequest put = new BasicClassicHttpRequest("PUT", "/");
- put.setEntity(HttpTestUtils.makeBody(128));
- put.setHeader("Content-Length", "128");
- put.setHeader("If-None-Match", "W/\"etag\"");
- request = put;
-
- testRequestWithWeakETagValidatorIsNotAllowed("If-None-Match");
- }
-
- @Test
- public void testDELETEWithIfMatchWeakETagIsNotAllowed() throws Exception {
- request = new BasicClassicHttpRequest("DELETE", "/");
- request.setHeader("If-Match", "W/\"etag\"");
-
- testRequestWithWeakETagValidatorIsNotAllowed("If-Match");
- }
-
- @Test
- public void testDELETEWithIfNoneMatchWeakETagIsNotAllowed() throws Exception {
- request = new BasicClassicHttpRequest("DELETE", "/");
- request.setHeader("If-None-Match", "W/\"etag\"");
-
- testRequestWithWeakETagValidatorIsNotAllowed("If-None-Match");
- }
-
- /*
- * "A cache or origin server receiving a conditional request, other than a
- * full-body GET request, MUST use the strong comparison function to
- * evaluate the condition."
- *
- * http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3
- */
- @Test
- public void testSubrangeGETMustUseStrongComparisonForCachedResponse() throws Exception {
- final Instant now = Instant.now();
- final ClassicHttpRequest req1 = new BasicClassicHttpRequest("GET", "/");
- final ClassicHttpResponse resp1 = HttpTestUtils.make200Response();
- resp1.setHeader("Date", DateUtils.formatStandardDate(now));
- resp1.setHeader("Cache-Control", "max-age=3600");
- resp1.setHeader("ETag", "\"etag\"");
-
- // according to weak comparison, this would match. Strong
- // comparison doesn't, because the cache entry's ETag is not
- // marked weak. Therefore, the If-Range must fail and we must
- // either get an error back or the full entity, but we better
- // not get the conditionally-requested Partial Content (206).
- final ClassicHttpRequest req2 = new BasicClassicHttpRequest("GET", "/");
- req2.setHeader("Range", "bytes=0-50");
- req2.setHeader("If-Range", "W/\"etag\"");
-
- Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp1);
-
- execute(req1);
- final ClassicHttpResponse result = execute(req2);
-
- Assertions.assertNotEquals(HttpStatus.SC_PARTIAL_CONTENT, result.getCode());
-
- Mockito.verify(mockExecChain).proceed(Mockito.any(), Mockito.any());
- }
-
/*
* "HTTP/1.1 clients: - If an entity tag has been provided by the origin
* server, MUST use that entity tag in any cache-conditional request (using
diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestRequestProtocolCompliance.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestRequestProtocolCompliance.java
deleted file mode 100644
index fd36b3500..000000000
--- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestRequestProtocolCompliance.java
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * ====================================================================
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
- *
- */
-package org.apache.hc.client5.http.impl.cache;
-
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.util.Collections;
-import java.util.List;
-
-import org.apache.hc.core5.http.HttpHeaders;
-import org.apache.hc.core5.http.HttpRequest;
-import org.apache.hc.core5.http.HttpVersion;
-import org.apache.hc.core5.http.ProtocolVersion;
-import org.apache.hc.core5.http.message.BasicHttpRequest;
-import org.apache.hc.core5.http.support.BasicRequestBuilder;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-public class TestRequestProtocolCompliance {
-
- private RequestProtocolCompliance impl;
-
- @BeforeEach
- public void setUp() {
- impl = new RequestProtocolCompliance(false);
- }
-
- @Test
- public void testRequestWithWeakETagAndRange() throws Exception {
- final HttpRequest req = new BasicHttpRequest("GET", "/");
- req.setHeader("Range", "bytes=0-499");
- req.setHeader("If-Range", "W/\"weak\"");
- assertEquals(1, impl.requestIsFatallyNonCompliant(req, false).size());
- }
-
- @Test
- public void testRequestWithWeekETagForPUTOrDELETEIfMatch() throws Exception {
- final HttpRequest req = new BasicHttpRequest("PUT", "http://example.com/");
- req.setHeader("If-Match", "W/\"weak\"");
- assertEquals(1, impl.requestIsFatallyNonCompliant(req, false).size());
- }
-
- @Test
- public void testRequestWithWeekETagForPUTOrDELETEIfMatchAllowed() throws Exception {
- final HttpRequest req = new BasicHttpRequest("PUT", "http://example.com/");
- req.setHeader("If-Match", "W/\"weak\"");
- impl = new RequestProtocolCompliance(true);
- assertEquals(Collections.emptyList(), impl.requestIsFatallyNonCompliant(req, false));
- }
-
- @Test
- public void doesNotModifyACompliantRequest() throws Exception {
- final HttpRequest req = new BasicHttpRequest("GET", "/");
- final HttpRequest wrapper = BasicRequestBuilder.copy(req).build();
- impl.makeRequestCompliant(wrapper);
- assertTrue(HttpTestUtils.equivalent(req, wrapper));
- }
-
- @Test
- public void upgrades1_0RequestTo1_1() throws Exception {
- final HttpRequest req = new BasicHttpRequest("GET", "/");
- req.setVersion(HttpVersion.HTTP_1_0);
- final HttpRequest wrapper = BasicRequestBuilder.copy(req).build();
- impl.makeRequestCompliant(wrapper);
- assertEquals(HttpVersion.HTTP_1_1, wrapper.getVersion());
- }
-
- @Test
- public void downgrades1_2RequestTo1_1() throws Exception {
- final HttpRequest req = new BasicHttpRequest("GET", "/");
- req.setVersion(new ProtocolVersion("HTTP", 1, 2));
- final HttpRequest wrapper = BasicRequestBuilder.copy(req).build();
- impl.makeRequestCompliant(wrapper);
- assertEquals(HttpVersion.HTTP_1_1, wrapper.getVersion());
- }
-
- @Test
- public void testRequestWithMultipleIfMatchHeaders() {
- final HttpRequest req = new BasicHttpRequest("PUT", "http://example.com/");
- req.addHeader(HttpHeaders.IF_MATCH, "W/\"weak1\"");
- req.addHeader(HttpHeaders.IF_MATCH, "W/\"weak2\"");
- assertEquals(1, impl.requestIsFatallyNonCompliant(req, false).size());
- }
-
- @Test
- public void testRequestWithMultipleIfNoneMatchHeaders() {
- final HttpRequest req = new BasicHttpRequest("PUT", "http://example.com/");
- req.addHeader(HttpHeaders.IF_NONE_MATCH, "W/\"weak1\"");
- req.addHeader(HttpHeaders.IF_NONE_MATCH, "W/\"weak2\"");
- assertEquals(1, impl.requestIsFatallyNonCompliant(req, false).size());
- }
-
- @Test
- public void testRequestWithPreconditionFailed() {
- final HttpRequest req = new BasicHttpRequest("GET", "http://example.com/");
- req.addHeader(HttpHeaders.IF_MATCH, "W/\"weak1\"");
- req.addHeader(HttpHeaders.RANGE, "1");
- req.addHeader(HttpHeaders.IF_RANGE, "W/\"weak2\""); // ETag doesn't match with If-Match ETag
- // This will cause the precondition If-Match to fail because the ETags are different
- final List<RequestProtocolError> requestProtocolErrors = impl.requestIsFatallyNonCompliant(req, false);
- assertTrue(requestProtocolErrors.contains(RequestProtocolError.WEAK_ETAG_AND_RANGE_ERROR));
- }
-
- @Test
- public void testRequestWithValidIfRangeDate() {
- final HttpRequest req = new BasicHttpRequest("GET", "http://example.com/");
- req.addHeader(HttpHeaders.RANGE, "bytes=0-499");
- req.addHeader(HttpHeaders.LAST_MODIFIED, "Wed, 21 Oct 2023 07:28:00 GMT");
- req.addHeader(HttpHeaders.IF_RANGE, "Wed, 21 Oct 2023 07:28:00 GMT");
- assertTrue(impl.requestIsFatallyNonCompliant(req, false).isEmpty());
- }
-
- @Test
- public void testRequestWithInvalidDateFormat() {
- final HttpRequest req = new BasicHttpRequest("GET", "http://example.com/");
- req.addHeader(HttpHeaders.RANGE, "bytes=0-499");
- req.addHeader(HttpHeaders.LAST_MODIFIED, "Wed, 21 Oct 2023 07:28:00 GMT");
- req.addHeader(HttpHeaders.IF_RANGE, "20/10/2023");
- assertTrue(impl.requestIsFatallyNonCompliant(req, false).isEmpty());
- }
-
- @Test
- public void testRequestWithMissingIfRangeDate() {
- final HttpRequest req = new BasicHttpRequest("GET", "http://example.com/");
- req.addHeader(HttpHeaders.RANGE, "bytes=0-499");
- req.addHeader(HttpHeaders.LAST_MODIFIED, "Wed, 21 Oct 2023 07:28:00 GMT");
- assertTrue(impl.requestIsFatallyNonCompliant(req, false).isEmpty());
- }
-
- @Test
- public void testRequestWithWeakETagAndRangeAndDAte() {
- // Setup request with GET method, Range header, If-Range header starting with "W/",
- // and a Last-Modified date that doesn't match the If-Range date
- final HttpRequest req = new BasicHttpRequest("GET", "http://example.com/");
- req.addHeader(HttpHeaders.RANGE, "bytes=0-499");
- req.addHeader(HttpHeaders.LAST_MODIFIED, "Fri, 20 Oct 2023 07:28:00 GMT");
- req.addHeader(HttpHeaders.IF_RANGE, "Wed, 18 Oct 2023 07:28:00 GMT");
-
-
- // Use your implementation to check the request
- final List<RequestProtocolError> errors = impl.requestIsFatallyNonCompliant(req, false);
-
- // Assert that the WEAK_ETAG_AND_RANGE_ERROR is in the list of errors
- assertTrue(errors.contains(RequestProtocolError.WEAK_ETAG_AND_RANGE_ERROR));
- }
-
- @Test
- public void testRequestWithWeekETagForPUTOrDELETEIfMatchWithStart() {
- final HttpRequest req = new BasicHttpRequest("PUT", "http://example.com/");
- req.setHeader(HttpHeaders.IF_MATCH, "*");
- assertEquals(0, impl.requestIsFatallyNonCompliant(req, false).size());
- }
-
- @Test
- public void testRequestOkETagForPUTOrDELETEIfMatch() {
- final HttpRequest req = new BasicHttpRequest("PUT", "http://example.com/");
- req.setHeader(HttpHeaders.IF_MATCH, "1234");
- assertEquals(0, impl.requestIsFatallyNonCompliant(req, false).size());
- }
-
-}