From e48091da3d945b056d9ad9ea46a62b91e142d33f Mon Sep 17 00:00:00 2001 From: Oleg Kalnichevski Date: Tue, 27 Dec 2016 19:48:07 +0000 Subject: [PATCH] Upgraded HttpCore to version 5.0-alpha2; Upgraded to the latest 5.0 APIs git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk@1776187 13f79535-47bb-0310-9956-ffa450edef68 --- .gitignore | 1 + .../client5/http/cache/HeaderConstants.java | 5 +- .../client5/http/cache/HttpCacheContext.java | 2 - .../hc/client5/http/cache/HttpCacheEntry.java | 179 +- .../hc/client5/http/cache/InputLimit.java | 3 - .../cache/AsynchronousValidationRequest.java | 16 +- .../impl/cache/AsynchronousValidator.java | 10 +- .../http/impl/cache/BasicHttpCache.java | 76 +- .../impl/cache/BasicHttpCacheStorage.java | 5 +- .../http/impl/cache/BasicIdGenerator.java | 7 +- .../client5/http/impl/cache/CacheEntity.java | 14 +- .../http/impl/cache/CacheEntryUpdater.java | 12 +- .../http/impl/cache/CacheInvalidator.java | 19 +- .../http/impl/cache/CacheKeyGenerator.java | 104 +- .../http/impl/cache/CacheValidityPolicy.java | 97 +- .../impl/cache/CacheableRequestPolicy.java | 39 +- .../cache/CachedHttpResponseGenerator.java | 35 +- .../CachedResponseSuitabilityChecker.java | 159 +- .../client5/http/impl/cache/CachingExec.java | 286 +- .../http/impl/cache/CachingHttpClients.java | 5 +- .../http/impl/cache/CombinedEntity.java | 9 +- .../impl/cache/ConditionalRequestBuilder.java | 36 +- .../http/impl/cache/DefaultFailureCache.java | 5 +- .../DefaultHttpCacheEntrySerializer.java | 5 +- .../ExponentialBackOffSchedulingStrategy.java | 5 +- .../http/impl/cache/FailureCacheValue.java | 5 +- .../client5/http/impl/cache/FileResource.java | 5 +- .../http/impl/cache/FileResourceFactory.java | 5 +- .../client5/http/impl/cache/HeapResource.java | 5 +- .../http/impl/cache/HeapResourceFactory.java | 5 +- .../hc/client5/http/impl/cache/HttpCache.java | 23 +- .../hc/client5/http/impl/cache/IOUtils.java | 5 +- .../cache/ImmediateSchedulingStrategy.java | 5 +- .../impl/cache/ManagedHttpCacheStorage.java | 5 +- .../impl/cache/OptionsHttp11Response.java | 97 +- .../hc/client5/http/impl/cache/Proxies.java | 56 - .../impl/cache/RequestProtocolCompliance.java | 108 +- .../http/impl/cache/ResourceReference.java | 5 +- .../impl/cache/ResponseCachingPolicy.java | 75 +- .../cache/ResponseProtocolCompliance.java | 45 +- .../http/impl/cache/ResponseProxyHandler.java | 89 - .../impl/cache/SizeLimitedResponseReader.java | 42 +- .../http/cache/TestHttpCacheEntry.java | 99 +- .../http/impl/cache/AbstractProtocolTest.java | 38 +- .../client5/http/impl/cache/DummyBackend.java | 23 +- .../http/impl/cache/HttpTestUtils.java | 132 +- .../hc/client5/http/impl/cache/OKStatus.java | 41 - .../TestAsynchronousValidationRequest.java | 65 +- .../impl/cache/TestAsynchronousValidator.java | 39 +- .../http/impl/cache/TestBasicHttpCache.java | 79 +- .../impl/cache/TestCacheEntryUpdater.java | 7 +- .../http/impl/cache/TestCacheInvalidator.java | 52 +- .../impl/cache/TestCacheKeyGenerator.java | 156 +- .../impl/cache/TestCacheValidityPolicy.java | 9 +- .../TestCachedHttpResponseGenerator.java | 39 +- .../TestCachedResponseSuitabilityChecker.java | 7 +- .../http/impl/cache/TestCachingExec.java | 99 +- .../http/impl/cache/TestCachingExecChain.java | 771 +++--- .../http/impl/cache/TestCombinedEntity.java | 2 +- .../cache/TestConditionalRequestBuilder.java | 135 +- ...ponentialBackingOffSchedulingStrategy.java | 10 +- .../cache/TestHttpCacheEntrySerializers.java | 14 +- .../cache/TestHttpCacheJiraNumber1147.java | 40 +- .../cache/TestProtocolAllowedBehavior.java | 36 +- .../impl/cache/TestProtocolDeviations.java | 89 +- .../cache/TestProtocolRecommendations.java | 657 +++-- .../impl/cache/TestProtocolRequirements.java | 2311 ++++++++--------- .../impl/cache/TestRFC5861Compliance.java | 239 +- .../cache/TestRequestProtocolCompliance.java | 46 +- .../impl/cache/TestResponseCachingPolicy.java | 114 +- .../cache/TestResponseProtocolCompliance.java | 44 +- .../cache/TestSizeLimitedResponseReader.java | 65 +- ...leWhileRevalidationReleasesConnection.java | 19 +- .../http/examples/fluent/FluentExecutor.java | 2 +- .../http/examples/fluent/FluentRequests.java | 2 +- .../fluent/FluentResponseHandling.java | 21 +- .../apache/hc/client5/http/fluent/Async.java | 2 +- .../hc/client5/http/fluent/Content.java | 2 +- .../http/fluent/ContentResponseHandler.java | 5 +- .../hc/client5/http/fluent/Executor.java | 27 +- .../http/fluent/InternalByteArrayEntity.java | 105 - .../http/fluent/InternalFileEntity.java | 85 - .../http/fluent/InternalHttpRequest.java | 142 - .../fluent/InternalInputStreamEntity.java | 98 - .../hc/client5/http/fluent/Request.java | 79 +- .../hc/client5/http/fluent/Response.java | 28 +- .../hc/client5/http/fluent/TestFluent.java | 24 +- httpclient5-osgi/pom.xml | 14 +- .../http/osgi/impl/MimeExportedIT.java | 2 +- .../examples/client/win/ClientWinAuth.java | 6 +- .../impl/win/WindowsNTLMSchemeFactory.java | 5 +- .../http/impl/win/WindowsNegotiateScheme.java | 28 +- .../win/WindowsNegotiateSchemeFactory.java | 5 +- .../impl/win/TestWindowsNegotiateScheme.java | 14 +- .../http/examples/ClientAbortMethod.java | 6 +- .../http/examples/ClientAuthentication.java | 8 +- .../http/examples/ClientChunkEncodedPost.java | 12 +- .../http/examples/ClientConfiguration.java | 32 +- .../examples/ClientConnectionRelease.java | 6 +- .../http/examples/ClientCustomContext.java | 8 +- .../ClientCustomPublicSuffixList.java | 11 +- .../http/examples/ClientCustomSSL.java | 11 +- .../ClientEvictExpiredConnections.java | 8 +- .../http/examples/ClientExecuteProxy.java | 9 +- .../http/examples/ClientExecuteSOCKS.java | 9 +- .../http/examples/ClientFormLogin.java | 8 +- .../ClientMultiThreadedExecution.java | 6 +- .../examples/ClientMultipartFormPost.java | 10 +- .../ClientPreemptiveBasicAuthentication.java | 8 +- .../ClientPreemptiveDigestAuthentication.java | 8 +- .../examples/ClientProxyAuthentication.java | 9 +- .../examples/ClientWithRequestFuture.java | 10 +- .../examples/ClientWithResponseHandler.java | 15 +- .../hc/client5/http/examples/QuickStart.java | 8 +- .../client5/http/ConnectTimeoutException.java | 2 - .../http/ConnectionPoolTimeoutException.java | 3 - .../http/HttpHostConnectException.java | 2 - .../org/apache/hc/client5/http/HttpRoute.java | 5 +- .../apache/hc/client5/http/RouteTracker.java | 2 - .../http/UnsupportedSchemeException.java | 3 - .../hc/client5/http/auth/AuthChallenge.java | 5 +- .../hc/client5/http/auth/AuthExchange.java | 2 - .../hc/client5/http/auth/AuthScope.java | 5 +- .../http/auth/AuthenticationException.java | 2 - .../client5/http/auth/BasicUserPrincipal.java | 5 +- .../auth/InvalidCredentialsException.java | 5 +- .../http/auth/KerberosCredentials.java | 5 +- .../auth/MalformedChallengeException.java | 2 - .../hc/client5/http/auth/NTCredentials.java | 5 +- .../hc/client5/http/auth/NTUserPrincipal.java | 5 +- .../auth/UsernamePasswordCredentials.java | 5 +- .../http/auth/util/ByteArrayBuilder.java | 5 +- .../hc/client5/http/config/AuthSchemes.java | 5 +- .../hc/client5/http/config/CookieSpecs.java | 5 +- .../hc/client5/http/config/RequestConfig.java | 25 +- .../client5/http/cookie/BasicCookieStore.java | 7 +- .../http/cookie/CookieIdentityComparator.java | 5 +- .../hc/client5/http/cookie/CookieOrigin.java | 5 +- .../http/cookie/CookiePathComparator.java | 5 +- .../http/cookie/CookiePriorityComparator.java | 5 +- .../CookieRestrictionViolationException.java | 3 - .../http/cookie/MalformedCookieException.java | 2 - .../http/entity/DecompressingEntity.java | 2 +- .../entity/DeflateDecompressingEntity.java | 2 +- .../hc/client5/http/entity/EntityBuilder.java | 18 +- .../http/entity/GzipCompressingEntity.java | 2 +- .../http/entity/GzipDecompressingEntity.java | 2 +- .../entity/LazyDecompressingInputStream.java | 3 - .../http/entity/UrlEncodedFormEntity.java | 8 +- .../http/entity/mime/AbstractContentBody.java | 2 +- .../entity/mime/AbstractMultipartForm.java | 2 +- .../http/entity/mime/ByteArrayBody.java | 2 +- .../hc/client5/http/entity/mime/FileBody.java | 2 +- .../http/entity/mime/FormBodyPartBuilder.java | 2 +- .../http/entity/mime/InputStreamBody.java | 2 +- .../entity/mime/MultipartEntityBuilder.java | 2 +- .../http/entity/mime/MultipartFormEntity.java | 12 +- .../client5/http/entity/mime/StringBody.java | 2 +- .../http/impl/BasicResponseHandler.java | 14 +- .../DefaultConnectionKeepAliveStrategy.java | 10 +- .../http/impl/DefaultSchemePortResolver.java | 5 +- .../http/impl/auth/BasicAuthCache.java | 5 +- .../client5/http/impl/auth/BasicScheme.java | 9 +- .../http/impl/auth/BasicSchemeFactory.java | 5 +- .../client5/http/impl/auth/DigestScheme.java | 22 +- .../http/impl/auth/DigestSchemeFactory.java | 5 +- .../client5/http/impl/auth/GGSSchemeBase.java | 2 - .../http/impl/auth/HttpAuthenticator.java | 2 +- .../http/impl/auth/KerberosScheme.java | 2 - .../http/impl/auth/KerberosSchemeFactory.java | 5 +- .../http/impl/auth/NTLMEngineException.java | 2 - .../http/impl/auth/NTLMEngineImpl.java | 5 +- .../hc/client5/http/impl/auth/NTLMScheme.java | 2 - .../http/impl/auth/NTLMSchemeFactory.java | 5 +- .../client5/http/impl/auth/SPNegoScheme.java | 2 - .../http/impl/auth/SPNegoSchemeFactory.java | 5 +- .../SystemDefaultCredentialsProvider.java | 48 +- .../UnsupportedDigestAlgorithmException.java | 3 - .../AbstractCookieAttributeHandler.java | 5 +- .../http/impl/cookie/AbstractCookieSpec.java | 5 +- .../http/impl/cookie/BasicClientCookie.java | 2 - .../http/impl/cookie/BasicDomainHandler.java | 7 +- .../http/impl/cookie/BasicExpiresHandler.java | 5 +- .../http/impl/cookie/BasicMaxAgeHandler.java | 5 +- .../http/impl/cookie/BasicPathHandler.java | 5 +- .../http/impl/cookie/BasicSecureHandler.java | 5 +- .../http/impl/cookie/CookieSpecBase.java | 5 +- .../client5/http/impl/cookie/IgnoreSpec.java | 5 +- .../http/impl/cookie/IgnoreSpecProvider.java | 5 +- .../http/impl/cookie/LaxExpiresHandler.java | 5 +- .../http/impl/cookie/LaxMaxAgeHandler.java | 5 +- .../impl/cookie/PublicSuffixDomainFilter.java | 5 +- .../http/impl/cookie/RFC6265CookieSpec.java | 5 +- .../cookie/RFC6265CookieSpecProvider.java | 5 +- .../http/impl/cookie/RFC6265LaxSpec.java | 5 +- .../http/impl/cookie/RFC6265StrictSpec.java | 5 +- .../io/BasicHttpClientConnectionManager.java | 25 +- .../apache/hc/client5/http/impl/io/CPool.java | 83 - .../hc/client5/http/impl/io/CPoolEntry.java | 101 - .../hc/client5/http/impl/io/CPoolProxy.java | 97 +- .../impl/io/ConnectionShutdownException.java | 3 - .../DefaultHttpClientConnectionOperator.java | 5 +- .../io/DefaultHttpResponseParserFactory.java | 25 +- .../DefaultManagedHttpClientConnection.java | 87 +- .../impl/io/LenientHttpResponseParser.java | 29 +- .../http/impl/io/LoggingInputStream.java | 3 - .../LoggingManagedHttpClientConnection.java | 48 +- .../http/impl/io/LoggingOutputStream.java | 3 - .../io/LoggingSocketHolder.java} | 42 +- .../ManagedHttpClientConnectionFactory.java | 43 +- .../PoolingHttpClientConnectionManager.java | 181 +- .../apache/hc/client5/http/impl/io/Wire.java | 5 +- .../DefaultAuthenticationStrategy.java | 5 +- .../protocol/DefaultRedirectStrategy.java | 30 +- .../protocol/DefaultUserTokenHandler.java | 5 +- .../http/impl/routing/BasicRouteDirector.java | 5 +- .../routing/DefaultProxyRoutePlanner.java | 5 +- .../impl/routing/DefaultRoutePlanner.java | 5 +- .../routing/SystemDefaultRoutePlanner.java | 5 +- .../impl/sync/AbstractResponseHandler.java | 26 +- .../http/impl/sync/BackoffStrategyExec.java | 21 +- .../impl/sync/BasicCredentialsProvider.java | 5 +- .../http/impl/sync/ClientExecChain.java | 13 +- .../http/impl/sync/CloseableHttpClient.java | 50 +- ...eProxy.java => CloseableHttpResponse.java} | 216 +- .../http/impl/sync/ConnectionHolder.java | 5 +- .../impl/sync/DefaultBackoffStrategy.java | 2 +- .../sync/DefaultHttpRequestRetryHandler.java | 7 +- ...efaultServiceUnavailableRetryStrategy.java | 8 +- .../sync/FutureRequestExecutionService.java | 7 +- .../http/impl/sync/HttpClientBuilder.java | 12 +- .../client5/http/impl/sync/HttpClients.java | 2 - .../http/impl/sync/HttpRequestFutureTask.java | 2 +- .../impl/sync/HttpRequestTaskCallable.java | 4 +- .../http/impl/sync/IdleConnectionEvictor.java | 4 +- .../http/impl/sync/InternalHttpClient.java | 26 +- .../http/impl/sync/MainClientExec.java | 67 +- .../http/impl/sync/MinimalClientExec.java | 92 +- .../http/impl/sync/MinimalHttpClient.java | 29 +- .../http/impl/sync/NoopUserTokenHandler.java | 5 +- .../client5/http/impl/sync/ProtocolExec.java | 93 +- .../client5/http/impl/sync/ProxyClient.java | 31 +- .../client5/http/impl/sync/RedirectExec.java | 53 +- .../impl/sync/RequestAbortedException.java | 3 - .../http/impl/sync/RequestEntityProxy.java | 19 +- .../http/impl/sync/ResponseEntityProxy.java | 12 +- .../hc/client5/http/impl/sync/RetryExec.java | 18 +- .../sync/ServiceUnavailableRetryExec.java | 18 +- .../impl/sync/TunnelRefusedException.java | 10 +- .../http/io/ConnectionReleaseTrigger.java | 5 +- .../client5/http/io/EofSensorInputStream.java | 295 --- .../hc/client5/http/io/EofSensorWatcher.java | 96 - .../http/io/HttpClientConnectionManager.java | 8 +- .../http/methods/CloseableHttpResponse.java | 40 - .../hc/client5/http/methods/HttpDelete.java | 21 +- .../hc/client5/http/methods/HttpGet.java | 21 +- .../hc/client5/http/methods/HttpHead.java | 21 +- .../hc/client5/http/methods/HttpOptions.java | 26 +- .../hc/client5/http/methods/HttpPatch.java | 21 +- .../hc/client5/http/methods/HttpPost.java | 21 +- .../hc/client5/http/methods/HttpPut.java | 20 +- .../client5/http/methods/HttpRequestBase.java | 129 - .../http/methods/HttpRequestWrapper.java | 163 -- .../hc/client5/http/methods/HttpTrace.java | 21 +- .../client5/http/methods/HttpUriRequest.java | 34 +- ...reRequest.java => HttpUriRequestBase.java} | 38 +- .../client5/http/methods/RequestBuilder.java | 54 +- .../http/methods/RoutedHttpRequest.java | 192 ++ .../protocol/CircularRedirectException.java | 3 - .../protocol/ClientProtocolException.java | 3 - .../http/protocol/HttpClientContext.java | 7 +- .../http/protocol/HttpResponseException.java | 3 - .../NonRepeatableRequestException.java | 2 - .../http/protocol/RedirectException.java | 2 - .../http/protocol/RedirectLocations.java | 3 - .../http/protocol/RedirectStrategy.java | 3 +- .../http/protocol/RequestAcceptEncoding.java | 12 +- .../http/protocol/RequestAddCookies.java | 49 +- .../http/protocol/RequestAuthCache.java | 28 +- .../protocol/RequestClientConnControl.java | 10 +- .../http/protocol/RequestDefaultHeaders.java | 10 +- .../http/protocol/RequestExpectContinue.java | 14 +- .../protocol/ResponseContentEncoding.java | 20 +- .../http/protocol/ResponseProcessCookies.java | 8 +- .../hc/client5/http/psl/PublicSuffixList.java | 5 +- .../http/psl/PublicSuffixListParser.java | 5 +- .../client5/http/psl/PublicSuffixMatcher.java | 5 +- .../http/psl/PublicSuffixMatcherLoader.java | 5 +- .../socket/PlainConnectionSocketFactory.java | 5 +- .../http/ssl/DefaultHostnameVerifier.java | 7 +- .../http/ssl/NoopHostnameVerifier.java | 5 +- .../http/ssl/SSLConnectionSocketFactory.java | 5 +- .../hc/client5/http/sync/HttpClient.java | 40 +- .../hc/client5/http/utils/DateUtils.java | 5 +- .../client5/http/utils/InetAddressUtils.java | 124 - .../hc/client5/http/utils/URIBuilder.java | 493 ---- .../hc/client5/http/utils/URIUtils.java | 67 +- .../client5/http/utils/URLEncodedUtils.java | 537 ---- .../http/config/TestRequestConfig.java | 1 - .../http/entity/TestDecompressingEntity.java | 6 +- .../hc/client5/http/entity/TestDeflate.java | 4 +- .../http/entity/TestEntityBuilder.java | 4 +- .../hc/client5/http/entity/TestGZip.java | 8 +- .../http/entity/mime/FormBodyPartTest.java | 4 +- .../entity/mime/TestFormBodyPartBuilder.java | 2 +- .../entity/mime/TestMultipartContentBody.java | 2 +- .../mime/TestMultipartEntityBuilder.java | 2 +- .../http/entity/mime/TestMultipartForm.java | 2 +- .../mime/TestMultipartFormHttpEntity.java | 2 +- .../impl/TestAbstractResponseHandler.java | 20 +- .../http/impl/TestBasicResponseHandler.java | 18 +- .../TestDefaultConnKeepAliveStrategy.java | 14 +- .../http/impl/auth/TestDigestScheme.java | 12 +- .../http/impl/auth/TestHttpAuthenticator.java | 35 +- .../http/impl/auth/TestRequestAuthCache.java | 17 +- .../TestSystemDefaultCredentialsProvider.java | 12 +- .../impl/integration/TestAbortHandling.java | 37 +- .../TestBasicConnectionManager.java | 6 +- .../integration/TestClientAuthentication.java | 152 +- .../TestClientAuthenticationFakeNTLM.java | 55 +- .../TestClientAuthenticationFallBack.java | 35 +- .../TestClientReauthentication.java | 37 +- .../TestClientRequestExecution.java | 51 +- .../TestConnectionAutoRelease.java | 20 +- .../integration/TestConnectionManagement.java | 317 +-- .../impl/integration/TestConnectionReuse.java | 48 +- .../impl/integration/TestContentCodings.java | 146 +- .../integration/TestCookieVirtualHost.java | 24 +- .../TestIdleConnectionEviction.java | 8 +- .../TestMalformedServerResponse.java | 30 +- .../TestMinimalClientRequestExecution.java | 17 +- .../http/impl/integration/TestRedirects.java | 219 +- .../impl/integration/TestSPNegoScheme.java | 22 +- .../TestStatefulConnManagement.java | 22 +- .../http/impl/io/SessionInputBufferMock.java | 104 - .../TestBasicHttpClientConnectionManager.java | 8 +- .../io/TestDefaultHttpResponseParser.java | 43 +- ...estPoolingHttpClientConnectionManager.java | 58 +- .../protocol/TestDefaultRedirectStrategy.java | 85 +- .../routing/TestDefaultProxyRoutePlanner.java | 5 +- .../impl/routing/TestDefaultRoutePlanner.java | 9 +- .../TestSystemDefaultRoutePlanner.java | 7 +- .../http/impl/sync/MockConnPoolControl.java | 9 + .../impl/sync/TestCloseableHttpClient.java | 32 +- .../impl/sync/TestDefaultBackoffStrategy.java | 7 +- ...efaultServiceUnavailableRetryStrategy.java | 13 +- .../TestFutureRequestExecutionService.java | 19 +- .../impl/sync/TestIdleConnectionEvictor.java | 8 +- .../impl/sync/TestInternalHttpClient.java | 35 +- .../http/impl/sync/TestMainClientExec.java | 182 +- .../http/impl/sync/TestMinimalClientExec.java | 93 +- .../impl/sync/TestNullBackoffStrategy.java | 4 +- .../http/impl/sync/TestProtocolExec.java | 154 +- .../http/impl/sync/TestRedirectExec.java | 100 +- .../impl/sync/TestResponseEntityWrapper.java | 2 +- .../client5/http/impl/sync/TestRetryExec.java | 25 +- .../sync/TestServiceUnavailableRetryExec.java | 21 +- .../http/io/TestEofSensorInputStream.java | 228 -- .../client5/http/localserver/EchoHandler.java | 16 +- .../http/localserver/LocalServerTestBase.java | 7 +- .../http/localserver/RandomHandler.java | 29 +- .../http/localserver/RequestBasicAuth.java | 2 + .../ResponseBasicUnauthorized.java | 4 +- .../client5/http/methods/TestHttpOptions.java | 8 +- .../http/methods/TestHttpRequestBase.java | 10 +- .../http/methods/TestRequestBuilder.java | 39 +- .../protocol/TestRequestAcceptEncoding.java | 4 +- .../http/protocol/TestRequestAddCookies.java | 63 +- .../TestRequestClientConnControl.java | 14 +- .../protocol/TestRequestDefaultHeaders.java | 6 +- .../protocol/TestRequestExpectContinue.java | 29 +- .../protocol/TestResponseContentEncoding.java | 45 +- .../protocol/TestResponseProcessCookies.java | 23 +- .../http/ssl/TestSSLSocketFactory.java | 15 +- .../http/utils/TestInetAddressUtils.java | 100 - .../http/utils/TestRequestBuilder.java | 2 +- .../hc/client5/http/utils/TestURIBuilder.java | 295 --- .../hc/client5/http/utils/TestURIUtils.java | 30 +- .../http/utils/TestURLEncodedUtils.java | 412 --- .../test/resources/log4j2-debug.xml.template | 32 + pom.xml | 4 +- 381 files changed, 5952 insertions(+), 10846 deletions(-) delete mode 100644 httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/Proxies.java delete mode 100644 httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ResponseProxyHandler.java delete mode 100644 httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/OKStatus.java delete mode 100644 httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/InternalByteArrayEntity.java delete mode 100644 httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/InternalFileEntity.java delete mode 100644 httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/InternalHttpRequest.java delete mode 100644 httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/InternalInputStreamEntity.java delete mode 100644 httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/CPool.java delete mode 100644 httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/CPoolEntry.java rename httpclient5/src/main/java/org/apache/hc/client5/http/{sync/ResponseHandler.java => impl/io/LoggingSocketHolder.java} (62%) rename httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/{HttpResponseProxy.java => CloseableHttpResponse.java} (54%) delete mode 100644 httpclient5/src/main/java/org/apache/hc/client5/http/io/EofSensorInputStream.java delete mode 100644 httpclient5/src/main/java/org/apache/hc/client5/http/io/EofSensorWatcher.java delete mode 100644 httpclient5/src/main/java/org/apache/hc/client5/http/methods/CloseableHttpResponse.java delete mode 100644 httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpRequestBase.java delete mode 100644 httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpRequestWrapper.java rename httpclient5/src/main/java/org/apache/hc/client5/http/methods/{AbstractExecutionAwareRequest.java => HttpUriRequestBase.java} (75%) create mode 100644 httpclient5/src/main/java/org/apache/hc/client5/http/methods/RoutedHttpRequest.java delete mode 100644 httpclient5/src/main/java/org/apache/hc/client5/http/utils/InetAddressUtils.java delete mode 100644 httpclient5/src/main/java/org/apache/hc/client5/http/utils/URIBuilder.java delete mode 100644 httpclient5/src/main/java/org/apache/hc/client5/http/utils/URLEncodedUtils.java delete mode 100644 httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/SessionInputBufferMock.java delete mode 100644 httpclient5/src/test/java/org/apache/hc/client5/http/io/TestEofSensorInputStream.java delete mode 100644 httpclient5/src/test/java/org/apache/hc/client5/http/utils/TestInetAddressUtils.java delete mode 100644 httpclient5/src/test/java/org/apache/hc/client5/http/utils/TestURIBuilder.java delete mode 100644 httpclient5/src/test/java/org/apache/hc/client5/http/utils/TestURLEncodedUtils.java create mode 100644 httpclient5/src/test/resources/log4j2-debug.xml.template diff --git a/.gitignore b/.gitignore index 81c343370..bf69348a7 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ bin target .idea *.iml +/httpclient5/src/test/resources/log4j2-debug.xml diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/cache/HeaderConstants.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/cache/HeaderConstants.java index def4d37f7..1dbaaf33f 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/cache/HeaderConstants.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/cache/HeaderConstants.java @@ -26,13 +26,14 @@ */ package org.apache.hc.client5.http.cache; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; /** * Records static constants for various HTTP header names. * @since 4.1 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class HeaderConstants { public static final String GET_METHOD = "GET"; diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/cache/HttpCacheContext.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/cache/HttpCacheContext.java index 9ee27f6c0..f1e4e8f32 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/cache/HttpCacheContext.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/cache/HttpCacheContext.java @@ -27,14 +27,12 @@ package org.apache.hc.client5.http.cache; import org.apache.hc.client5.http.protocol.HttpClientContext; -import org.apache.hc.core5.annotation.NotThreadSafe; import org.apache.hc.core5.http.protocol.BasicHttpContext; import org.apache.hc.core5.http.protocol.HttpContext; /** * @since 4.3 */ -@NotThreadSafe public class HttpCacheContext extends HttpClientContext { /** diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/cache/HttpCacheEntry.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/cache/HttpCacheEntry.java index 243f26bef..62cf5083a 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/cache/HttpCacheEntry.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/cache/HttpCacheEntry.java @@ -34,11 +34,13 @@ import java.util.Iterator; import java.util.Map; import org.apache.hc.client5.http.utils.DateUtils; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpHeaders; -import org.apache.hc.core5.http.ProtocolVersion; -import org.apache.hc.core5.http.StatusLine; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.MessageHeaders; +import org.apache.hc.core5.http.ProtocolException; import org.apache.hc.core5.http.message.HeaderGroup; import org.apache.hc.core5.util.Args; @@ -51,15 +53,15 @@ import org.apache.hc.core5.util.Args; * * @since 4.1 */ -@Immutable -public class HttpCacheEntry implements Serializable { +@Contract(threading = ThreadingBehavior.IMMUTABLE) +public class HttpCacheEntry implements MessageHeaders, Serializable { private static final long serialVersionUID = -6300496422359477413L; private static final String REQUEST_METHOD_HEADER_NAME = "Hc-Request-Method"; private final Date requestDate; private final Date responseDate; - private final StatusLine statusLine; + private final int status; private final HeaderGroup responseHeaders; private final Resource resource; private final Map variantMap; @@ -73,8 +75,8 @@ public class HttpCacheEntry implements Serializable { * @param responseDate * Date/time that the response came back (Used for age * calculations) - * @param statusLine - * HTTP status line from origin response + * @param status + * HTTP status from origin response * @param responseHeaders * Header[] from original HTTP Response * @param resource representing origin response body @@ -82,62 +84,29 @@ public class HttpCacheEntry implements Serializable { * of this parent entry; this maps a "variant key" (derived * from the varying request headers) to a "cache key" (where * in the cache storage the particular variant is located) - * @param requestMethod HTTP method used when the request was made */ public HttpCacheEntry( final Date requestDate, final Date responseDate, - final StatusLine statusLine, + final int status, final Header[] responseHeaders, final Resource resource, - final Map variantMap, - final String requestMethod) { + final Map variantMap) { super(); Args.notNull(requestDate, "Request date"); Args.notNull(responseDate, "Response date"); - Args.notNull(statusLine, "Status line"); + Args.check(status >= HttpStatus.SC_SUCCESS, "Status code"); Args.notNull(responseHeaders, "Response headers"); this.requestDate = requestDate; this.responseDate = responseDate; - this.statusLine = statusLine; + this.status = status; this.responseHeaders = new HeaderGroup(); this.responseHeaders.setHeaders(responseHeaders); this.resource = resource; - this.variantMap = variantMap != null - ? new HashMap<>(variantMap) - : null; + this.variantMap = variantMap != null ? new HashMap<>(variantMap) : null; this.date = parseDate(); } - /** - * Create a new {@link HttpCacheEntry} with variants. - * @param requestDate - * Date/time when the request was made (Used for age - * calculations) - * @param responseDate - * Date/time that the response came back (Used for age - * calculations) - * @param statusLine - * HTTP status line from origin response - * @param responseHeaders - * Header[] from original HTTP Response - * @param resource representing origin response body - * @param variantMap describing cache entries that are variants - * of this parent entry; this maps a "variant key" (derived - * from the varying request headers) to a "cache key" (where - * in the cache storage the particular variant is located) - */ - public HttpCacheEntry( - final Date requestDate, - final Date responseDate, - final StatusLine statusLine, - final Header[] responseHeaders, - final Resource resource, - final Map variantMap) { - this(requestDate, responseDate, statusLine, responseHeaders, resource, - variantMap, null); - } - /** * Create a new {@link HttpCacheEntry}. * @@ -147,38 +116,15 @@ public class HttpCacheEntry implements Serializable { * @param responseDate * Date/time that the response came back (Used for age * calculations) - * @param statusLine - * HTTP status line from origin response + * @param status + * HTTP status from origin response * @param responseHeaders * Header[] from original HTTP Response * @param resource representing origin response body */ - public HttpCacheEntry(final Date requestDate, final Date responseDate, final StatusLine statusLine, + public HttpCacheEntry(final Date requestDate, final Date responseDate, final int status, final Header[] responseHeaders, final Resource resource) { - this(requestDate, responseDate, statusLine, responseHeaders, resource, - new HashMap()); - } - - /** - * Create a new {@link HttpCacheEntry}. - * - * @param requestDate - * Date/time when the request was made (Used for age - * calculations) - * @param responseDate - * Date/time that the response came back (Used for age - * calculations) - * @param statusLine - * HTTP status line from origin response - * @param responseHeaders - * Header[] from original HTTP Response - * @param resource representing origin response body - * @param requestMethod HTTP method used when the request was made - */ - public HttpCacheEntry(final Date requestDate, final Date responseDate, final StatusLine statusLine, - final Header[] responseHeaders, final Resource resource, final String requestMethod) { - this(requestDate, responseDate, statusLine, responseHeaders, resource, - new HashMap(),requestMethod); + this(requestDate, responseDate, status, responseHeaders, resource, new HashMap()); } /** @@ -194,35 +140,10 @@ public class HttpCacheEntry implements Serializable { } /** - * Returns the {@link StatusLine} from the origin - * {@link org.apache.hc.core5.http.HttpResponse}. + * Returns the status from the origin {@link org.apache.hc.core5.http.HttpResponse}. */ - public StatusLine getStatusLine() { - return this.statusLine; - } - - /** - * Returns the {@link ProtocolVersion} from the origin - * {@link org.apache.hc.core5.http.HttpResponse}. - */ - public ProtocolVersion getProtocolVersion() { - return this.statusLine.getProtocolVersion(); - } - - /** - * Gets the reason phrase from the origin - * {@link org.apache.hc.core5.http.HttpResponse}, for example, "Not Modified". - */ - public String getReasonPhrase() { - return this.statusLine.getReasonPhrase(); - } - - /** - * Returns the HTTP response code from the origin - * {@link org.apache.hc.core5.http.HttpResponse}. - */ - public int getStatusCode() { - return this.statusLine.getStatusCode(); + public int getStatus() { + return this.status; } /** @@ -245,6 +166,7 @@ public class HttpCacheEntry implements Serializable { /** * Returns all the headers that were on the origin response. */ + @Override public Header[] getAllHeaders() { final HeaderGroup filteredHeaders = new HeaderGroup(); for (final Iterator
iterator = responseHeaders.headerIterator(); iterator.hasNext();) { @@ -260,6 +182,7 @@ public class HttpCacheEntry implements Serializable { * Returns the first header from the origin response with the given * name. */ + @Override public Header getFirstHeader(final String name) { if (REQUEST_METHOD_HEADER_NAME.equalsIgnoreCase(name)) { return null; @@ -267,10 +190,19 @@ public class HttpCacheEntry implements Serializable { return responseHeaders.getFirstHeader(name); } + /** + * @since 5.0 + */ + @Override + public Header getLastHeader(final String name) { + return responseHeaders.getLastHeader(name); + } + /** * Gets all the headers with the given name that were on the origin * response. */ + @Override public Header[] getHeaders(final String name) { if (REQUEST_METHOD_HEADER_NAME.equalsIgnoreCase(name)) { return new Header[0]; @@ -278,6 +210,46 @@ public class HttpCacheEntry implements Serializable { return responseHeaders.getHeaders(name); } + /** + * @since 5.0 + */ + @Override + public boolean containsHeader(final String name) { + return responseHeaders.containsHeader(name); + } + + /** + * @since 5.0 + */ + @Override + public int containsHeaders(final String name) { + return responseHeaders.containsHeaders(name); + } + + /** + * @since 5.0 + */ + @Override + public Header getSingleHeader(final String name) throws ProtocolException { + return responseHeaders.getSingleHeader(name); + } + + /** + * @since 5.0 + */ + @Override + public Iterator
headerIterator() { + return responseHeaders.headerIterator(); + } + + /** + * @since 5.0 + */ + @Override + public Iterator
headerIterator(final String name) { + return responseHeaders.headerIterator(name); + } + /** * Gets the Date value of the "Date" header or null if the header is missing or cannot be * parsed. @@ -325,8 +297,7 @@ public class HttpCacheEntry implements Serializable { * @since 4.4 */ public String getRequestMethod() { - final Header requestMethodHeader = responseHeaders - .getFirstHeader(REQUEST_METHOD_HEADER_NAME); + final Header requestMethodHeader = responseHeaders.getFirstHeader(REQUEST_METHOD_HEADER_NAME); if (requestMethodHeader != null) { return requestMethodHeader.getValue(); } @@ -340,7 +311,7 @@ public class HttpCacheEntry implements Serializable { @Override public String toString() { return "[request date=" + this.requestDate + "; response date=" + this.responseDate - + "; statusLine=" + this.statusLine + "]"; + + "; status=" + this.status + "]"; } } diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/cache/InputLimit.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/cache/InputLimit.java index 563c7ecc1..9f1e63e43 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/cache/InputLimit.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/cache/InputLimit.java @@ -26,15 +26,12 @@ */ package org.apache.hc.client5.http.cache; -import org.apache.hc.core5.annotation.NotThreadSafe; - /** * Used to limiting the size of an incoming response body of * unknown size that is optimistically being read in anticipation * of caching it. * @since 4.1 */ -@NotThreadSafe // reached public class InputLimit { private final long value; diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/AsynchronousValidationRequest.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/AsynchronousValidationRequest.java index ed9c32c5b..595f51d37 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/AsynchronousValidationRequest.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/AsynchronousValidationRequest.java @@ -30,13 +30,12 @@ import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.hc.client5.http.HttpRoute; import org.apache.hc.client5.http.cache.HeaderConstants; import org.apache.hc.client5.http.cache.HttpCacheEntry; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpExecutionAware; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.HttpClientContext; +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.HttpResponse; @@ -48,8 +47,7 @@ import org.apache.hc.core5.http.HttpResponse; public class AsynchronousValidationRequest implements Runnable { private final AsynchronousValidator parent; private final CachingExec cachingExec; - private final HttpRoute route; - private final HttpRequestWrapper request; + private final RoutedHttpRequest request; private final HttpClientContext context; private final HttpExecutionAware execAware; private final HttpCacheEntry cacheEntry; @@ -70,8 +68,7 @@ public class AsynchronousValidationRequest implements Runnable { AsynchronousValidationRequest( final AsynchronousValidator parent, final CachingExec cachingExec, - final HttpRoute route, - final HttpRequestWrapper request, + final RoutedHttpRequest request, final HttpClientContext context, final HttpExecutionAware execAware, final HttpCacheEntry cacheEntry, @@ -79,7 +76,6 @@ public class AsynchronousValidationRequest implements Runnable { final int consecutiveFailedAttempts) { this.parent = parent; this.cachingExec = cachingExec; - this.route = route; this.request = request; this.context = context; this.execAware = execAware; @@ -110,8 +106,8 @@ public class AsynchronousValidationRequest implements Runnable { */ private boolean revalidateCacheEntry() { try { - try (CloseableHttpResponse httpResponse = cachingExec.revalidateCacheEntry(route, request, context, execAware, cacheEntry)) { - final int statusCode = httpResponse.getStatusLine().getStatusCode(); + try (ClassicHttpResponse httpResponse = cachingExec.revalidateCacheEntry(request, context, execAware, cacheEntry)) { + final int statusCode = httpResponse.getCode(); return isNotServerError(statusCode) && isNotStale(httpResponse); } } catch (final IOException ioe) { diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/AsynchronousValidator.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/AsynchronousValidator.java index f03b4558d..e187d2c0a 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/AsynchronousValidator.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/AsynchronousValidator.java @@ -35,10 +35,9 @@ import java.util.concurrent.RejectedExecutionException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.hc.client5.http.HttpRoute; import org.apache.hc.client5.http.cache.HttpCacheEntry; import org.apache.hc.client5.http.methods.HttpExecutionAware; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.HttpClientContext; /** @@ -91,19 +90,18 @@ class AsynchronousValidator implements Closeable { */ public synchronized void revalidateCacheEntry( final CachingExec cachingExec, - final HttpRoute route, - final HttpRequestWrapper request, + final RoutedHttpRequest request, final HttpClientContext context, final HttpExecutionAware execAware, final HttpCacheEntry entry) { // getVariantURI will fall back on getURI if no variants exist - final String uri = cacheKeyGenerator.getVariantURI(context.getTargetHost(), request, entry); + final String uri = cacheKeyGenerator.generateVariantURI(request.getTargetHost(), request, entry); if (!queued.contains(uri)) { final int consecutiveFailedAttempts = failureCache.getErrorCount(uri); final AsynchronousValidationRequest revalidationRequest = new AsynchronousValidationRequest( - this, cachingExec, route, request, context, execAware, entry, uri, consecutiveFailedAttempts); + this, cachingExec, request, context, execAware, entry, uri, consecutiveFailedAttempts); try { schedulingStrategy.schedule(revalidationRequest); diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/BasicHttpCache.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/BasicHttpCache.java index 984425fac..00f0c83e8 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/BasicHttpCache.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/BasicHttpCache.java @@ -44,17 +44,15 @@ import org.apache.hc.client5.http.cache.HttpCacheUpdateCallback; import org.apache.hc.client5.http.cache.HttpCacheUpdateException; import org.apache.hc.client5.http.cache.Resource; import org.apache.hc.client5.http.cache.ResourceFactory; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.Header; 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.HttpResponse; import org.apache.hc.core5.http.HttpStatus; -import org.apache.hc.core5.http.HttpVersion; -import org.apache.hc.core5.http.entity.ByteArrayEntity; -import org.apache.hc.core5.http.message.BasicHttpResponse; +import org.apache.hc.core5.http.io.entity.ByteArrayEntity; +import org.apache.hc.core5.http.message.BasicClassicHttpResponse; class BasicHttpCache implements HttpCache { private static final Set safeRequestMethods = new HashSet<>( @@ -114,15 +112,15 @@ class BasicHttpCache implements HttpCache { @Override public void flushCacheEntriesFor(final HttpHost host, final HttpRequest request) throws IOException { - if (!safeRequestMethods.contains(request.getRequestLine().getMethod())) { - final String uri = uriExtractor.getURI(host, request); + if (!safeRequestMethods.contains(request.getMethod())) { + final String uri = uriExtractor.generateKey(host, request); storage.removeEntry(uri); } } @Override public void flushInvalidatedCacheEntriesFor(final HttpHost host, final HttpRequest request, final HttpResponse response) { - if (!safeRequestMethods.contains(request.getRequestLine().getMethod())) { + if (!safeRequestMethods.contains(request.getMethod())) { cacheInvalidator.flushInvalidatedCacheEntries(host, request, response); } } @@ -138,7 +136,7 @@ class BasicHttpCache implements HttpCache { void storeNonVariantEntry( final HttpHost target, final HttpRequest req, final HttpCacheEntry entry) throws IOException { - final String uri = uriExtractor.getURI(target, req); + final String uri = uriExtractor.generateKey(target, req); storage.putEntry(uri, entry); } @@ -146,8 +144,8 @@ class BasicHttpCache implements HttpCache { final HttpHost target, final HttpRequest req, final HttpCacheEntry entry) throws IOException { - final String parentURI = uriExtractor.getURI(target, req); - final String variantURI = uriExtractor.getVariantURI(target, req, entry); + final String parentURI = uriExtractor.generateKey(target, req); + final String variantURI = uriExtractor.generateVariantURI(target, req, entry); storage.putEntry(variantURI, entry); final HttpCacheUpdateCallback callback = new HttpCacheUpdateCallback() { @@ -155,8 +153,8 @@ class BasicHttpCache implements HttpCache { @Override public HttpCacheEntry update(final HttpCacheEntry existing) throws IOException { return doGetUpdatedParentEntry( - req.getRequestLine().getUri(), existing, entry, - uriExtractor.getVariantKey(req, entry), + req.getRequestUri(), existing, entry, + uriExtractor.generateVariantKey(req, entry), variantURI); } @@ -172,16 +170,16 @@ class BasicHttpCache implements HttpCache { @Override public void reuseVariantEntryFor(final HttpHost target, final HttpRequest req, final Variant variant) throws IOException { - final String parentCacheKey = uriExtractor.getURI(target, req); + final String parentCacheKey = uriExtractor.generateKey(target, req); final HttpCacheEntry entry = variant.getEntry(); - final String variantKey = uriExtractor.getVariantKey(req, entry); + final String variantKey = uriExtractor.generateVariantKey(req, entry); final String variantCacheKey = variant.getCacheKey(); final HttpCacheUpdateCallback callback = new HttpCacheUpdateCallback() { @Override public HttpCacheEntry update(final HttpCacheEntry existing) throws IOException { - return doGetUpdatedParentEntry(req.getRequestLine().getUri(), + return doGetUpdatedParentEntry(req.getRequestUri(), existing, entry, variantKey, variantCacheKey); } }; @@ -194,7 +192,7 @@ class BasicHttpCache implements HttpCache { } boolean isIncompleteResponse(final HttpResponse resp, final Resource resource) { - final int status = resp.getStatusLine().getStatusCode(); + final int status = resp.getCode(); if (status != HttpStatus.SC_OK && status != HttpStatus.SC_PARTIAL_CONTENT) { return false; @@ -215,11 +213,10 @@ class BasicHttpCache implements HttpCache { return (resource.length() < contentLength); } - CloseableHttpResponse generateIncompleteResponseError( + ClassicHttpResponse generateIncompleteResponseError( final HttpResponse response, final Resource resource) { final Integer contentLength = Integer.valueOf(response.getFirstHeader(HttpHeaders.CONTENT_LENGTH).getValue()); - final HttpResponse error = - new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_BAD_GATEWAY, "Bad Gateway"); + final ClassicHttpResponse error = new BasicClassicHttpResponse(HttpStatus.SC_BAD_GATEWAY, "Bad Gateway"); error.setHeader("Content-Type","text/plain;charset=UTF-8"); final String msg = String.format("Received incomplete response " + "with Content-Length %d but actual body length %d", @@ -227,7 +224,7 @@ class BasicHttpCache implements HttpCache { final byte[] msgBytes = msg.getBytes(); error.setHeader("Content-Length", Integer.toString(msgBytes.length)); error.setEntity(new ByteArrayEntity(msgBytes)); - return Proxies.enhanceResponse(error); + return error; } HttpCacheEntry doGetUpdatedParentEntry( @@ -250,11 +247,10 @@ class BasicHttpCache implements HttpCache { return new HttpCacheEntry( src.getRequestDate(), src.getResponseDate(), - src.getStatusLine(), + src.getStatus(), src.getAllHeaders(), resource, - variantMap, - src.getRequestMethod()); + variantMap); } @Override @@ -262,7 +258,7 @@ class BasicHttpCache implements HttpCache { final HttpCacheEntry stale, final HttpResponse originResponse, final Date requestSent, final Date responseReceived) throws IOException { final HttpCacheEntry updatedEntry = cacheEntryUpdater.updateCacheEntry( - request.getRequestLine().getUri(), + request.getRequestUri(), stale, requestSent, responseReceived, @@ -276,7 +272,7 @@ class BasicHttpCache implements HttpCache { final HttpCacheEntry stale, final HttpResponse originResponse, final Date requestSent, final Date responseReceived, final String cacheKey) throws IOException { final HttpCacheEntry updatedEntry = cacheEntryUpdater.updateCacheEntry( - request.getRequestLine().getUri(), + request.getRequestUri(), stale, requestSent, responseReceived, @@ -286,19 +282,10 @@ class BasicHttpCache implements HttpCache { } @Override - public HttpResponse cacheAndReturnResponse(final HttpHost host, final HttpRequest request, - final HttpResponse originResponse, final Date requestSent, final Date responseReceived) - throws IOException { - return cacheAndReturnResponse(host, request, - Proxies.enhanceResponse(originResponse), requestSent, - responseReceived); - } - - @Override - public CloseableHttpResponse cacheAndReturnResponse( + public ClassicHttpResponse cacheAndReturnResponse( final HttpHost host, final HttpRequest request, - final CloseableHttpResponse originResponse, + final ClassicHttpResponse originResponse, final Date requestSent, final Date responseReceived) throws IOException { @@ -320,12 +307,11 @@ class BasicHttpCache implements HttpCache { final HttpCacheEntry entry = new HttpCacheEntry( requestSent, responseReceived, - originResponse.getStatusLine(), + originResponse.getCode(), originResponse.getAllHeaders(), - resource, - request.getRequestLine().getMethod()); + resource); storeInCache(host, request, entry); - return responseGenerator.generateResponse(HttpRequestWrapper.wrap(request, host), entry); + return responseGenerator.generateResponse(request, entry); } finally { if (closeOriginResponse) { originResponse.close(); @@ -334,21 +320,21 @@ class BasicHttpCache implements HttpCache { } SizeLimitedResponseReader getResponseReader(final HttpRequest request, - final CloseableHttpResponse backEndResponse) { + final ClassicHttpResponse backEndResponse) { return new SizeLimitedResponseReader( resourceFactory, maxObjectSizeBytes, request, backEndResponse); } @Override public HttpCacheEntry getCacheEntry(final HttpHost host, final HttpRequest request) throws IOException { - final HttpCacheEntry root = storage.getEntry(uriExtractor.getURI(host, request)); + final HttpCacheEntry root = storage.getEntry(uriExtractor.generateKey(host, request)); if (root == null) { return null; } if (!root.hasVariants()) { return root; } - final String variantCacheKey = root.getVariantMap().get(uriExtractor.getVariantKey(request, root)); + final String variantCacheKey = root.getVariantMap().get(uriExtractor.generateVariantKey(request, root)); if (variantCacheKey == null) { return null; } @@ -365,7 +351,7 @@ class BasicHttpCache implements HttpCache { public Map getVariantCacheEntriesWithEtags(final HttpHost host, final HttpRequest request) throws IOException { final Map variants = new HashMap<>(); - final HttpCacheEntry root = storage.getEntry(uriExtractor.getURI(host, request)); + final HttpCacheEntry root = storage.getEntry(uriExtractor.generateKey(host, request)); if (root == null || !root.hasVariants()) { return variants; } diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/BasicHttpCacheStorage.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/BasicHttpCacheStorage.java index ad429c530..43899c594 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/BasicHttpCacheStorage.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/BasicHttpCacheStorage.java @@ -31,7 +31,8 @@ import java.io.IOException; import org.apache.hc.client5.http.cache.HttpCacheEntry; import org.apache.hc.client5.http.cache.HttpCacheStorage; import org.apache.hc.client5.http.cache.HttpCacheUpdateCallback; -import org.apache.hc.core5.annotation.ThreadSafe; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; /** * Basic {@link HttpCacheStorage} implementation backed by an instance of @@ -43,7 +44,7 @@ import org.apache.hc.core5.annotation.ThreadSafe; * * @since 4.1 */ -@ThreadSafe +@Contract(threading = ThreadingBehavior.SAFE) public class BasicHttpCacheStorage implements HttpCacheStorage { private final CacheMap entries; diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/BasicIdGenerator.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/BasicIdGenerator.java index f3c202441..5c48ed719 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/BasicIdGenerator.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/BasicIdGenerator.java @@ -33,19 +33,18 @@ import java.security.SecureRandom; import java.util.Formatter; import java.util.Locale; -import org.apache.hc.core5.annotation.GuardedBy; -import org.apache.hc.core5.annotation.ThreadSafe; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; /** * Should produce reasonably unique tokens. */ -@ThreadSafe +@Contract(threading = ThreadingBehavior.SAFE) class BasicIdGenerator { private final String hostname; private final SecureRandom rnd; - @GuardedBy("this") private long count; public BasicIdGenerator() { diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheEntity.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheEntity.java index 7f0e72de5..9968b93d0 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheEntity.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheEntity.java @@ -30,17 +30,19 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; +import java.util.List; import java.util.Set; import org.apache.hc.client5.http.cache.HttpCacheEntry; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; +import org.apache.hc.core5.function.Supplier; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.HttpHeaders; -import org.apache.hc.core5.http.TrailerSupplier; import org.apache.hc.core5.util.Args; -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) class CacheEntity implements HttpEntity, Serializable { private static final long serialVersionUID = -3467082284120936233L; @@ -98,7 +100,7 @@ class CacheEntity implements HttpEntity, Serializable { } @Override - public TrailerSupplier getTrailers() { + public Supplier> getTrailers() { return null; } @@ -107,4 +109,8 @@ class CacheEntity implements HttpEntity, Serializable { return null; } + @Override + public void close() throws IOException { + } + } diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheEntryUpdater.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheEntryUpdater.java index b4a6c0ad7..29e558659 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheEntryUpdater.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheEntryUpdater.java @@ -38,7 +38,8 @@ import org.apache.hc.client5.http.cache.HttpCacheEntry; import org.apache.hc.client5.http.cache.Resource; import org.apache.hc.client5.http.cache.ResourceFactory; import org.apache.hc.client5.http.utils.DateUtils; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpHeaders; import org.apache.hc.core5.http.HttpResponse; @@ -52,7 +53,7 @@ import org.apache.hc.core5.util.Args; * * @since 4.1 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) class CacheEntryUpdater { private final ResourceFactory resourceFactory; @@ -84,7 +85,7 @@ class CacheEntryUpdater { final Date requestDate, final Date responseDate, final HttpResponse response) throws IOException { - Args.check(response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_MODIFIED, + Args.check(response.getCode() == HttpStatus.SC_NOT_MODIFIED, "Response must have 304 status code"); final Header[] mergedHeaders = mergeHeaders(entry, response); Resource resource = null; @@ -94,10 +95,9 @@ class CacheEntryUpdater { return new HttpCacheEntry( requestDate, responseDate, - entry.getStatusLine(), + entry.getStatus(), mergedHeaders, - resource, - entry.getRequestMethod()); + resource); } protected Header[] mergeHeaders(final HttpCacheEntry entry, final HttpResponse response) { diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheInvalidator.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheInvalidator.java index 46c0ac796..666a2b1b6 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheInvalidator.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheInvalidator.java @@ -38,7 +38,8 @@ import org.apache.hc.client5.http.cache.HttpCacheEntry; import org.apache.hc.client5.http.cache.HttpCacheInvalidator; import org.apache.hc.client5.http.cache.HttpCacheStorage; import org.apache.hc.client5.http.utils.DateUtils; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpHeaders; import org.apache.hc.core5.http.HttpHost; @@ -51,7 +52,7 @@ import org.apache.hc.core5.http.HttpResponse; * * @since 4.1 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) class CacheInvalidator implements HttpCacheInvalidator { private final HttpCacheStorage storage; @@ -82,7 +83,7 @@ class CacheInvalidator implements HttpCacheInvalidator { */ @Override public void flushInvalidatedCacheEntries(final HttpHost host, final HttpRequest req) { - final String theUri = cacheKeyGenerator.getURI(host, req); + final String theUri = cacheKeyGenerator.generateKey(host, req); final HttpCacheEntry parent = getEntry(theUri); if (requestShouldNotBeCached(req) || shouldInvalidateHeadCacheEntry(req, parent)) { @@ -117,7 +118,7 @@ class CacheInvalidator implements HttpCacheInvalidator { } private boolean requestIsGet(final HttpRequest req) { - return req.getRequestLine().getMethod().equals((HeaderConstants.GET_METHOD)); + return req.getMethod().equals((HeaderConstants.GET_METHOD)); } private boolean isAHeadCacheEntry(final HttpCacheEntry parentCacheEntry) { @@ -142,7 +143,7 @@ class CacheInvalidator implements HttpCacheInvalidator { } protected void flushUriIfSameHost(final URL requestURL, final URL targetURL) { - final URL canonicalTarget = getAbsoluteURL(cacheKeyGenerator.canonicalizeUri(targetURL.toString())); + final URL canonicalTarget = getAbsoluteURL(cacheKeyGenerator.generateKey(targetURL)); if (canonicalTarget == null) { return; } @@ -190,7 +191,7 @@ class CacheInvalidator implements HttpCacheInvalidator { } protected boolean requestShouldNotBeCached(final HttpRequest req) { - final String method = req.getRequestLine().getMethod(); + final String method = req.getMethod(); return notGetOrHeadRequest(method); } @@ -205,11 +206,11 @@ class CacheInvalidator implements HttpCacheInvalidator { @Override public void flushInvalidatedCacheEntries(final HttpHost host, final HttpRequest request, final HttpResponse response) { - final int status = response.getStatusLine().getStatusCode(); + final int status = response.getCode(); if (status < 200 || status > 299) { return; } - final URL reqURL = getAbsoluteURL(cacheKeyGenerator.getURI(host, request)); + final URL reqURL = getAbsoluteURL(cacheKeyGenerator.generateKey(host, request)); if (reqURL == null) { return; } @@ -225,7 +226,7 @@ class CacheInvalidator implements HttpCacheInvalidator { private void flushLocationCacheEntry(final URL reqURL, final HttpResponse response, final URL location) { - final String cacheKey = cacheKeyGenerator.canonicalizeUri(location.toString()); + final String cacheKey = cacheKeyGenerator.generateKey(location); final HttpCacheEntry entry = getEntry(cacheKey); if (entry == null) { return; diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheKeyGenerator.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheKeyGenerator.java index f09805b1b..684f0f066 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheKeyGenerator.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheKeyGenerator.java @@ -27,32 +27,56 @@ package org.apache.hc.client5.http.impl.cache; import java.io.UnsupportedEncodingException; -import java.net.MalformedURLException; import java.net.URI; +import java.net.URISyntaxException; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; +import java.util.Iterator; import java.util.List; import org.apache.hc.client5.http.cache.HeaderConstants; import org.apache.hc.client5.http.cache.HttpCacheEntry; import org.apache.hc.client5.http.utils.URIUtils; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HeaderElement; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpRequest; +import org.apache.hc.core5.http.message.MessageSupport; +import org.apache.hc.core5.net.URIBuilder; /** * @since 4.1 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) class CacheKeyGenerator { private static final URI BASE_URI = URI.create("http://example.com/"); + private URI normalize(final URI uri) throws URISyntaxException { + final URIBuilder builder = new URIBuilder(URIUtils.resolve(BASE_URI, uri)) ; + if (builder.getHost() != null) { + if (builder.getScheme() == null) { + builder.setScheme("http"); + } + if (builder.getPort() == -1) { + if ("http".equalsIgnoreCase(builder.getScheme())) { + builder.setPort(80); + } else if ("https".equalsIgnoreCase(builder.getScheme())) { + builder.setPort(443); + } + } + } + if (builder.getPath() == null) { + builder.setPath("/"); + } + return builder.build(); + } + /** * For a given {@link HttpHost} and {@link HttpRequest} get a URI from the * pair that I can use as an identifier KEY into my HttpCache @@ -61,60 +85,40 @@ class CacheKeyGenerator { * @param req the {@link HttpRequest} * @return String the extracted URI */ - public String getURI(final HttpHost host, final HttpRequest req) { - if (isRelativeRequest(req)) { - return canonicalizeUri(String.format("%s%s", host.toString(), req.getRequestLine().getUri())); - } - return canonicalizeUri(req.getRequestLine().getUri()); - } - - public String canonicalizeUri(final String uri) { + public String generateKey(final HttpHost host, final HttpRequest req) { try { - final URI normalized = URIUtils.resolve(BASE_URI, uri); - final URL u = new URL(normalized.toASCIIString()); - final String protocol = u.getProtocol(); - final String hostname = u.getHost(); - final int port = canonicalizePort(u.getPort(), protocol); - final String path = u.getPath(); - final String query = u.getQuery(); - final String file = (query != null) ? (path + "?" + query) : path; - final URL out = new URL(protocol, hostname, port, file); - return out.toString(); - } catch (final IllegalArgumentException e) { - return uri; - } catch (final MalformedURLException e) { - return uri; + URI uri = req.getUri(); + if (!uri.isAbsolute()) { + uri = URIUtils.rewriteURI(uri, host); + } + return normalize(uri).toASCIIString(); + } catch (URISyntaxException ex) { + return req.getRequestUri(); } } - private int canonicalizePort(final int port, final String protocol) { - if (port == -1 && "http".equalsIgnoreCase(protocol)) { - return 80; - } else if (port == -1 && "https".equalsIgnoreCase(protocol)) { - return 443; + public String generateKey(final URL url) { + if (url == null) { + return null; + } + try { + return normalize(url.toURI()).toASCIIString(); + } catch (URISyntaxException ex) { + return url.toString(); } - return port; - } - - private boolean isRelativeRequest(final HttpRequest req) { - final String requestUri = req.getRequestLine().getUri(); - return ("*".equals(requestUri) || requestUri.startsWith("/")); } protected String getFullHeaderValue(final Header[] headers) { if (headers == null) { return ""; } - final StringBuilder buf = new StringBuilder(""); - boolean first = true; - for (final Header hdr : headers) { - if (!first) { + for (int i = 0; i < headers.length; i++) { + final Header hdr = headers[i]; + if (i > 0) { buf.append(", "); } buf.append(hdr.getValue().trim()); - first = false; - } return buf.toString(); } @@ -129,11 +133,11 @@ class CacheKeyGenerator { * @param entry the parent entry used to track the variants * @return String the extracted variant URI */ - public String getVariantURI(final HttpHost host, final HttpRequest req, final HttpCacheEntry entry) { + public String generateVariantURI(final HttpHost host, final HttpRequest req, final HttpCacheEntry entry) { if (!entry.hasVariants()) { - return getURI(host, req); + return generateKey(host, req); } - return getVariantKey(req, entry) + getURI(host, req); + return generateVariantKey(req, entry) + generateKey(host, req); } /** @@ -145,12 +149,12 @@ class CacheKeyGenerator { * @param entry cache entry in question that has variants * @return a {@code String} variant key */ - public String getVariantKey(final HttpRequest req, final HttpCacheEntry entry) { + public String generateVariantKey(final HttpRequest req, final HttpCacheEntry entry) { final List variantHeaderNames = new ArrayList<>(); - for (final Header varyHdr : entry.getHeaders(HeaderConstants.VARY)) { - for (final HeaderElement elt : varyHdr.getElements()) { - variantHeaderNames.add(elt.getName()); - } + final Iterator it = MessageSupport.iterate(entry, HeaderConstants.VARY); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + variantHeaderNames.add(elt.getName()); } Collections.sort(variantHeaderNames); diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheValidityPolicy.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheValidityPolicy.java index 07fec9666..d468f265e 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheValidityPolicy.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheValidityPolicy.java @@ -27,20 +27,24 @@ package org.apache.hc.client5.http.impl.cache; import java.util.Date; +import java.util.Iterator; import org.apache.hc.client5.http.cache.HeaderConstants; import org.apache.hc.client5.http.cache.HttpCacheEntry; import org.apache.hc.client5.http.utils.DateUtils; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.http.message.MessageSupport; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; 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.MessageHeaders; /** * @since 4.1 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) class CacheValidityPolicy { public static final long MAX_AGE = 2147483648L; @@ -124,17 +128,17 @@ class CacheValidityPolicy { } public boolean mayReturnStaleWhileRevalidating(final HttpCacheEntry entry, final Date now) { - for (final Header h : entry.getHeaders(HeaderConstants.CACHE_CONTROL)) { - for(final HeaderElement elt : h.getElements()) { - if (HeaderConstants.STALE_WHILE_REVALIDATE.equalsIgnoreCase(elt.getName())) { - try { - final int allowedStalenessLifetime = Integer.parseInt(elt.getValue()); - if (getStalenessSecs(entry, now) <= allowedStalenessLifetime) { - return true; - } - } catch (final NumberFormatException nfe) { - // skip malformed directive + final Iterator it = MessageSupport.iterate(entry, HeaderConstants.CACHE_CONTROL); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + if (HeaderConstants.STALE_WHILE_REVALIDATE.equalsIgnoreCase(elt.getName())) { + try { + final int allowedStalenessLifetime = Integer.parseInt(elt.getValue()); + if (getStalenessSecs(entry, now) <= allowedStalenessLifetime) { + return true; } + } catch (final NumberFormatException nfe) { + // skip malformed directive } } } @@ -142,29 +146,26 @@ class CacheValidityPolicy { return false; } - public boolean mayReturnStaleIfError(final HttpRequest request, - final HttpCacheEntry entry, final Date now) { + public boolean mayReturnStaleIfError(final HttpRequest request, final HttpCacheEntry entry, final Date now) { final long stalenessSecs = getStalenessSecs(entry, now); - return mayReturnStaleIfError(request.getHeaders(HeaderConstants.CACHE_CONTROL), - stalenessSecs) - || mayReturnStaleIfError(entry.getHeaders(HeaderConstants.CACHE_CONTROL), - stalenessSecs); + return mayReturnStaleIfError(request, HeaderConstants.CACHE_CONTROL, stalenessSecs) + || mayReturnStaleIfError(entry, HeaderConstants.CACHE_CONTROL, stalenessSecs); } - private boolean mayReturnStaleIfError(final Header[] headers, final long stalenessSecs) { + private boolean mayReturnStaleIfError(final MessageHeaders headers, final String name, final long stalenessSecs) { boolean result = false; - for(final Header h : headers) { - for(final HeaderElement elt : h.getElements()) { - if (HeaderConstants.STALE_IF_ERROR.equals(elt.getName())) { - try { - final int staleIfErrorSecs = Integer.parseInt(elt.getValue()); - if (stalenessSecs <= staleIfErrorSecs) { - result = true; - break; - } - } catch (final NumberFormatException nfe) { - // skip malformed directive + final Iterator it = MessageSupport.iterate(headers, name); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + if (HeaderConstants.STALE_IF_ERROR.equals(elt.getName())) { + try { + final int staleIfErrorSecs = Integer.parseInt(elt.getValue()); + if (stalenessSecs <= staleIfErrorSecs) { + result = true; + break; } + } catch (final NumberFormatException nfe) { + // skip malformed directive } } } @@ -259,19 +260,18 @@ class CacheValidityPolicy { protected long getMaxAge(final HttpCacheEntry entry) { long maxage = -1; - for (final Header hdr : entry.getHeaders(HeaderConstants.CACHE_CONTROL)) { - for (final HeaderElement elt : hdr.getElements()) { - if (HeaderConstants.CACHE_CONTROL_MAX_AGE.equals(elt.getName()) - || "s-maxage".equals(elt.getName())) { - try { - final long currMaxAge = Long.parseLong(elt.getValue()); - if (maxage == -1 || currMaxAge < maxage) { - maxage = currMaxAge; - } - } catch (final NumberFormatException nfe) { - // be conservative if can't parse - maxage = 0; + final Iterator it = MessageSupport.iterate(entry, HeaderConstants.CACHE_CONTROL); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + if (HeaderConstants.CACHE_CONTROL_MAX_AGE.equals(elt.getName()) || "s-maxage".equals(elt.getName())) { + try { + final long currMaxAge = Long.parseLong(elt.getValue()); + if (maxage == -1 || currMaxAge < maxage) { + maxage = currMaxAge; } + } catch (final NumberFormatException nfe) { + // be conservative if can't parse + maxage = 0; } } } @@ -286,13 +286,12 @@ class CacheValidityPolicy { return DateUtils.parseDate(expiresHeader.getValue()); } - public boolean hasCacheControlDirective(final HttpCacheEntry entry, - final String directive) { - for (final Header h : entry.getHeaders(HeaderConstants.CACHE_CONTROL)) { - for(final HeaderElement elt : h.getElements()) { - if (directive.equalsIgnoreCase(elt.getName())) { - return true; - } + public boolean hasCacheControlDirective(final HttpCacheEntry entry, final String directive) { + final Iterator it = MessageSupport.iterate(entry, HeaderConstants.CACHE_CONTROL); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + if (directive.equalsIgnoreCase(elt.getName())) { + return true; } } return false; 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 b71c3f6c0..05924fcf7 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,11 +26,14 @@ */ package org.apache.hc.client5.http.impl.cache; +import java.util.Iterator; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.apache.hc.core5.http.message.MessageSupport; import org.apache.hc.client5.http.cache.HeaderConstants; -import org.apache.hc.core5.annotation.Immutable; -import org.apache.hc.core5.http.Header; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.HeaderElement; import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.HttpVersion; @@ -41,7 +44,7 @@ import org.apache.hc.core5.http.ProtocolVersion; * * @since 4.1 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) class CacheableRequestPolicy { private final Log log = LogFactory.getLog(getClass()); @@ -54,9 +57,9 @@ class CacheableRequestPolicy { * @return boolean Is it possible to serve this request from cache */ public boolean isServableFromCache(final HttpRequest request) { - final String method = request.getRequestLine().getMethod(); + final String method = request.getMethod(); - final ProtocolVersion pv = request.getRequestLine().getProtocolVersion(); + final ProtocolVersion pv = request.getVersion() != null ? request.getVersion() : HttpVersion.DEFAULT; if (HttpVersion.HTTP_1_1.compareToVersion(pv) != 0) { log.trace("non-HTTP/1.1 request was not serveable from cache"); return false; @@ -73,20 +76,18 @@ class CacheableRequestPolicy { return false; } - final Header[] cacheControlHeaders = request.getHeaders(HeaderConstants.CACHE_CONTROL); - for (final Header cacheControl : cacheControlHeaders) { - for (final HeaderElement cacheControlElement : cacheControl.getElements()) { - if (HeaderConstants.CACHE_CONTROL_NO_STORE.equalsIgnoreCase(cacheControlElement - .getName())) { - log.trace("Request with no-store was not serveable from cache"); - return false; - } - - if (HeaderConstants.CACHE_CONTROL_NO_CACHE.equalsIgnoreCase(cacheControlElement - .getName())) { - log.trace("Request with no-cache was not serveable from cache"); - return false; - } + final Iterator it = MessageSupport.iterate(request, HeaderConstants.CACHE_CONTROL); + while (it.hasNext()) { + final HeaderElement cacheControlElement = it.next(); + if (HeaderConstants.CACHE_CONTROL_NO_STORE.equalsIgnoreCase(cacheControlElement + .getName())) { + log.trace("Request with no-store was not serveable from cache"); + return false; + } + if (HeaderConstants.CACHE_CONTROL_NO_CACHE.equalsIgnoreCase(cacheControlElement + .getName())) { + log.trace("Request with no-cache was not serveable from cache"); + return false; } } 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 ceaae71a2..22bbfc765 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 @@ -30,25 +30,26 @@ import java.util.Date; import org.apache.hc.client5.http.cache.HeaderConstants; import org.apache.hc.client5.http.cache.HttpCacheEntry; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; import org.apache.hc.client5.http.utils.DateUtils; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; +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.HttpHeaders; +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.HttpVersion; +import org.apache.hc.core5.http.message.BasicClassicHttpResponse; import org.apache.hc.core5.http.message.BasicHeader; -import org.apache.hc.core5.http.message.BasicHttpResponse; /** * Rebuilds an {@link HttpResponse} from a {@link net.sf.ehcache.CacheEntry} * * @since 4.1 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) class CachedHttpResponseGenerator { private final CacheValidityPolicy validityStrategy; @@ -63,16 +64,16 @@ class CachedHttpResponseGenerator { } /** - * If I was able to use a {@link CacheEntity} to response to the {@link org.apache.hc.core5.http.HttpRequest} then + * If I was able to use a {@link CacheEntity} to response to the {@link HttpRequest} then * generate an {@link HttpResponse} based on the cache entry. - * @param request {@link HttpRequestWrapper} to generate the response for + * @param request {@link HttpRequest} to generate the response for * @param entry {@link CacheEntity} to transform into an {@link HttpResponse} * @return {@link HttpResponse} that was constructed */ - CloseableHttpResponse generateResponse(final HttpRequestWrapper request, final HttpCacheEntry entry) { + ClassicHttpResponse generateResponse(final HttpRequest request, final HttpCacheEntry entry) { final Date now = new Date(); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, entry - .getStatusCode(), entry.getReasonPhrase()); + final ClassicHttpResponse response = new BasicClassicHttpResponse(entry.getStatus()); + response.setVersion(HttpVersion.DEFAULT); response.setHeaders(entry.getAllHeaders()); @@ -91,17 +92,16 @@ class CachedHttpResponseGenerator { } } - return Proxies.enhanceResponse(response); + return response; } /** * Generate a 304 - Not Modified response from a {@link CacheEntity}. This should be * used to respond to conditional requests, when the entry exists or has been re-validated. */ - CloseableHttpResponse generateNotModifiedResponse(final HttpCacheEntry entry) { + ClassicHttpResponse generateNotModifiedResponse(final HttpCacheEntry entry) { - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_NOT_MODIFIED, "Not Modified"); + final ClassicHttpResponse response = new BasicClassicHttpResponse(HttpStatus.SC_NOT_MODIFIED, "Not Modified"); // The response MUST include the following headers // (http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) @@ -143,7 +143,7 @@ class CachedHttpResponseGenerator { response.addHeader(varyHeader); } - return Proxies.enhanceResponse(response); + return response; } private void addMissingContentLengthHeader(final HttpResponse response, final HttpEntity entity) { @@ -164,9 +164,8 @@ class CachedHttpResponseGenerator { return hdr != null; } - private boolean responseShouldContainEntity(final HttpRequestWrapper request, final HttpCacheEntry cacheEntry) { - return request.getRequestLine().getMethod().equals(HeaderConstants.GET_METHOD) && - cacheEntry.getResource() != null; + private boolean responseShouldContainEntity(final HttpRequest request, final HttpCacheEntry cacheEntry) { + return request.getMethod().equals(HeaderConstants.GET_METHOD) && cacheEntry.getResource() != null; } } diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachedResponseSuitabilityChecker.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachedResponseSuitabilityChecker.java index 3a8b43b8d..7462b7ef8 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachedResponseSuitabilityChecker.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachedResponseSuitabilityChecker.java @@ -27,13 +27,16 @@ package org.apache.hc.client5.http.impl.cache; import java.util.Date; +import java.util.Iterator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hc.client5.http.cache.HeaderConstants; import org.apache.hc.client5.http.cache.HttpCacheEntry; import org.apache.hc.client5.http.utils.DateUtils; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.http.message.MessageSupport; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HeaderElement; import org.apache.hc.core5.http.HttpHost; @@ -46,7 +49,7 @@ import org.apache.hc.core5.http.HttpStatus; * * @since 4.1 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) class CachedResponseSuitabilityChecker { private final Log log = LogFactory.getLog(getClass()); @@ -102,25 +105,24 @@ class CachedResponseSuitabilityChecker { private long getMaxStale(final HttpRequest request) { long maxstale = -1; - for(final Header h : request.getHeaders(HeaderConstants.CACHE_CONTROL)) { - for(final HeaderElement elt : h.getElements()) { - if (HeaderConstants.CACHE_CONTROL_MAX_STALE.equals(elt.getName())) { - if ((elt.getValue() == null || "".equals(elt.getValue().trim())) - && maxstale == -1) { - maxstale = Long.MAX_VALUE; - } else { - try { - long val = Long.parseLong(elt.getValue()); - if (val < 0) { - val = 0; - } - if (maxstale == -1 || val < maxstale) { - maxstale = val; - } - } catch (final NumberFormatException nfe) { - // err on the side of preserving semantic transparency - maxstale = 0; + final Iterator it = MessageSupport.iterate(request, HeaderConstants.CACHE_CONTROL); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + if (HeaderConstants.CACHE_CONTROL_MAX_STALE.equals(elt.getName())) { + if ((elt.getValue() == null || "".equals(elt.getValue().trim())) && maxstale == -1) { + maxstale = Long.MAX_VALUE; + } else { + try { + long val = Long.parseLong(elt.getValue()); + if (val < 0) { + val = 0; } + if (maxstale == -1 || val < maxstale) { + maxstale = val; + } + } catch (final NumberFormatException nfe) { + // err on the side of preserving semantic transparency + maxstale = 0; } } } @@ -158,7 +160,7 @@ class CachedResponseSuitabilityChecker { return false; } - if (!isConditional(request) && entry.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) { + if (!isConditional(request) && entry.getStatus() == HttpStatus.SC_NOT_MODIFIED) { return false; } @@ -171,65 +173,64 @@ class CachedResponseSuitabilityChecker { "request method, entity or a 204 response"); return false; } + final Iterator it = MessageSupport.iterate(request, HeaderConstants.CACHE_CONTROL); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + if (HeaderConstants.CACHE_CONTROL_NO_CACHE.equals(elt.getName())) { + log.trace("Response contained NO CACHE directive, cache was not suitable"); + return false; + } - for (final Header ccHdr : request.getHeaders(HeaderConstants.CACHE_CONTROL)) { - for (final HeaderElement elt : ccHdr.getElements()) { - if (HeaderConstants.CACHE_CONTROL_NO_CACHE.equals(elt.getName())) { - log.trace("Response contained NO CACHE directive, cache was not suitable"); + if (HeaderConstants.CACHE_CONTROL_NO_STORE.equals(elt.getName())) { + log.trace("Response contained NO STORE directive, cache was not suitable"); + return false; + } + + if (HeaderConstants.CACHE_CONTROL_MAX_AGE.equals(elt.getName())) { + try { + final int maxage = Integer.parseInt(elt.getValue()); + if (validityStrategy.getCurrentAgeSecs(entry, now) > maxage) { + log.trace("Response from cache was NOT suitable due to max age"); + return false; + } + } catch (final NumberFormatException ex) { + // err conservatively + log.debug("Response from cache was malformed" + ex.getMessage()); return false; } + } - if (HeaderConstants.CACHE_CONTROL_NO_STORE.equals(elt.getName())) { - log.trace("Response contained NO STORE directive, cache was not suitable"); + if (HeaderConstants.CACHE_CONTROL_MAX_STALE.equals(elt.getName())) { + try { + final int maxstale = Integer.parseInt(elt.getValue()); + if (validityStrategy.getFreshnessLifetimeSecs(entry) > maxstale) { + log.trace("Response from cache was not suitable due to Max stale freshness"); + return false; + } + } catch (final NumberFormatException ex) { + // err conservatively + log.debug("Response from cache was malformed: " + ex.getMessage()); return false; } + } - if (HeaderConstants.CACHE_CONTROL_MAX_AGE.equals(elt.getName())) { - try { - final int maxage = Integer.parseInt(elt.getValue()); - if (validityStrategy.getCurrentAgeSecs(entry, now) > maxage) { - log.trace("Response from cache was NOT suitable due to max age"); - return false; - } - } catch (final NumberFormatException ex) { - // err conservatively - log.debug("Response from cache was malformed" + ex.getMessage()); + if (HeaderConstants.CACHE_CONTROL_MIN_FRESH.equals(elt.getName())) { + try { + final long minfresh = Long.parseLong(elt.getValue()); + if (minfresh < 0L) { return false; } - } - - if (HeaderConstants.CACHE_CONTROL_MAX_STALE.equals(elt.getName())) { - try { - final int maxstale = Integer.parseInt(elt.getValue()); - if (validityStrategy.getFreshnessLifetimeSecs(entry) > maxstale) { - log.trace("Response from cache was not suitable due to Max stale freshness"); - return false; - } - } catch (final NumberFormatException ex) { - // err conservatively - log.debug("Response from cache was malformed: " + ex.getMessage()); - return false; - } - } - - if (HeaderConstants.CACHE_CONTROL_MIN_FRESH.equals(elt.getName())) { - try { - final long minfresh = Long.parseLong(elt.getValue()); - if (minfresh < 0L) { - return false; - } - final long age = validityStrategy.getCurrentAgeSecs(entry, now); - final long freshness = validityStrategy.getFreshnessLifetimeSecs(entry); - if (freshness - age < minfresh) { - log.trace("Response from cache was not suitable due to min fresh " + - "freshness requirement"); - return false; - } - } catch (final NumberFormatException ex) { - // err conservatively - log.debug("Response from cache was malformed: " + ex.getMessage()); + final long age = validityStrategy.getCurrentAgeSecs(entry, now); + final long freshness = validityStrategy.getFreshnessLifetimeSecs(entry); + if (freshness - age < minfresh) { + log.trace("Response from cache was not suitable due to min fresh " + + "freshness requirement"); return false; } + } catch (final NumberFormatException ex) { + // err conservatively + log.debug("Response from cache was malformed: " + ex.getMessage()); + return false; } } } @@ -239,11 +240,11 @@ class CachedResponseSuitabilityChecker { } private boolean isGet(final HttpRequest request) { - return request.getRequestLine().getMethod().equals(HeaderConstants.GET_METHOD); + return request.getMethod().equals(HeaderConstants.GET_METHOD); } private boolean entryIsNotA204Response(final HttpCacheEntry entry) { - return entry.getStatusCode() != HttpStatus.SC_NO_CONTENT; + return entry.getStatus() != HttpStatus.SC_NO_CONTENT; } private boolean cacheEntryDoesNotContainMethodAndEntity(final HttpCacheEntry entry) { @@ -313,16 +314,12 @@ class CachedResponseSuitabilityChecker { private boolean etagValidatorMatches(final HttpRequest request, final HttpCacheEntry entry) { final Header etagHeader = entry.getFirstHeader(HeaderConstants.ETAG); final String etag = (etagHeader != null) ? etagHeader.getValue() : null; - final Header[] ifNoneMatch = request.getHeaders(HeaderConstants.IF_NONE_MATCH); - if (ifNoneMatch != null) { - for (final Header h : ifNoneMatch) { - for (final HeaderElement elt : h.getElements()) { - final String reqEtag = elt.toString(); - if (("*".equals(reqEtag) && etag != null) - || reqEtag.equals(etag)) { - return true; - } - } + final Iterator it = MessageSupport.iterate(request, HeaderConstants.IF_NONE_MATCH); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + final String reqEtag = elt.toString(); + if (("*".equals(reqEtag) && etag != null) || reqEtag.equals(etag)) { + 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 38a17cb22..872116cb1 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 @@ -27,10 +27,9 @@ package org.apache.hc.client5.http.impl.cache; import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; import java.util.Date; import java.util.HashMap; +import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; @@ -45,13 +44,13 @@ import org.apache.hc.client5.http.cache.HttpCacheEntry; import org.apache.hc.client5.http.cache.HttpCacheStorage; import org.apache.hc.client5.http.cache.ResourceFactory; import org.apache.hc.client5.http.impl.sync.ClientExecChain; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpExecutionAware; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.utils.DateUtils; -import org.apache.hc.client5.http.utils.URIUtils; -import org.apache.hc.core5.annotation.ThreadSafe; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; +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.HttpException; @@ -62,10 +61,9 @@ 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.HttpVersion; -import org.apache.hc.core5.http.ProtocolException; import org.apache.hc.core5.http.ProtocolVersion; -import org.apache.hc.core5.http.RequestLine; -import org.apache.hc.core5.http.message.BasicHttpResponse; +import org.apache.hc.core5.http.message.BasicClassicHttpResponse; +import org.apache.hc.core5.http.message.MessageSupport; import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.http.protocol.HttpCoreContext; import org.apache.hc.core5.util.Args; @@ -99,7 +97,7 @@ import org.apache.hc.core5.util.VersionInfo; * * @since 4.3 */ -@ThreadSafe // So long as the responseCache implementation is threadsafe +@Contract(threading = ThreadingBehavior.SAFE) // So long as the responseCache implementation is threadsafe public class CachingExec implements ClientExecChain { private final static boolean SUPPORTS_RANGE_AND_CONTENT_RANGE_HEADERS = false; @@ -223,27 +221,23 @@ public class CachingExec implements ClientExecChain { return cacheUpdates.get(); } - public CloseableHttpResponse execute( - final HttpRoute route, - final HttpRequestWrapper request) throws IOException, HttpException { - return execute(route, request, HttpClientContext.create(), null); + public ClassicHttpResponse execute(final RoutedHttpRequest request) throws IOException, HttpException { + return execute(request, HttpClientContext.create(), null); } - public CloseableHttpResponse execute( - final HttpRoute route, - final HttpRequestWrapper request, + public ClassicHttpResponse execute( + final RoutedHttpRequest request, final HttpClientContext context) throws IOException, HttpException { - return execute(route, request, context, null); + return execute(request, context, null); } @Override - public CloseableHttpResponse execute( - final HttpRoute route, - final HttpRequestWrapper request, + public ClassicHttpResponse execute( + final RoutedHttpRequest request, final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException { - final HttpHost target = context.getTargetHost(); + final HttpHost target = request.getTargetHost(); final String via = generateViaHeader(request.getOriginal()); // default response context @@ -251,42 +245,41 @@ public class CachingExec implements ClientExecChain { if (clientRequestsOurOptions(request)) { setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE); - return Proxies.enhanceResponse(new OptionsHttp11Response()); + return new OptionsHttp11Response(); } - final HttpResponse fatalErrorResponse = getFatallyNoncompliantResponse(request, context); + final ClassicHttpResponse fatalErrorResponse = getFatallyNoncompliantResponse(request, context); if (fatalErrorResponse != null) { - return Proxies.enhanceResponse(fatalErrorResponse); + return fatalErrorResponse; } requestCompliance.makeRequestCompliant(request); request.addHeader("Via",via); - flushEntriesInvalidatedByRequest(context.getTargetHost(), request); + flushEntriesInvalidatedByRequest(target, request); if (!cacheableRequestPolicy.isServableFromCache(request)) { log.debug("Request is not servable from cache"); - return callBackend(route, request, context, execAware); + return callBackend(request, context, execAware); } final HttpCacheEntry entry = satisfyFromCache(target, request); if (entry == null) { log.debug("Cache miss"); - return handleCacheMiss(route, request, context, execAware); + return handleCacheMiss(request, context, execAware); } else { - return handleCacheHit(route, request, context, execAware, entry); + return handleCacheHit(request, context, execAware, entry); } } - private CloseableHttpResponse handleCacheHit( - final HttpRoute route, - final HttpRequestWrapper request, + private ClassicHttpResponse handleCacheHit( + final RoutedHttpRequest request, final HttpClientContext context, final HttpExecutionAware execAware, final HttpCacheEntry entry) throws IOException, HttpException { - final HttpHost target = context.getTargetHost(); + final HttpHost target = request.getTargetHost(); recordCacheHit(target, request); - CloseableHttpResponse out = null; + ClassicHttpResponse out; final Date now = getCurrentDate(); if (suitabilityChecker.canCachedResponseBeUsed(target, request, entry, now)) { log.debug("Cache hit"); @@ -294,24 +287,23 @@ public class CachingExec implements ClientExecChain { } else if (!mayCallBackend(request)) { log.debug("Cache entry not suitable but only-if-cached requested"); out = generateGatewayTimeout(context); - } else if (!(entry.getStatusCode() == HttpStatus.SC_NOT_MODIFIED + } else if (!(entry.getStatus() == HttpStatus.SC_NOT_MODIFIED && !suitabilityChecker.isConditional(request))) { log.debug("Revalidating cache entry"); - return revalidateCacheEntry(route, request, context, execAware, entry, now); + return revalidateCacheEntry(request, context, execAware, entry, now); } else { log.debug("Cache entry not usable; calling backend"); - return callBackend(route, request, context, execAware); + return callBackend(request, context, execAware); } + final HttpRoute route = request.getRoute(); context.setAttribute(HttpClientContext.HTTP_ROUTE, route); - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target); context.setAttribute(HttpCoreContext.HTTP_REQUEST, request); context.setAttribute(HttpCoreContext.HTTP_RESPONSE, out); return out; } - private CloseableHttpResponse revalidateCacheEntry( - final HttpRoute route, - final HttpRequestWrapper request, + private ClassicHttpResponse revalidateCacheEntry( + final RoutedHttpRequest request, final HttpClientContext context, final HttpExecutionAware execAware, final HttpCacheEntry entry, @@ -322,41 +314,37 @@ public class CachingExec implements ClientExecChain { && !staleResponseNotAllowed(request, entry, now) && validityPolicy.mayReturnStaleWhileRevalidating(entry, now)) { log.trace("Serving stale with asynchronous revalidation"); - final CloseableHttpResponse resp = generateCachedResponse(request, context, entry, now); - asynchRevalidator.revalidateCacheEntry(this, route, request, context, execAware, entry); + final ClassicHttpResponse resp = generateCachedResponse(request, context, entry, now); + asynchRevalidator.revalidateCacheEntry(this, request, context, execAware, entry); return resp; } - return revalidateCacheEntry(route, request, context, execAware, entry); + return revalidateCacheEntry(request, context, execAware, entry); } catch (final IOException ioex) { return handleRevalidationFailure(request, context, entry, now); } } - private CloseableHttpResponse handleCacheMiss( - final HttpRoute route, - final HttpRequestWrapper request, + private ClassicHttpResponse handleCacheMiss( + final RoutedHttpRequest request, final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException { - final HttpHost target = context.getTargetHost(); + final HttpHost target = request.getTargetHost(); recordCacheMiss(target, request); if (!mayCallBackend(request)) { - return Proxies.enhanceResponse( - new BasicHttpResponse( - HttpVersion.HTTP_1_1, HttpStatus.SC_GATEWAY_TIMEOUT, "Gateway Timeout")); + return new BasicClassicHttpResponse(HttpStatus.SC_GATEWAY_TIMEOUT, "Gateway Timeout"); } final Map variants = getExistingCacheVariants(target, request); if (variants != null && !variants.isEmpty()) { - return negotiateResponseFromVariants(route, request, context, - execAware, variants); + return negotiateResponseFromVariants(request, context, execAware, variants); } - return callBackend(route, request, context, execAware); + return callBackend(request, context, execAware); } private HttpCacheEntry satisfyFromCache( - final HttpHost target, final HttpRequestWrapper request) { + final HttpHost target, final RoutedHttpRequest request) { HttpCacheEntry entry = null; try { entry = responseCache.getCacheEntry(target, request); @@ -366,10 +354,10 @@ public class CachingExec implements ClientExecChain { return entry; } - private HttpResponse getFatallyNoncompliantResponse( - final HttpRequestWrapper request, + private ClassicHttpResponse getFatallyNoncompliantResponse( + final RoutedHttpRequest request, final HttpContext context) { - HttpResponse fatalErrorResponse = null; + ClassicHttpResponse fatalErrorResponse = null; final List fatalError = requestCompliance.requestIsFatallyNonCompliant(request); for (final RequestProtocolError error : fatalError) { @@ -381,7 +369,7 @@ public class CachingExec implements ClientExecChain { private Map getExistingCacheVariants( final HttpHost target, - final HttpRequestWrapper request) { + final RoutedHttpRequest request) { Map variants = null; try { variants = responseCache.getVariantCacheEntriesWithEtags(target, request); @@ -391,19 +379,17 @@ public class CachingExec implements ClientExecChain { return variants; } - private void recordCacheMiss(final HttpHost target, final HttpRequestWrapper request) { + private void recordCacheMiss(final HttpHost target, final RoutedHttpRequest request) { cacheMisses.getAndIncrement(); if (log.isTraceEnabled()) { - final RequestLine rl = request.getRequestLine(); - log.trace("Cache miss [host: " + target + "; uri: " + rl.getUri() + "]"); + log.trace("Cache miss [host: " + target + "; uri: " + request.getRequestUri() + "]"); } } - private void recordCacheHit(final HttpHost target, final HttpRequestWrapper request) { + private void recordCacheHit(final HttpHost target, final RoutedHttpRequest request) { cacheHits.getAndIncrement(); if (log.isTraceEnabled()) { - final RequestLine rl = request.getRequestLine(); - log.trace("Cache hit [host: " + target + "; uri: " + rl.getUri() + "]"); + log.trace("Cache hit [host: " + target + "; uri: " + request.getRequestUri() + "]"); } } @@ -414,7 +400,7 @@ public class CachingExec implements ClientExecChain { private void flushEntriesInvalidatedByRequest( final HttpHost target, - final HttpRequestWrapper request) { + final RoutedHttpRequest request) { try { responseCache.flushInvalidatedCacheEntriesFor(target, request); } catch (final IOException ioe) { @@ -422,9 +408,9 @@ public class CachingExec implements ClientExecChain { } } - private CloseableHttpResponse generateCachedResponse(final HttpRequestWrapper request, + private ClassicHttpResponse generateCachedResponse(final RoutedHttpRequest request, final HttpContext context, final HttpCacheEntry entry, final Date now) { - final CloseableHttpResponse cachedResponse; + final ClassicHttpResponse cachedResponse; if (request.containsHeader(HeaderConstants.IF_NONE_MATCH) || request.containsHeader(HeaderConstants.IF_MODIFIED_SINCE)) { cachedResponse = responseGenerator.generateNotModifiedResponse(entry); @@ -438,8 +424,8 @@ public class CachingExec implements ClientExecChain { return cachedResponse; } - private CloseableHttpResponse handleRevalidationFailure( - final HttpRequestWrapper request, + private ClassicHttpResponse handleRevalidationFailure( + final RoutedHttpRequest request, final HttpContext context, final HttpCacheEntry entry, final Date now) { @@ -450,26 +436,24 @@ public class CachingExec implements ClientExecChain { } } - private CloseableHttpResponse generateGatewayTimeout( + private ClassicHttpResponse generateGatewayTimeout( final HttpContext context) { setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE); - return Proxies.enhanceResponse(new BasicHttpResponse( - HttpVersion.HTTP_1_1, HttpStatus.SC_GATEWAY_TIMEOUT, - "Gateway Timeout")); + return new BasicClassicHttpResponse(HttpStatus.SC_GATEWAY_TIMEOUT, "Gateway Timeout"); } - private CloseableHttpResponse unvalidatedCacheHit( - final HttpRequestWrapper request, + private ClassicHttpResponse unvalidatedCacheHit( + final RoutedHttpRequest request, final HttpContext context, final HttpCacheEntry entry) { - final CloseableHttpResponse cachedResponse = responseGenerator.generateResponse(request, entry); + final ClassicHttpResponse cachedResponse = responseGenerator.generateResponse(request, entry); setResponseStatus(context, CacheResponseStatus.CACHE_HIT); cachedResponse.addHeader(HeaderConstants.WARNING, "111 localhost \"Revalidation failed\""); return cachedResponse; } private boolean staleResponseNotAllowed( - final HttpRequestWrapper request, + final RoutedHttpRequest request, final HttpCacheEntry entry, final Date now) { return validityPolicy.mustRevalidate(entry) @@ -477,39 +461,39 @@ public class CachingExec implements ClientExecChain { || explicitFreshnessRequest(request, entry, now); } - private boolean mayCallBackend(final HttpRequestWrapper request) { - for (final Header h: request.getHeaders(HeaderConstants.CACHE_CONTROL)) { - for (final HeaderElement elt : h.getElements()) { - if ("only-if-cached".equals(elt.getName())) { - log.trace("Request marked only-if-cached"); - return false; - } + private boolean mayCallBackend(final RoutedHttpRequest request) { + final Iterator it = MessageSupport.iterate(request, HeaderConstants.CACHE_CONTROL); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + if ("only-if-cached".equals(elt.getName())) { + log.trace("Request marked only-if-cached"); + return false; } } return true; } private boolean explicitFreshnessRequest( - final HttpRequestWrapper request, + final RoutedHttpRequest request, final HttpCacheEntry entry, final Date now) { - for(final Header h : request.getHeaders(HeaderConstants.CACHE_CONTROL)) { - for(final HeaderElement elt : h.getElements()) { - if (HeaderConstants.CACHE_CONTROL_MAX_STALE.equals(elt.getName())) { - try { - final int maxstale = Integer.parseInt(elt.getValue()); - final long age = validityPolicy.getCurrentAgeSecs(entry, now); - final long lifetime = validityPolicy.getFreshnessLifetimeSecs(entry); - if (age - lifetime > maxstale) { - return true; - } - } catch (final NumberFormatException nfe) { + final Iterator it = MessageSupport.iterate(request, HeaderConstants.CACHE_CONTROL); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + if (HeaderConstants.CACHE_CONTROL_MAX_STALE.equals(elt.getName())) { + try { + final int maxstale = Integer.parseInt(elt.getValue()); + final long age = validityPolicy.getCurrentAgeSecs(entry, now); + final long lifetime = validityPolicy.getFreshnessLifetimeSecs(entry); + if (age - lifetime > maxstale) { return true; } - } else if (HeaderConstants.CACHE_CONTROL_MIN_FRESH.equals(elt.getName()) - || HeaderConstants.CACHE_CONTROL_MAX_AGE.equals(elt.getName())) { + } catch (final NumberFormatException nfe) { return true; } + } else if (HeaderConstants.CACHE_CONTROL_MIN_FRESH.equals(elt.getName()) + || HeaderConstants.CACHE_CONTROL_MAX_AGE.equals(elt.getName())) { + return true; } } return false; @@ -517,7 +501,7 @@ public class CachingExec implements ClientExecChain { private String generateViaHeader(final HttpMessage msg) { - final ProtocolVersion pv = msg.getProtocolVersion(); + final ProtocolVersion pv = msg.getVersion() != null ? msg.getVersion() : HttpVersion.DEFAULT; final String existingEntry = viaHeaders.get(pv); if (existingEntry != null) { return existingEntry; @@ -562,13 +546,11 @@ public class CachingExec implements ClientExecChain { } boolean clientRequestsOurOptions(final HttpRequest request) { - final RequestLine line = request.getRequestLine(); - - if (!HeaderConstants.OPTIONS_METHOD.equals(line.getMethod())) { + if (!HeaderConstants.OPTIONS_METHOD.equals(request.getMethod())) { return false; } - if (!"*".equals(line.getUri())) { + if (!"*".equals(request.getRequestUri())) { return false; } @@ -579,16 +561,15 @@ public class CachingExec implements ClientExecChain { return true; } - CloseableHttpResponse callBackend( - final HttpRoute route, - final HttpRequestWrapper request, + ClassicHttpResponse callBackend( + final RoutedHttpRequest request, final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException { final Date requestDate = getCurrentDate(); log.trace("Calling the backend"); - final CloseableHttpResponse backendResponse = backend.execute(route, request, context, execAware); + final ClassicHttpResponse backendResponse = backend.execute(request, context, execAware); try { backendResponse.addHeader("Via", generateViaHeader(backendResponse)); return handleBackendResponse(request, context, requestDate, getCurrentDate(), @@ -620,24 +601,22 @@ public class CachingExec implements ClientExecChain { return false; } - CloseableHttpResponse negotiateResponseFromVariants( - final HttpRoute route, - final HttpRequestWrapper request, + ClassicHttpResponse negotiateResponseFromVariants( + final RoutedHttpRequest request, final HttpClientContext context, final HttpExecutionAware execAware, final Map variants) throws IOException, HttpException { - final HttpRequestWrapper conditionalRequest = conditionalRequestBuilder + final RoutedHttpRequest conditionalRequest = conditionalRequestBuilder .buildConditionalRequestFromVariants(request, variants); final Date requestDate = getCurrentDate(); - final CloseableHttpResponse backendResponse = backend.execute( - route, conditionalRequest, context, execAware); + final ClassicHttpResponse backendResponse = backend.execute(conditionalRequest, context, execAware); try { final Date responseDate = getCurrentDate(); backendResponse.addHeader("Via", generateViaHeader(backendResponse)); - if (backendResponse.getStatusLine().getStatusCode() != HttpStatus.SC_NOT_MODIFIED) { + if (backendResponse.getCode() != HttpStatus.SC_NOT_MODIFIED) { return handleBackendResponse(request, context, requestDate, responseDate, backendResponse); } @@ -647,7 +626,7 @@ public class CachingExec implements ClientExecChain { log.warn("304 response did not contain ETag"); IOUtils.consume(backendResponse.getEntity()); backendResponse.close(); - return callBackend(route, request, context, execAware); + return callBackend(request, context, execAware); } final String resultEtag = resultEtagHeader.getValue(); @@ -656,7 +635,7 @@ public class CachingExec implements ClientExecChain { log.debug("304 response did not contain ETag matching one sent in If-None-Match"); IOUtils.consume(backendResponse.getEntity()); backendResponse.close(); - return callBackend(route, request, context, execAware); + return callBackend(request, context, execAware); } final HttpCacheEntry matchedEntry = matchingVariant.getEntry(); @@ -664,18 +643,18 @@ public class CachingExec implements ClientExecChain { if (revalidationResponseIsTooOld(backendResponse, matchedEntry)) { IOUtils.consume(backendResponse.getEntity()); backendResponse.close(); - return retryRequestUnconditionally(route, request, context, execAware, matchedEntry); + return retryRequestUnconditionally(request, context, execAware); } recordCacheUpdate(context); final HttpCacheEntry responseEntry = getUpdatedVariantEntry( - context.getTargetHost(), conditionalRequest, requestDate, responseDate, + request.getTargetHost(), conditionalRequest, requestDate, responseDate, backendResponse, matchingVariant, matchedEntry); backendResponse.close(); - final CloseableHttpResponse resp = responseGenerator.generateResponse(request, responseEntry); - tryToUpdateVariantMap(context.getTargetHost(), request, matchingVariant); + final ClassicHttpResponse resp = responseGenerator.generateResponse(request, responseEntry); + tryToUpdateVariantMap(request.getTargetHost(), request, matchingVariant); if (shouldSendNotModifiedResponse(request, responseEntry)) { return responseGenerator.generateNotModifiedResponse(responseEntry); @@ -687,23 +666,20 @@ public class CachingExec implements ClientExecChain { } } - private CloseableHttpResponse retryRequestUnconditionally( - final HttpRoute route, - final HttpRequestWrapper request, + private ClassicHttpResponse retryRequestUnconditionally( + final RoutedHttpRequest request, final HttpClientContext context, - final HttpExecutionAware execAware, - final HttpCacheEntry matchedEntry) throws IOException, HttpException { - final HttpRequestWrapper unconditional = conditionalRequestBuilder - .buildUnconditionalRequest(request, matchedEntry); - return callBackend(route, unconditional, context, execAware); + final HttpExecutionAware execAware) throws IOException, HttpException { + final RoutedHttpRequest unconditional = conditionalRequestBuilder.buildUnconditionalRequest(request); + return callBackend(unconditional, context, execAware); } private HttpCacheEntry getUpdatedVariantEntry( final HttpHost target, - final HttpRequestWrapper conditionalRequest, + final RoutedHttpRequest conditionalRequest, final Date requestDate, final Date responseDate, - final CloseableHttpResponse backendResponse, + final ClassicHttpResponse backendResponse, final Variant matchingVariant, final HttpCacheEntry matchedEntry) throws IOException { HttpCacheEntry responseEntry = matchedEntry; @@ -720,7 +696,7 @@ public class CachingExec implements ClientExecChain { private void tryToUpdateVariantMap( final HttpHost target, - final HttpRequestWrapper request, + final RoutedHttpRequest request, final Variant matchingVariant) { try { responseCache.reuseVariantEntryFor(target, request, matchingVariant); @@ -730,53 +706,42 @@ public class CachingExec implements ClientExecChain { } private boolean shouldSendNotModifiedResponse( - final HttpRequestWrapper request, + final RoutedHttpRequest request, final HttpCacheEntry responseEntry) { return (suitabilityChecker.isConditional(request) && suitabilityChecker.allConditionalsMatch(request, responseEntry, new Date())); } - CloseableHttpResponse revalidateCacheEntry( - final HttpRoute route, - final HttpRequestWrapper request, + ClassicHttpResponse revalidateCacheEntry( + final RoutedHttpRequest request, final HttpClientContext context, final HttpExecutionAware execAware, final HttpCacheEntry cacheEntry) throws IOException, HttpException { - final HttpRequestWrapper conditionalRequest = conditionalRequestBuilder.buildConditionalRequest(request, cacheEntry); - final URI uri = conditionalRequest.getURI(); - if (uri != null) { - try { - conditionalRequest.setURI(URIUtils.rewriteURIForRoute(uri, route)); - } catch (final URISyntaxException ex) { - throw new ProtocolException("Invalid URI: " + uri, ex); - } - } + final RoutedHttpRequest conditionalRequest = conditionalRequestBuilder.buildConditionalRequest(request, cacheEntry); Date requestDate = getCurrentDate(); - CloseableHttpResponse backendResponse = backend.execute( - route, conditionalRequest, context, execAware); + ClassicHttpResponse backendResponse = backend.execute(conditionalRequest, context, execAware); Date responseDate = getCurrentDate(); if (revalidationResponseIsTooOld(backendResponse, cacheEntry)) { backendResponse.close(); - final HttpRequestWrapper unconditional = conditionalRequestBuilder - .buildUnconditionalRequest(request, cacheEntry); + final RoutedHttpRequest unconditional = conditionalRequestBuilder.buildUnconditionalRequest(request); requestDate = getCurrentDate(); - backendResponse = backend.execute(route, unconditional, context, execAware); + backendResponse = backend.execute(unconditional, context, execAware); responseDate = getCurrentDate(); } backendResponse.addHeader(HeaderConstants.VIA, generateViaHeader(backendResponse)); - final int statusCode = backendResponse.getStatusLine().getStatusCode(); + final int statusCode = backendResponse.getCode(); if (statusCode == HttpStatus.SC_NOT_MODIFIED || statusCode == HttpStatus.SC_OK) { recordCacheUpdate(context); } if (statusCode == HttpStatus.SC_NOT_MODIFIED) { final HttpCacheEntry updatedEntry = responseCache.updateCacheEntry( - context.getTargetHost(), request, cacheEntry, + request.getTargetHost(), request, cacheEntry, backendResponse, requestDate, responseDate); if (suitabilityChecker.isConditional(request) && suitabilityChecker.allConditionalsMatch(request, updatedEntry, new Date())) { @@ -790,7 +755,7 @@ public class CachingExec implements ClientExecChain { && !staleResponseNotAllowed(request, cacheEntry, getCurrentDate()) && validityPolicy.mayReturnStaleIfError(request, cacheEntry, responseDate)) { try { - final CloseableHttpResponse cachedResponse = responseGenerator.generateResponse(request, cacheEntry); + final ClassicHttpResponse cachedResponse = responseGenerator.generateResponse(request, cacheEntry); cachedResponse.addHeader(HeaderConstants.WARNING, "110 localhost \"Response is stale\""); return cachedResponse; } finally { @@ -808,23 +773,22 @@ public class CachingExec implements ClientExecChain { || statusCode == HttpStatus.SC_GATEWAY_TIMEOUT; } - CloseableHttpResponse handleBackendResponse( - final HttpRequestWrapper request, + ClassicHttpResponse handleBackendResponse( + final RoutedHttpRequest request, final HttpClientContext context, final Date requestDate, final Date responseDate, - final CloseableHttpResponse backendResponse) throws IOException { + final ClassicHttpResponse backendResponse) throws IOException { log.trace("Handling Backend response"); responseCompliance.ensureProtocolCompliance(request, backendResponse); - final HttpHost target = context.getTargetHost(); + final HttpHost target = request.getTargetHost(); final boolean cacheable = responseCachingPolicy.isResponseCacheable(request, backendResponse); responseCache.flushInvalidatedCacheEntriesFor(target, request, backendResponse); if (cacheable && !alreadyHaveNewerCacheEntry(target, request, backendResponse)) { storeRequestIfModifiedSinceFor304Response(request, backendResponse); - return responseCache.cacheAndReturnResponse(target, request, - backendResponse, requestDate, responseDate); + return responseCache.cacheAndReturnResponse(target, request, backendResponse, requestDate, responseDate); } if (!cacheable) { try { @@ -846,7 +810,7 @@ public class CachingExec implements ClientExecChain { */ private void storeRequestIfModifiedSinceFor304Response( final HttpRequest request, final HttpResponse backendResponse) { - if (backendResponse.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_MODIFIED) { + if (backendResponse.getCode() == HttpStatus.SC_NOT_MODIFIED) { final Header h = request.getFirstHeader("If-Modified-Since"); if (h != null) { backendResponse.addHeader("Last-Modified", h.getValue()); @@ -854,7 +818,7 @@ public class CachingExec implements ClientExecChain { } } - private boolean alreadyHaveNewerCacheEntry(final HttpHost target, final HttpRequestWrapper request, + private boolean alreadyHaveNewerCacheEntry(final HttpHost target, final RoutedHttpRequest request, final HttpResponse backendResponse) { HttpCacheEntry existing = null; try { diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingHttpClients.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingHttpClients.java index 89bd816e4..fe7aab2f7 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingHttpClients.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CachingHttpClients.java @@ -30,7 +30,8 @@ package org.apache.hc.client5.http.impl.cache; import java.io.File; import org.apache.hc.client5.http.impl.sync.CloseableHttpClient; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; /** * Factory methods for {@link CloseableHttpClient} instances @@ -38,7 +39,7 @@ import org.apache.hc.core5.annotation.Immutable; * * @since 4.3 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class CachingHttpClients { private CachingHttpClients() { diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CombinedEntity.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CombinedEntity.java index 691866368..b41a32642 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CombinedEntity.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CombinedEntity.java @@ -33,11 +33,9 @@ import java.io.OutputStream; import java.io.SequenceInputStream; import org.apache.hc.client5.http.cache.Resource; -import org.apache.hc.core5.annotation.NotThreadSafe; -import org.apache.hc.core5.http.entity.AbstractHttpEntity; +import org.apache.hc.core5.http.io.entity.AbstractHttpEntity; import org.apache.hc.core5.util.Args; -@NotThreadSafe class CombinedEntity extends AbstractHttpEntity { private final Resource resource; @@ -82,6 +80,11 @@ class CombinedEntity extends AbstractHttpEntity { } } + @Override + public void close() throws IOException { + dispose(); + } + private void dispose() { this.resource.dispose(); } 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 c0fa37069..97b37a7b1 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 @@ -26,12 +26,15 @@ */ package org.apache.hc.client5.http.impl.cache; +import java.util.Iterator; import java.util.Map; import org.apache.hc.client5.http.cache.HeaderConstants; import org.apache.hc.client5.http.cache.HttpCacheEntry; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; +import org.apache.hc.core5.http.message.MessageSupport; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HeaderElement; import org.apache.hc.core5.http.ProtocolException; @@ -39,7 +42,7 @@ import org.apache.hc.core5.http.ProtocolException; /** * @since 4.1 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) class ConditionalRequestBuilder { /** @@ -53,9 +56,9 @@ class ConditionalRequestBuilder { * @return the wrapped request * @throws ProtocolException when I am unable to build a new origin request. */ - public HttpRequestWrapper buildConditionalRequest(final HttpRequestWrapper request, final HttpCacheEntry cacheEntry) + public RoutedHttpRequest buildConditionalRequest(final RoutedHttpRequest request, final HttpCacheEntry cacheEntry) throws ProtocolException { - final HttpRequestWrapper newRequest = HttpRequestWrapper.wrap(request.getOriginal(), request.getTarget()); + final RoutedHttpRequest newRequest = RoutedHttpRequest.adapt(request.getOriginal(), request.getRoute()); newRequest.setHeaders(request.getAllHeaders()); final Header eTag = cacheEntry.getFirstHeader(HeaderConstants.ETAG); if (eTag != null) { @@ -66,13 +69,13 @@ class ConditionalRequestBuilder { newRequest.setHeader(HeaderConstants.IF_MODIFIED_SINCE, lastModified.getValue()); } boolean mustRevalidate = false; - for(final Header h : cacheEntry.getHeaders(HeaderConstants.CACHE_CONTROL)) { - for(final HeaderElement elt : h.getElements()) { - if (HeaderConstants.CACHE_CONTROL_MUST_REVALIDATE.equalsIgnoreCase(elt.getName()) + final Iterator it = MessageSupport.iterate(cacheEntry, HeaderConstants.CACHE_CONTROL); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + if (HeaderConstants.CACHE_CONTROL_MUST_REVALIDATE.equalsIgnoreCase(elt.getName()) || HeaderConstants.CACHE_CONTROL_PROXY_REVALIDATE.equalsIgnoreCase(elt.getName())) { - mustRevalidate = true; - break; - } + mustRevalidate = true; + break; } } if (mustRevalidate) { @@ -93,9 +96,9 @@ class ConditionalRequestBuilder { * @param variants * @return the wrapped request */ - public HttpRequestWrapper buildConditionalRequestFromVariants(final HttpRequestWrapper request, - final Map variants) { - final HttpRequestWrapper newRequest = HttpRequestWrapper.wrap(request.getOriginal(), request.getTarget()); + public RoutedHttpRequest buildConditionalRequestFromVariants(final RoutedHttpRequest request, + final Map variants) { + final RoutedHttpRequest newRequest = RoutedHttpRequest.adapt(request.getOriginal(), request.getRoute()); newRequest.setHeaders(request.getAllHeaders()); // we do not support partial content so all etags are used @@ -121,11 +124,10 @@ class ConditionalRequestBuilder { * our current cache entry. In this case, the protocol recommendation * is to retry the validation and force syncup with the origin. * @param request client request we are trying to satisfy - * @param entry existing cache entry we are trying to validate * @return an unconditional validation request */ - public HttpRequestWrapper buildUnconditionalRequest(final HttpRequestWrapper request, final HttpCacheEntry entry) { - final HttpRequestWrapper newRequest = HttpRequestWrapper.wrap(request.getOriginal(), request.getTarget()); + public RoutedHttpRequest buildUnconditionalRequest(final RoutedHttpRequest request) { + final RoutedHttpRequest newRequest = RoutedHttpRequest.adapt(request.getOriginal(), request.getRoute()); newRequest.setHeaders(request.getAllHeaders()); newRequest.addHeader(HeaderConstants.CACHE_CONTROL,HeaderConstants.CACHE_CONTROL_NO_CACHE); newRequest.addHeader(HeaderConstants.PRAGMA,HeaderConstants.CACHE_CONTROL_NO_CACHE); diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/DefaultFailureCache.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/DefaultFailureCache.java index 3e3df41ff..7170d9926 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/DefaultFailureCache.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/DefaultFailureCache.java @@ -30,7 +30,8 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -import org.apache.hc.core5.annotation.ThreadSafe; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; /** * Implements a bounded failure cache. The oldest entries are discarded when @@ -38,7 +39,7 @@ import org.apache.hc.core5.annotation.ThreadSafe; * * @since 4.3 */ -@ThreadSafe +@Contract(threading = ThreadingBehavior.SAFE) public class DefaultFailureCache implements FailureCache { static final int DEFAULT_MAX_SIZE = 1000; diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/DefaultHttpCacheEntrySerializer.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/DefaultHttpCacheEntrySerializer.java index 0bd503b08..778375eaf 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/DefaultHttpCacheEntrySerializer.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/DefaultHttpCacheEntrySerializer.java @@ -35,7 +35,8 @@ import java.io.OutputStream; import org.apache.hc.client5.http.cache.HttpCacheEntry; import org.apache.hc.client5.http.cache.HttpCacheEntrySerializationException; import org.apache.hc.client5.http.cache.HttpCacheEntrySerializer; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; /** * {@link HttpCacheEntrySerializer} implementation that uses the default (native) @@ -45,7 +46,7 @@ import org.apache.hc.core5.annotation.Immutable; * * @since 4.1 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class DefaultHttpCacheEntrySerializer implements HttpCacheEntrySerializer { @Override diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ExponentialBackOffSchedulingStrategy.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ExponentialBackOffSchedulingStrategy.java index 2ec45be61..921d49e9c 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ExponentialBackOffSchedulingStrategy.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ExponentialBackOffSchedulingStrategy.java @@ -30,7 +30,8 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; -import org.apache.hc.core5.annotation.ThreadSafe; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.util.Args; /** @@ -56,7 +57,7 @@ import org.apache.hc.core5.util.Args; * * @since 4.3 */ -@ThreadSafe +@Contract(threading = ThreadingBehavior.SAFE) public class ExponentialBackOffSchedulingStrategy implements SchedulingStrategy { public static final long DEFAULT_BACK_OFF_RATE = 10; diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/FailureCacheValue.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/FailureCacheValue.java index 11931b1d8..32f7702b6 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/FailureCacheValue.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/FailureCacheValue.java @@ -26,14 +26,15 @@ */ package org.apache.hc.client5.http.impl.cache; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; /** * The error count with a creation timestamp and its associated key. * * @since 4.3 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class FailureCacheValue { private final long creationTimeInNanos; diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/FileResource.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/FileResource.java index 2b16954ae..e92ae9a65 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/FileResource.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/FileResource.java @@ -32,14 +32,15 @@ import java.io.IOException; import java.io.InputStream; import org.apache.hc.client5.http.cache.Resource; -import org.apache.hc.core5.annotation.ThreadSafe; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; /** * Cache resource backed by a file. * * @since 4.1 */ -@ThreadSafe +@Contract(threading = ThreadingBehavior.SAFE) public class FileResource implements Resource { private static final long serialVersionUID = 4132244415919043397L; diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/FileResourceFactory.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/FileResourceFactory.java index 8d9755d22..253385af4 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/FileResourceFactory.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/FileResourceFactory.java @@ -34,14 +34,15 @@ import java.io.InputStream; import org.apache.hc.client5.http.cache.InputLimit; import org.apache.hc.client5.http.cache.Resource; import org.apache.hc.client5.http.cache.ResourceFactory; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; /** * Generates {@link Resource} instances whose body is stored in a temporary file. * * @since 4.1 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class FileResourceFactory implements ResourceFactory { private final File cacheDir; diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/HeapResource.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/HeapResource.java index f1b51cb88..bbb0bee27 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/HeapResource.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/HeapResource.java @@ -30,14 +30,15 @@ import java.io.ByteArrayInputStream; import java.io.InputStream; import org.apache.hc.client5.http.cache.Resource; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; /** * Cache resource backed by a byte array on the heap. * * @since 4.1 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class HeapResource implements Resource { private static final long serialVersionUID = -2078599905620463394L; diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/HeapResourceFactory.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/HeapResourceFactory.java index 946db58dc..b3528a05c 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/HeapResourceFactory.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/HeapResourceFactory.java @@ -33,14 +33,15 @@ import java.io.InputStream; import org.apache.hc.client5.http.cache.InputLimit; import org.apache.hc.client5.http.cache.Resource; import org.apache.hc.client5.http.cache.ResourceFactory; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; /** * Generates {@link Resource} instances stored entirely in heap. * * @since 4.1 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class HeapResourceFactory implements ResourceFactory { @Override diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/HttpCache.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/HttpCache.java index 3a6679fa2..d2cf58e63 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/HttpCache.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/HttpCache.java @@ -31,7 +31,7 @@ import java.util.Date; import java.util.Map; import org.apache.hc.client5.http.cache.HttpCacheEntry; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.HttpResponse; @@ -99,24 +99,9 @@ interface HttpCache { * @return the {@link HttpResponse} * @throws IOException */ - HttpResponse cacheAndReturnResponse( - HttpHost host, HttpRequest request, HttpResponse originResponse, - Date requestSent, Date responseReceived) - throws IOException; - - /** - * Store a {@link HttpResponse} in the cache if possible, and return - * @param host - * @param request - * @param originResponse - * @param requestSent - * @param responseReceived - * @return the {@link HttpResponse} - * @throws IOException - */ - CloseableHttpResponse cacheAndReturnResponse(HttpHost host, - HttpRequest request, CloseableHttpResponse originResponse, - Date requestSent, Date responseReceived) + ClassicHttpResponse cacheAndReturnResponse(HttpHost host, + HttpRequest request, ClassicHttpResponse originResponse, + Date requestSent, Date responseReceived) throws IOException; /** diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/IOUtils.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/IOUtils.java index 1c89d3318..551b998ea 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/IOUtils.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/IOUtils.java @@ -34,10 +34,11 @@ import java.io.OutputStream; import java.io.RandomAccessFile; import java.nio.channels.FileChannel; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.HttpEntity; -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) class IOUtils { static void consume(final HttpEntity entity) throws IOException { diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ImmediateSchedulingStrategy.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ImmediateSchedulingStrategy.java index e6ffadf2d..f38b06170 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ImmediateSchedulingStrategy.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ImmediateSchedulingStrategy.java @@ -31,7 +31,8 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; -import org.apache.hc.core5.annotation.ThreadSafe; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.util.Args; /** @@ -40,7 +41,7 @@ import org.apache.hc.core5.util.Args; * * @since 4.3 */ -@ThreadSafe +@Contract(threading = ThreadingBehavior.SAFE) public class ImmediateSchedulingStrategy implements SchedulingStrategy { private final ExecutorService executor; diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ManagedHttpCacheStorage.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ManagedHttpCacheStorage.java index 6217646af..ed5ff10d8 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ManagedHttpCacheStorage.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ManagedHttpCacheStorage.java @@ -37,7 +37,8 @@ import org.apache.hc.client5.http.cache.HttpCacheEntry; import org.apache.hc.client5.http.cache.HttpCacheStorage; import org.apache.hc.client5.http.cache.HttpCacheUpdateCallback; import org.apache.hc.client5.http.cache.Resource; -import org.apache.hc.core5.annotation.ThreadSafe; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.util.Args; /** @@ -70,7 +71,7 @@ import org.apache.hc.core5.util.Args; * * @since 4.1 */ -@ThreadSafe +@Contract(threading = ThreadingBehavior.SAFE) public class ManagedHttpCacheStorage implements HttpCacheStorage, Closeable { private final CacheMap entries; diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/OptionsHttp11Response.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/OptionsHttp11Response.java index 737f37a50..9a4250746 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/OptionsHttp11Response.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/OptionsHttp11Response.java @@ -26,73 +26,60 @@ */ package org.apache.hc.client5.http.impl.cache; +import java.io.IOException; +import java.io.Serializable; +import java.util.Collections; import java.util.Iterator; import java.util.Locale; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; +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.HttpResponse; import org.apache.hc.core5.http.HttpStatus; import org.apache.hc.core5.http.HttpVersion; +import org.apache.hc.core5.http.ProtocolException; import org.apache.hc.core5.http.ProtocolVersion; -import org.apache.hc.core5.http.StatusLine; -import org.apache.hc.core5.http.message.AbstractHttpMessage; -import org.apache.hc.core5.http.message.BasicStatusLine; /** * @since 4.1 */ -@Immutable -final class OptionsHttp11Response extends AbstractHttpMessage implements HttpResponse { +@Contract(threading = ThreadingBehavior.IMMUTABLE) +final class OptionsHttp11Response implements ClassicHttpResponse, Serializable { private static final long serialVersionUID = 1L; - private final StatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1, - HttpStatus.SC_NOT_IMPLEMENTED, ""); - private final ProtocolVersion version = HttpVersion.HTTP_1_1; - - @Override - public StatusLine getStatusLine() { - return statusLine; - } @Override public int getCode() { - return statusLine.getStatusCode(); + return HttpStatus.SC_NOT_IMPLEMENTED; } @Override - public void setStatusLine(final StatusLine statusline) { - // No-op on purpose, this class is not going to be doing any work. + public void setCode(final int code) { } @Override - public void setStatusLine(final ProtocolVersion ver, final int code) { - // No-op on purpose, this class is not going to be doing any work. - } - - @Override - public void setStatusLine(final ProtocolVersion ver, final int code, final String reason) { - // No-op on purpose, this class is not going to be doing any work. - } - - @Override - public void setStatusCode(final int code) throws IllegalStateException { - // No-op on purpose, this class is not going to be doing any work. - } - - @Override - public void setReasonPhrase(final String reason) throws IllegalStateException { - // No-op on purpose, this class is not going to be doing any work. - } - - @Override - public HttpEntity getEntity() { + public String getReasonPhrase() { return null; } @Override - public void setEntity(final HttpEntity entity) { + public void setVersion(final ProtocolVersion version) { + } + + @Override + public int containsHeaders(final String name) { + return 0; + } + + @Override + public Header getSingleHeader(final String name) throws ProtocolException { + return null; + } + + @Override + public void setReasonPhrase(final String reason) throws IllegalStateException { // No-op on purpose, this class is not going to be doing any work. } @@ -107,33 +94,33 @@ final class OptionsHttp11Response extends AbstractHttpMessage implements HttpRes } @Override - public ProtocolVersion getProtocolVersion() { - return version; + public ProtocolVersion getVersion() { + return HttpVersion.HTTP_1_1; } @Override public boolean containsHeader(final String name) { - return super.containsHeader(name); + return false; } @Override public Header[] getHeaders(final String name) { - return super.getHeaders(name); + return null; } @Override public Header getFirstHeader(final String name) { - return super.getFirstHeader(name); + return null; } @Override public Header getLastHeader(final String name) { - return super.getLastHeader(name); + return null; } @Override public Header[] getAllHeaders() { - return super.getAllHeaders(); + return null; } @Override @@ -173,13 +160,25 @@ final class OptionsHttp11Response extends AbstractHttpMessage implements HttpRes @Override public Iterator
headerIterator() { - return super.headerIterator(); + return Collections.emptyIterator(); } @Override public Iterator
headerIterator(final String name) { - return super.headerIterator(name); + return Collections.emptyIterator(); } + @Override + public HttpEntity getEntity() { + return null; + } + + @Override + public void setEntity(final HttpEntity entity) { + } + + @Override + public void close() throws IOException { + } } diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/Proxies.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/Proxies.java deleted file mode 100644 index c71622ce7..000000000 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/Proxies.java +++ /dev/null @@ -1,56 +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 - * . - * - */ -package org.apache.hc.client5.http.impl.cache; - -import java.lang.reflect.Proxy; - -import org.apache.hc.client5.http.methods.CloseableHttpResponse; -import org.apache.hc.core5.annotation.NotThreadSafe; -import org.apache.hc.core5.http.HttpResponse; -import org.apache.hc.core5.util.Args; - -/** - * Proxies for HTTP message objects. - * - * @since 4.3 - */ -@NotThreadSafe -class Proxies { - - public static CloseableHttpResponse enhanceResponse(final HttpResponse original) { - Args.notNull(original, "HTTP response"); - if (original instanceof CloseableHttpResponse) { - return (CloseableHttpResponse) original; - } else { - return (CloseableHttpResponse) Proxy.newProxyInstance( - ResponseProxyHandler.class.getClassLoader(), - new Class[] { CloseableHttpResponse.class }, - new ResponseProxyHandler(original)); - } - } - -} 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 index 34f435bcf..96e56cae7 100644 --- 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 @@ -28,32 +28,34 @@ package org.apache.hc.client5.http.impl.cache; import java.util.ArrayList; import java.util.Arrays; +import java.util.Iterator; import java.util.List; import org.apache.hc.client5.http.cache.HeaderConstants; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.ClientProtocolException; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; +import org.apache.hc.core5.http.ClassicHttpResponse; +import org.apache.hc.core5.http.ContentType; 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.http.HttpEntity; 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.HttpStatus; import org.apache.hc.core5.http.HttpVersion; import org.apache.hc.core5.http.ProtocolVersion; -import org.apache.hc.core5.http.entity.AbstractHttpEntity; -import org.apache.hc.core5.http.entity.ContentType; +import org.apache.hc.core5.http.io.entity.AbstractHttpEntity; +import org.apache.hc.core5.http.message.BasicClassicHttpResponse; import org.apache.hc.core5.http.message.BasicHeader; -import org.apache.hc.core5.http.message.BasicHttpResponse; -import org.apache.hc.core5.http.message.BasicStatusLine; +import org.apache.hc.core5.http.message.MessageSupport; /** * @since 4.1 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) class RequestProtocolCompliance { private final boolean weakETagOnPutDeleteAllowed; @@ -107,7 +109,7 @@ class RequestProtocolCompliance { * @param request the request to check for compliance * @throws ClientProtocolException when we have trouble making the request compliant */ - public void makeRequestCompliant(final HttpRequestWrapper request) + public void makeRequestCompliant(final RoutedHttpRequest request) throws ClientProtocolException { if (requestMustNotHaveEntity(request)) { @@ -119,23 +121,22 @@ class RequestProtocolCompliance { decrementOPTIONSMaxForwardsIfGreaterThen0(request); stripOtherFreshnessDirectivesWithNoCache(request); - if (requestVersionIsTooLow(request) - || requestMinorVersionIsTooHighMajorVersionsMatch(request)) { - request.setProtocolVersion(HttpVersion.HTTP_1_1); + if (requestVersionIsTooLow(request) || requestMinorVersionIsTooHighMajorVersionsMatch(request)) { + request.setVersion(HttpVersion.HTTP_1_1); } } private void stripOtherFreshnessDirectivesWithNoCache(final HttpRequest request) { final List outElts = new ArrayList<>(); boolean shouldStrip = false; - for(final Header h : request.getHeaders(HeaderConstants.CACHE_CONTROL)) { - for(final HeaderElement elt : h.getElements()) { - if (!disallowedWithNoCache.contains(elt.getName())) { - outElts.add(elt); - } - if (HeaderConstants.CACHE_CONTROL_NO_CACHE.equals(elt.getName())) { - shouldStrip = true; - } + final Iterator it = MessageSupport.iterate(request, HeaderConstants.CACHE_CONTROL); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + if (!disallowedWithNoCache.contains(elt.getName())) { + outElts.add(elt); + } + if (HeaderConstants.CACHE_CONTROL_NO_CACHE.equals(elt.getName())) { + shouldStrip = true; } } if (!shouldStrip) { @@ -160,11 +161,11 @@ class RequestProtocolCompliance { } private boolean requestMustNotHaveEntity(final HttpRequest request) { - return HeaderConstants.TRACE_METHOD.equals(request.getRequestLine().getMethod()); + return HeaderConstants.TRACE_METHOD.equals(request.getMethod()); } private void decrementOPTIONSMaxForwardsIfGreaterThen0(final HttpRequest request) { - if (!HeaderConstants.OPTIONS_METHOD.equals(request.getRequestLine().getMethod())) { + if (!HeaderConstants.OPTIONS_METHOD.equals(request.getMethod())) { return; } @@ -179,22 +180,22 @@ class RequestProtocolCompliance { request.setHeader(HeaderConstants.MAX_FORWARDS, Integer.toString(currentMaxForwards - 1)); } - private void verifyOPTIONSRequestWithBodyHasContentType(final HttpRequest request) { - if (!HeaderConstants.OPTIONS_METHOD.equals(request.getRequestLine().getMethod())) { + private void verifyOPTIONSRequestWithBodyHasContentType(final RoutedHttpRequest request) { + if (!HeaderConstants.OPTIONS_METHOD.equals(request.getMethod())) { return; } addContentTypeHeaderIfMissing(request); } - private void addContentTypeHeaderIfMissing(final HttpRequest request) { + private void addContentTypeHeaderIfMissing(final RoutedHttpRequest request) { final HttpEntity entity = request.getEntity(); if (entity != null && entity.getContentType() == null) { ((AbstractHttpEntity) entity).setContentType(ContentType.APPLICATION_OCTET_STREAM.getMimeType()); } } - private void verifyRequestWithExpectContinueFlagHas100continueHeader(final HttpRequest request) { + private void verifyRequestWithExpectContinueFlagHas100continueHeader(final RoutedHttpRequest request) { if (request.containsHeader(HttpHeaders.EXPECT) && request.getEntity() != null) { add100ContinueHeaderIfMissing(request); } else { @@ -209,7 +210,7 @@ class RequestProtocolCompliance { List expectElementsThatAreNot100Continue = new ArrayList<>(); for (final Header h : expectHeaders) { - for (final HeaderElement elt : h.getElements()) { + for (final HeaderElement elt : MessageSupport.parse(h)) { if (!(HeaderElements.CONTINUE.equalsIgnoreCase(elt.getName()))) { expectElementsThatAreNot100Continue.add(elt); } else { @@ -233,11 +234,11 @@ class RequestProtocolCompliance { private void add100ContinueHeaderIfMissing(final HttpRequest request) { boolean hasHeader = false; - for (final Header h : request.getHeaders(HttpHeaders.EXPECT)) { - for (final HeaderElement elt : h.getElements()) { - if (HeaderElements.CONTINUE.equalsIgnoreCase(elt.getName())) { - hasHeader = true; - } + final Iterator it = MessageSupport.iterate(request, HttpHeaders.EXPECT); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + if (HeaderElements.CONTINUE.equalsIgnoreCase(elt.getName())) { + hasHeader = true; } } @@ -247,7 +248,7 @@ class RequestProtocolCompliance { } protected boolean requestMinorVersionIsTooHighMajorVersionsMatch(final HttpRequest request) { - final ProtocolVersion requestProtocol = request.getProtocolVersion(); + final ProtocolVersion requestProtocol = request.getVersion(); if (requestProtocol.getMajor() != HttpVersion.HTTP_1_1.getMajor()) { return false; } @@ -260,7 +261,7 @@ class RequestProtocolCompliance { } protected boolean requestVersionIsTooLow(final HttpRequest request) { - return request.getProtocolVersion().compareToVersion(HttpVersion.HTTP_1_1) < 0; + return request.getVersion().compareToVersion(HttpVersion.HTTP_1_1) < 0; } /** @@ -268,27 +269,24 @@ class RequestProtocolCompliance { * that a problem occured. * * @param errorCheck What type of error should I get - * @return The {@link HttpResponse} that is the error generated + * @return The {@link ClassicHttpResponse} that is the error generated */ - public HttpResponse getErrorForRequest(final RequestProtocolError errorCheck) { + public ClassicHttpResponse getErrorForRequest(final RequestProtocolError errorCheck) { switch (errorCheck) { case BODY_BUT_NO_LENGTH_ERROR: - return new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, - HttpStatus.SC_LENGTH_REQUIRED, "")); + return new BasicClassicHttpResponse(HttpStatus.SC_LENGTH_REQUIRED, ""); case WEAK_ETAG_AND_RANGE_ERROR: - return new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, - HttpStatus.SC_BAD_REQUEST, "Weak eTag not compatible with byte range")); + return new BasicClassicHttpResponse(HttpStatus.SC_BAD_REQUEST, + "Weak eTag not compatible with byte range"); case WEAK_ETAG_ON_PUTDELETE_METHOD_ERROR: - return new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, - HttpStatus.SC_BAD_REQUEST, - "Weak eTag not compatible with PUT or DELETE requests")); + return new BasicClassicHttpResponse(HttpStatus.SC_BAD_REQUEST, + "Weak eTag not compatible with PUT or DELETE requests"); case NO_CACHE_DIRECTIVE_WITH_FIELD_NAME: - return new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, - HttpStatus.SC_BAD_REQUEST, - "No-Cache directive MUST NOT include a field name")); + return new BasicClassicHttpResponse(HttpStatus.SC_BAD_REQUEST, + "No-Cache directive MUST NOT include a field name"); default: throw new IllegalStateException( @@ -299,7 +297,7 @@ class RequestProtocolCompliance { private RequestProtocolError requestHasWeakETagAndRange(final HttpRequest request) { // TODO: Should these be looking at all the headers marked as Range? - final String method = request.getRequestLine().getMethod(); + final String method = request.getMethod(); if (!(HeaderConstants.GET_METHOD.equals(method))) { return null; } @@ -325,9 +323,8 @@ class RequestProtocolCompliance { private RequestProtocolError requestHasWeekETagForPUTOrDELETEIfMatch(final HttpRequest request) { // TODO: Should these be looking at all the headers marked as If-Match/If-None-Match? - final String method = request.getRequestLine().getMethod(); - if (!(HeaderConstants.PUT_METHOD.equals(method) || HeaderConstants.DELETE_METHOD - .equals(method))) { + final String method = request.getMethod(); + if (!(HeaderConstants.PUT_METHOD.equals(method) || HeaderConstants.DELETE_METHOD.equals(method))) { return null; } @@ -353,12 +350,11 @@ class RequestProtocolCompliance { } private RequestProtocolError requestContainsNoCacheDirectiveWithFieldName(final HttpRequest request) { - for(final Header h : request.getHeaders(HeaderConstants.CACHE_CONTROL)) { - for(final HeaderElement elt : h.getElements()) { - if (HeaderConstants.CACHE_CONTROL_NO_CACHE.equalsIgnoreCase(elt.getName()) - && elt.getValue() != null) { - return RequestProtocolError.NO_CACHE_DIRECTIVE_WITH_FIELD_NAME; - } + final Iterator it = MessageSupport.iterate(request, HeaderConstants.CACHE_CONTROL); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + if (HeaderConstants.CACHE_CONTROL_NO_CACHE.equalsIgnoreCase(elt.getName()) && elt.getValue() != null) { + return RequestProtocolError.NO_CACHE_DIRECTIVE_WITH_FIELD_NAME; } } return null; diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ResourceReference.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ResourceReference.java index 9cdd674b0..502e13e90 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ResourceReference.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ResourceReference.java @@ -31,10 +31,11 @@ import java.lang.ref.ReferenceQueue; import org.apache.hc.client5.http.cache.HttpCacheEntry; import org.apache.hc.client5.http.cache.Resource; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.util.Args; -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) class ResourceReference extends PhantomReference { private final Resource resource; 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 bf59560c0..4ef532be0 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 @@ -29,13 +29,15 @@ package org.apache.hc.client5.http.impl.cache; import java.util.Arrays; import java.util.Date; import java.util.HashSet; +import java.util.Iterator; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hc.client5.http.cache.HeaderConstants; import org.apache.hc.client5.http.utils.DateUtils; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HeaderElement; import org.apache.hc.core5.http.HttpHeaders; @@ -44,13 +46,15 @@ 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.HttpVersion; +import org.apache.hc.core5.http.ProtocolVersion; +import org.apache.hc.core5.http.message.MessageSupport; /** * Determines if an HttpResponse can be cached. * * @since 4.1 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) class ResponseCachingPolicy { private static final String[] AUTH_CACHEABLE_PARAMS = { @@ -111,7 +115,7 @@ class ResponseCachingPolicy { return false; } - final int status = response.getStatusLine().getStatusCode(); + final int status = response.getCode(); if (cacheableStatuses.contains(status)) { // these response codes MAY be cached cacheable = true; @@ -154,11 +158,11 @@ class ResponseCachingPolicy { return false; } - for (final Header varyHdr : response.getHeaders(HeaderConstants.VARY)) { - for (final HeaderElement elem : varyHdr.getElements()) { - if ("*".equals(elem.getName())) { - return false; - } + final Iterator it = MessageSupport.iterate(response, HeaderConstants.VARY); + while (it.hasNext()) { + final HeaderElement elem = it.next(); + if ("*".equals(elem.getName())) { + return false; } } @@ -189,27 +193,25 @@ class ResponseCachingPolicy { } protected boolean isExplicitlyNonCacheable(final HttpResponse response) { - final Header[] cacheControlHeaders = response.getHeaders(HeaderConstants.CACHE_CONTROL); - for (final Header header : cacheControlHeaders) { - for (final HeaderElement elem : header.getElements()) { - if (HeaderConstants.CACHE_CONTROL_NO_STORE.equals(elem.getName()) - || HeaderConstants.CACHE_CONTROL_NO_CACHE.equals(elem.getName()) - || (sharedCache && HeaderConstants.PRIVATE.equals(elem.getName()))) { - return true; - } + final Iterator it = MessageSupport.iterate(response, HeaderConstants.CACHE_CONTROL); + while (it.hasNext()) { + final HeaderElement elem = it.next(); + if (HeaderConstants.CACHE_CONTROL_NO_STORE.equals(elem.getName()) + || HeaderConstants.CACHE_CONTROL_NO_CACHE.equals(elem.getName()) + || (sharedCache && HeaderConstants.PRIVATE.equals(elem.getName()))) { + return true; } } return false; } protected boolean hasCacheControlParameterFrom(final HttpMessage msg, final String[] params) { - final Header[] cacheControlHeaders = msg.getHeaders(HeaderConstants.CACHE_CONTROL); - for (final Header header : cacheControlHeaders) { - for (final HeaderElement elem : header.getElements()) { - for (final String param : params) { - if (param.equalsIgnoreCase(elem.getName())) { - return true; - } + final Iterator it = MessageSupport.iterate(msg, HeaderConstants.CACHE_CONTROL); + while (it.hasNext()) { + final HeaderElement elem = it.next(); + for (final String param : params) { + if (param.equalsIgnoreCase(elem.getName())) { + return true; } } } @@ -247,7 +249,7 @@ class ResponseCachingPolicy { return false; } - if (request.getRequestLine().getUri().contains("?")) { + if (request.getRequestUri().contains("?")) { if (neverCache1_0ResponsesWithQueryString && from1_0Origin(response)) { log.debug("Response was not cacheable as it had a query string."); return false; @@ -269,7 +271,7 @@ class ResponseCachingPolicy { } } - final String method = request.getRequestLine().getMethod(); + final String method = request.getMethod(); return isResponseCacheable(method, response); } @@ -292,22 +294,23 @@ class ResponseCachingPolicy { } private boolean from1_0Origin(final HttpResponse response) { - final Header via = response.getFirstHeader(HeaderConstants.VIA); - if (via != null) { - for(final HeaderElement elt : via.getElements()) { - final String proto = elt.toString().split("\\s")[0]; - if (proto.contains("/")) { - return proto.equals("HTTP/1.0"); - } else { - return proto.equals("1.0"); - } + final Iterator it = MessageSupport.iterate(response, HeaderConstants.VIA); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + final String proto = elt.toString().split("\\s")[0]; + if (proto.contains("/")) { + return proto.equals("HTTP/1.0"); + } else { + return proto.equals("1.0"); } } - return HttpVersion.HTTP_1_0.equals(response.getProtocolVersion()); + final ProtocolVersion version = response.getVersion() != null ? response.getVersion() : HttpVersion.DEFAULT; + return HttpVersion.HTTP_1_0.equals(version); } private boolean requestProtocolGreaterThanAccepted(final HttpRequest req) { - return req.getProtocolVersion().compareToVersion(HttpVersion.HTTP_1_1) > 0; + final ProtocolVersion version = req.getVersion() != null ? req.getVersion() : HttpVersion.DEFAULT; + return version.compareToVersion(HttpVersion.HTTP_1_1) > 0; } } 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 ba7c89f83..816e38bbd 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 @@ -32,10 +32,12 @@ import java.util.Date; import java.util.List; import org.apache.hc.client5.http.cache.HeaderConstants; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.ClientProtocolException; import org.apache.hc.client5.http.utils.DateUtils; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; +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.HeaderElements; @@ -45,12 +47,14 @@ 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.HttpVersion; +import org.apache.hc.core5.http.ProtocolVersion; import org.apache.hc.core5.http.message.BasicHeader; +import org.apache.hc.core5.http.message.MessageSupport; /** * @since 4.1 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) class ResponseProtocolCompliance { private static final String UNEXPECTED_100_CONTINUE = "The incoming request did not contain a " @@ -66,7 +70,7 @@ class ResponseProtocolCompliance { * @param response The {@link HttpResponse} from the origin server * @throws IOException Bad things happened */ - public void ensureProtocolCompliance(final HttpRequestWrapper request, final HttpResponse response) + public void ensureProtocolCompliance(final RoutedHttpRequest request, final ClassicHttpResponse response) throws IOException { if (backendResponseMustNotHaveBody(request, response)) { consumeBody(response); @@ -90,7 +94,7 @@ class ResponseProtocolCompliance { warningsWithNonMatchingWarnDatesAreRemoved(response); } - private void consumeBody(final HttpResponse response) throws IOException { + private void consumeBody(final ClassicHttpResponse response) throws IOException { final HttpEntity body = response.getEntity(); if (body != null) { IOUtils.consume(body); @@ -140,7 +144,7 @@ class ResponseProtocolCompliance { for (final Header h : hdrs) { final StringBuilder buf = new StringBuilder(); boolean first = true; - for (final HeaderElement elt : h.getElements()) { + for (final HeaderElement elt : MessageSupport.parse(h)) { if ("identity".equalsIgnoreCase(elt.getName())) { modified = true; } else { @@ -173,9 +177,9 @@ class ResponseProtocolCompliance { } private void ensurePartialContentIsNotSentToAClientThatDidNotRequestIt(final HttpRequest request, - final HttpResponse response) throws IOException { + final ClassicHttpResponse response) throws IOException { if (request.getFirstHeader(HeaderConstants.RANGE) != null - || response.getStatusLine().getStatusCode() != HttpStatus.SC_PARTIAL_CONTENT) { + || response.getCode() != HttpStatus.SC_PARTIAL_CONTENT) { return; } @@ -185,11 +189,11 @@ class ResponseProtocolCompliance { private void ensure200ForOPTIONSRequestWithNoBodyHasContentLengthZero(final HttpRequest request, final HttpResponse response) { - if (!request.getRequestLine().getMethod().equalsIgnoreCase(HeaderConstants.OPTIONS_METHOD)) { + if (!request.getMethod().equalsIgnoreCase(HeaderConstants.OPTIONS_METHOD)) { return; } - if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { + if (response.getCode() != HttpStatus.SC_OK) { return; } @@ -203,7 +207,7 @@ class ResponseProtocolCompliance { "Content-Language", HttpHeaders.CONTENT_LENGTH, "Content-MD5", "Content-Range", HttpHeaders.CONTENT_TYPE, HeaderConstants.LAST_MODIFIED }; - if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_MODIFIED) { + if (response.getCode() == HttpStatus.SC_NOT_MODIFIED) { for(final String hdr : disallowedEntityHeaders) { response.removeHeaders(hdr); } @@ -211,15 +215,15 @@ class ResponseProtocolCompliance { } private boolean backendResponseMustNotHaveBody(final HttpRequest request, final HttpResponse backendResponse) { - return HeaderConstants.HEAD_METHOD.equals(request.getRequestLine().getMethod()) - || backendResponse.getStatusLine().getStatusCode() == HttpStatus.SC_NO_CONTENT - || backendResponse.getStatusLine().getStatusCode() == HttpStatus.SC_RESET_CONTENT - || backendResponse.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_MODIFIED; + return HeaderConstants.HEAD_METHOD.equals(request.getMethod()) + || backendResponse.getCode() == HttpStatus.SC_NO_CONTENT + || backendResponse.getCode() == HttpStatus.SC_RESET_CONTENT + || backendResponse.getCode() == HttpStatus.SC_NOT_MODIFIED; } - private void requestDidNotExpect100ContinueButResponseIsOne(final HttpRequestWrapper request, - final HttpResponse response) throws IOException { - if (response.getStatusLine().getStatusCode() != HttpStatus.SC_CONTINUE) { + private void requestDidNotExpect100ContinueButResponseIsOne(final RoutedHttpRequest request, + final ClassicHttpResponse response) throws IOException { + if (response.getCode() != HttpStatus.SC_CONTINUE) { return; } @@ -232,10 +236,11 @@ class ResponseProtocolCompliance { throw new ClientProtocolException(UNEXPECTED_100_CONTINUE); } - private void transferEncodingIsNotReturnedTo1_0Client(final HttpRequestWrapper request, + private void transferEncodingIsNotReturnedTo1_0Client(final RoutedHttpRequest request, final HttpResponse response) { final HttpRequest originalRequest = request.getOriginal(); - if (originalRequest.getProtocolVersion().compareToVersion(HttpVersion.HTTP_1_1) >= 0) { + final ProtocolVersion version = originalRequest.getVersion() != null ? originalRequest.getVersion() : HttpVersion.DEFAULT; + if (version.compareToVersion(HttpVersion.HTTP_1_1) >= 0) { return; } diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ResponseProxyHandler.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ResponseProxyHandler.java deleted file mode 100644 index 715974d8f..000000000 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ResponseProxyHandler.java +++ /dev/null @@ -1,89 +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 - * . - * - */ - -package org.apache.hc.client5.http.impl.cache; - -import java.io.Closeable; -import java.io.IOException; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -import org.apache.hc.core5.annotation.NotThreadSafe; -import org.apache.hc.core5.http.HttpResponse; - -/** - * A proxy class that can enhance an arbitrary {@link HttpResponse} with - * {@link Closeable#close()} method. - * - * @since 4.3 - */ -@NotThreadSafe -class ResponseProxyHandler implements InvocationHandler { - - private static final Method CLOSE_METHOD; - - static { - try { - CLOSE_METHOD = Closeable.class.getMethod("close"); - } catch (final NoSuchMethodException ex) { - throw new Error(ex); - } - } - - private final HttpResponse original; - - ResponseProxyHandler(final HttpResponse original) { - super(); - this.original = original; - } - - public void close() throws IOException { - IOUtils.consume(original.getEntity()); - } - - @Override - public Object invoke( - final Object proxy, final Method method, final Object[] args) throws Throwable { - if (method.equals(CLOSE_METHOD)) { - close(); - return null; - } else { - try { - return method.invoke(this.original, args); - } catch (final InvocationTargetException ex) { - final Throwable cause = ex.getCause(); - if (cause != null) { - throw cause; - } else { - throw ex; - } - } - } - } - -} diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/SizeLimitedResponseReader.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/SizeLimitedResponseReader.java index 61ca82404..56a725932 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/SizeLimitedResponseReader.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/SizeLimitedResponseReader.java @@ -28,28 +28,24 @@ package org.apache.hc.client5.http.impl.cache; import java.io.IOException; import java.io.InputStream; -import java.lang.reflect.Proxy; import org.apache.hc.client5.http.cache.InputLimit; import org.apache.hc.client5.http.cache.Resource; import org.apache.hc.client5.http.cache.ResourceFactory; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; -import org.apache.hc.core5.annotation.NotThreadSafe; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.HttpRequest; -import org.apache.hc.core5.http.HttpResponse; -import org.apache.hc.core5.http.message.BasicHttpResponse; +import org.apache.hc.core5.http.message.BasicClassicHttpResponse; /** * @since 4.1 */ -@NotThreadSafe class SizeLimitedResponseReader { private final ResourceFactory resourceFactory; private final long maxResponseSizeBytes; private final HttpRequest request; - private final CloseableHttpResponse response; + private final ClassicHttpResponse response; private InputStream instream; private InputLimit limit; @@ -57,14 +53,14 @@ class SizeLimitedResponseReader { private boolean consumed; /** - * Create an {@link HttpResponse} that is limited in size, this allows for checking + * Create an {@link ClassicHttpResponse} that is limited in size, this allows for checking * the size of objects that will be stored in the cache. */ public SizeLimitedResponseReader( final ResourceFactory resourceFactory, final long maxResponseSizeBytes, final HttpRequest request, - final CloseableHttpResponse response) { + final ClassicHttpResponse response) { super(); this.resourceFactory = resourceFactory; this.maxResponseSizeBytes = maxResponseSizeBytes; @@ -100,7 +96,7 @@ class SizeLimitedResponseReader { if (entity == null) { return; } - final String uri = request.getRequestLine().getUri(); + final String uri = request.getRequestUri(); instream = entity.getContent(); try { resource = resourceFactory.generate(uri, instream, limit); @@ -121,9 +117,19 @@ class SizeLimitedResponseReader { return resource; } - CloseableHttpResponse getReconstructedResponse() throws IOException { + ClassicHttpResponse getReconstructedResponse() throws IOException { ensureConsumed(); - final HttpResponse reconstructed = new BasicHttpResponse(response.getStatusLine()); + final ClassicHttpResponse reconstructed = new BasicClassicHttpResponse(response.getCode()) { + + @Override + public void close() throws IOException { + try { + super.close(); + } finally { + response.close(); + } + } + }; reconstructed.setHeaders(response.getAllHeaders()); final CombinedEntity combinedEntity = new CombinedEntity(resource, instream); @@ -134,17 +140,7 @@ class SizeLimitedResponseReader { combinedEntity.setChunked(entity.isChunked()); } reconstructed.setEntity(combinedEntity); - return (CloseableHttpResponse) Proxy.newProxyInstance( - ResponseProxyHandler.class.getClassLoader(), - new Class[] { CloseableHttpResponse.class }, - new ResponseProxyHandler(reconstructed) { - - @Override - public void close() throws IOException { - response.close(); - } - - }); + return reconstructed; } } diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/cache/TestHttpCacheEntry.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/cache/TestHttpCacheEntry.java index 36ce10dca..14d7234e0 100644 --- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/cache/TestHttpCacheEntry.java +++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/cache/TestHttpCacheEntry.java @@ -42,10 +42,7 @@ import java.util.Map; import org.apache.hc.client5.http.utils.DateUtils; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpStatus; -import org.apache.hc.core5.http.HttpVersion; -import org.apache.hc.core5.http.StatusLine; import org.apache.hc.core5.http.message.BasicHeader; -import org.apache.hc.core5.http.message.BasicStatusLine; import org.junit.Before; import org.junit.Test; @@ -55,7 +52,6 @@ public class TestHttpCacheEntry { private Date elevenSecondsAgo; private Date nineSecondsAgo; private Resource mockResource; - private StatusLine statusLine; private HttpCacheEntry entry; @Before @@ -63,14 +59,11 @@ public class TestHttpCacheEntry { now = new Date(); elevenSecondsAgo = new Date(now.getTime() - 11 * 1000L); nineSecondsAgo = new Date(now.getTime() - 9 * 1000L); - statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1, - HttpStatus.SC_OK, "OK"); mockResource = mock(Resource.class); } private HttpCacheEntry makeEntry(final Header[] headers) { - return new HttpCacheEntry(elevenSecondsAgo, nineSecondsAgo, - statusLine, headers, mockResource, HeaderConstants.GET_METHOD); + return new HttpCacheEntry(elevenSecondsAgo, nineSecondsAgo, HttpStatus.SC_OK, headers, mockResource); } @Test @@ -147,8 +140,7 @@ public class TestHttpCacheEntry { @Test public void mustProvideRequestDate() { try { - new HttpCacheEntry(null, new Date(), statusLine, - new Header[]{}, mockResource, HeaderConstants.GET_METHOD); + new HttpCacheEntry(null, new Date(), HttpStatus.SC_OK, new Header[]{}, mockResource); fail("Should have thrown exception"); } catch (final IllegalArgumentException expected) { } @@ -158,19 +150,7 @@ public class TestHttpCacheEntry { @Test public void mustProvideResponseDate() { try { - new HttpCacheEntry(new Date(), null, statusLine, - new Header[]{}, mockResource, HeaderConstants.GET_METHOD); - fail("Should have thrown exception"); - } catch (final IllegalArgumentException expected) { - } - } - - @SuppressWarnings("unused") - @Test - public void mustProvideStatusLine() { - try { - new HttpCacheEntry(new Date(), new Date(), null, - new Header[]{}, mockResource, HeaderConstants.GET_METHOD); + new HttpCacheEntry(new Date(), null, HttpStatus.SC_OK, new Header[]{}, mockResource); fail("Should have thrown exception"); } catch (final IllegalArgumentException expected) { } @@ -180,62 +160,35 @@ public class TestHttpCacheEntry { @Test public void mustProvideResponseHeaders() { try { - new HttpCacheEntry(new Date(), new Date(), statusLine, - null, mockResource, HeaderConstants.GET_METHOD); + new HttpCacheEntry(new Date(), new Date(), HttpStatus.SC_OK, null, mockResource); fail("Should have thrown exception"); } catch (final IllegalArgumentException expected) { } } - @Test - public void canRetrieveOriginalStatusLine() { - entry = new HttpCacheEntry(new Date(), new Date(), statusLine, - new Header[]{}, mockResource, HeaderConstants.GET_METHOD); - assertSame(statusLine, entry.getStatusLine()); - } - - @Test - public void protocolVersionComesFromOriginalStatusLine() { - entry = new HttpCacheEntry(new Date(), new Date(), statusLine, - new Header[]{}, mockResource, HeaderConstants.GET_METHOD); - assertSame(statusLine.getProtocolVersion(), - entry.getProtocolVersion()); - } - - @Test - public void reasonPhraseComesFromOriginalStatusLine() { - entry = new HttpCacheEntry(new Date(), new Date(), statusLine, - new Header[]{}, mockResource, HeaderConstants.GET_METHOD); - assertSame(statusLine.getReasonPhrase(), entry.getReasonPhrase()); - } - @Test public void statusCodeComesFromOriginalStatusLine() { - entry = new HttpCacheEntry(new Date(), new Date(), statusLine, - new Header[]{}, mockResource, HeaderConstants.GET_METHOD); - assertEquals(statusLine.getStatusCode(), entry.getStatusCode()); + entry = new HttpCacheEntry(new Date(), new Date(), HttpStatus.SC_OK, new Header[]{}, mockResource); + assertEquals(HttpStatus.SC_OK, entry.getStatus()); } @Test public void canGetOriginalRequestDate() { final Date requestDate = new Date(); - entry = new HttpCacheEntry(requestDate, new Date(), statusLine, - new Header[]{}, mockResource, HeaderConstants.GET_METHOD); + entry = new HttpCacheEntry(requestDate, new Date(), HttpStatus.SC_OK, new Header[]{}, mockResource); assertSame(requestDate, entry.getRequestDate()); } @Test public void canGetOriginalResponseDate() { final Date responseDate = new Date(); - entry = new HttpCacheEntry(new Date(), responseDate, statusLine, - new Header[]{}, mockResource, HeaderConstants.GET_METHOD); + entry = new HttpCacheEntry(new Date(), responseDate, HttpStatus.SC_OK, new Header[]{}, mockResource); assertSame(responseDate, entry.getResponseDate()); } @Test public void canGetOriginalResource() { - entry = new HttpCacheEntry(new Date(), new Date(), statusLine, - new Header[]{}, mockResource, HeaderConstants.GET_METHOD); + entry = new HttpCacheEntry(new Date(), new Date(), HttpStatus.SC_OK, new Header[]{}, mockResource); assertSame(mockResource, entry.getResource()); } @@ -245,8 +198,7 @@ public class TestHttpCacheEntry { new BasicHeader("Server", "MockServer/1.0"), new BasicHeader("Date", DateUtils.formatDate(now)) }; - entry = new HttpCacheEntry(new Date(), new Date(), statusLine, - headers, mockResource, HeaderConstants.GET_METHOD); + entry = new HttpCacheEntry(new Date(), new Date(), HttpStatus.SC_OK, headers, mockResource); final Header[] result = entry.getAllHeaders(); assertEquals(headers.length, result.length); for(int i=0; i(), HeaderConstants.GET_METHOD); + new HashMap()); } @Test @@ -274,9 +225,9 @@ public class TestHttpCacheEntry { final Map variantMap = new HashMap<>(); variantMap.put("A","B"); variantMap.put("C","D"); - entry = new HttpCacheEntry(new Date(), new Date(), statusLine, + entry = new HttpCacheEntry(new Date(), new Date(), HttpStatus.SC_OK, new Header[]{}, mockResource, - variantMap, HeaderConstants.GET_METHOD); + variantMap); final Map result = entry.getVariantMap(); assertEquals(2, result.size()); assertEquals("B", result.get("A")); @@ -288,9 +239,9 @@ public class TestHttpCacheEntry { final Map variantMap = new HashMap<>(); variantMap.put("A","B"); variantMap.put("C","D"); - entry = new HttpCacheEntry(new Date(), new Date(), statusLine, + entry = new HttpCacheEntry(new Date(), new Date(), HttpStatus.SC_OK, new Header[]{}, mockResource, - variantMap, HeaderConstants.GET_METHOD); + variantMap); final Map result = entry.getVariantMap(); try { result.remove("A"); @@ -306,8 +257,8 @@ public class TestHttpCacheEntry { @Test public void canConvertToString() { - entry = new HttpCacheEntry(new Date(), new Date(), statusLine, - new Header[]{}, mockResource, HeaderConstants.GET_METHOD); + entry = new HttpCacheEntry(new Date(), new Date(), HttpStatus.SC_OK, + new Header[]{}, mockResource); assertNotNull(entry.toString()); assertFalse("".equals(entry.toString())); } @@ -315,16 +266,16 @@ public class TestHttpCacheEntry { @Test public void testMissingDateHeaderIsIgnored() { final Header[] headers = new Header[] {}; - entry = new HttpCacheEntry(new Date(), new Date(), statusLine, - headers, mockResource, HeaderConstants.GET_METHOD); + entry = new HttpCacheEntry(new Date(), new Date(), HttpStatus.SC_OK, + headers, mockResource); assertNull(entry.getDate()); } @Test public void testMalformedDateHeaderIsIgnored() { final Header[] headers = new Header[] { new BasicHeader("Date", "asdf") }; - entry = new HttpCacheEntry(new Date(), new Date(), statusLine, - headers, mockResource, HeaderConstants.GET_METHOD); + entry = new HttpCacheEntry(new Date(), new Date(), HttpStatus.SC_OK, + headers, mockResource); assertNull(entry.getDate()); } @@ -334,8 +285,8 @@ public class TestHttpCacheEntry { // round down to nearest second to make comparison easier final Date date = new Date(nowMs - (nowMs % 1000L)); final Header[] headers = new Header[] { new BasicHeader("Date", DateUtils.formatDate(date)) }; - entry = new HttpCacheEntry(new Date(), new Date(), statusLine, - headers, mockResource, HeaderConstants.GET_METHOD); + entry = new HttpCacheEntry(new Date(), new Date(), HttpStatus.SC_OK, + headers, mockResource); final Date dateHeaderValue = entry.getDate(); assertNotNull(dateHeaderValue); assertEquals(date.getTime(), dateHeaderValue.getTime()); diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/AbstractProtocolTest.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/AbstractProtocolTest.java index d1944982c..9ee01daf2 100644 --- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/AbstractProtocolTest.java +++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/AbstractProtocolTest.java @@ -31,16 +31,15 @@ import java.util.HashMap; import org.apache.hc.client5.http.HttpRoute; import org.apache.hc.client5.http.cache.HttpCacheContext; import org.apache.hc.client5.http.impl.sync.ClientExecChain; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpExecutionAware; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.HttpClientContext; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.HttpResponse; -import org.apache.hc.core5.http.HttpVersion; -import org.apache.hc.core5.http.message.BasicHttpRequest; +import org.apache.hc.core5.http.message.BasicClassicHttpRequest; import org.easymock.EasyMock; import org.easymock.IExpectationSetters; import org.junit.Before; @@ -55,14 +54,14 @@ public abstract class AbstractProtocolTest { protected HttpEntity body; protected ClientExecChain mockBackend; protected HttpCache mockCache; - protected HttpRequestWrapper request; + protected RoutedHttpRequest request; protected HttpCacheContext context; - protected CloseableHttpResponse originResponse; + protected ClassicHttpResponse originResponse; protected CacheConfig config; protected ClientExecChain impl; protected HttpCache cache; - public static HttpRequestWrapper eqRequest(final HttpRequestWrapper in) { + public static RoutedHttpRequest eqRequest(final RoutedHttpRequest in) { EasyMock.reportMatcher(new RequestEquivalent(in)); return null; } @@ -72,7 +71,7 @@ public abstract class AbstractProtocolTest { return null; } - public static CloseableHttpResponse eqCloseableResponse(final CloseableHttpResponse in) { + public static ClassicHttpResponse eqCloseableResponse(final ClassicHttpResponse in) { EasyMock.reportMatcher(new ResponseEquivalent(in)); return null; } @@ -85,12 +84,11 @@ public abstract class AbstractProtocolTest { body = HttpTestUtils.makeBody(entityLength); - request = HttpRequestWrapper.wrap(new BasicHttpRequest("GET", "/foo", HttpVersion.HTTP_1_1), host); + request = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("GET", "/foo"), route); context = HttpCacheContext.create(); - context.setTargetHost(host); - originResponse = Proxies.enhanceResponse(HttpTestUtils.make200Response()); + originResponse = HttpTestUtils.make200Response(); config = CacheConfig.custom() .setMaxCacheEntries(MAX_ENTRIES) @@ -122,23 +120,21 @@ public abstract class AbstractProtocolTest { EasyMock.verify(mockCache); } - protected IExpectationSetters backendExpectsAnyRequest() throws Exception { - final CloseableHttpResponse resp = mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + protected IExpectationSetters backendExpectsAnyRequest() throws Exception { + final ClassicHttpResponse resp = mockBackend.execute( + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull()); return EasyMock.expect(resp); } - protected IExpectationSetters backendExpectsAnyRequestAndReturn( - final HttpResponse reponse) throws Exception { - final CloseableHttpResponse resp = mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + protected IExpectationSetters backendExpectsAnyRequestAndReturn( + final ClassicHttpResponse response) throws Exception { + final ClassicHttpResponse resp = mockBackend.execute( + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull()); - return EasyMock.expect(resp).andReturn(Proxies.enhanceResponse(reponse)); + return EasyMock.expect(resp).andReturn(response); } protected void emptyMockCacheExpectsNoPuts() throws Exception { diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/DummyBackend.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/DummyBackend.java index 3da3a54ea..7ae212ab8 100644 --- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/DummyBackend.java +++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/DummyBackend.java @@ -28,26 +28,24 @@ package org.apache.hc.client5.http.impl.cache; import java.io.IOException; -import org.apache.hc.client5.http.HttpRoute; import org.apache.hc.client5.http.impl.sync.ClientExecChain; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpExecutionAware; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.HttpClientContext; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpException; 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.ProtocolVersion; -import org.apache.hc.core5.http.message.BasicHttpResponse; +import org.apache.hc.core5.http.message.BasicClassicHttpResponse; public class DummyBackend implements ClientExecChain { - private HttpRequest request; - private HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP",1,1), HttpStatus.SC_OK, "OK"); + private ClassicHttpRequest request; + private ClassicHttpResponse response = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); private int executions = 0; - public void setResponse(final HttpResponse resp) { + public void setResponse(final ClassicHttpResponse resp) { response = resp; } @@ -56,14 +54,13 @@ public class DummyBackend implements ClientExecChain { } @Override - public CloseableHttpResponse execute( - final HttpRoute route, - final HttpRequestWrapper request, + public ClassicHttpResponse execute( + final RoutedHttpRequest request, final HttpClientContext clientContext, final HttpExecutionAware execAware) throws IOException, HttpException { this.request = request; executions++; - return Proxies.enhanceResponse(response); + return response; } public int getExecutions() { 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 4c87d3bbd..fe2505033 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,27 +29,30 @@ package org.apache.hc.client5.http.impl.cache; import java.io.InputStream; import java.util.Date; import java.util.HashMap; +import java.util.Iterator; import java.util.Map; import java.util.Random; -import org.apache.hc.client5.http.cache.HeaderConstants; import org.apache.hc.client5.http.cache.HttpCacheEntry; 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.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; import org.apache.hc.core5.http.HttpStatus; import org.apache.hc.core5.http.HttpVersion; -import org.apache.hc.core5.http.RequestLine; -import org.apache.hc.core5.http.StatusLine; -import org.apache.hc.core5.http.entity.ByteArrayEntity; +import org.apache.hc.core5.http.ProtocolVersion; +import org.apache.hc.core5.http.io.entity.ByteArrayEntity; +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.BasicHttpRequest; -import org.apache.hc.core5.http.message.BasicHttpResponse; -import org.apache.hc.core5.http.message.BasicStatusLine; +import org.apache.hc.core5.http.message.MessageSupport; +import org.apache.hc.core5.util.LangUtils; import org.junit.Assert; public class HttpTestUtils { @@ -72,7 +75,7 @@ public class HttpTestUtils { private static final String[] MULTI_HEADERS = { "Accept", "Accept-Charset", "Accept-Encoding", "Accept-Language", "Allow", "Cache-Control", "Connection", "Content-Encoding", "Content-Language", "Expect", "Pragma", "Proxy-Authenticate", "TE", "Trailer", - "Transfer-Encoding", "Upgrade", "Via", "Warning", "WWW-Authenticate" }; + "Transfer-Encoding", "Upgrade", "Via", HttpHeaders.WARNING, "WWW-Authenticate" }; private static final String[] SINGLE_HEADERS = { "Accept-Ranges", "Age", "Authorization", "Content-Length", "Content-Location", "Content-MD5", "Content-Range", "Content-Type", "Date", "ETag", "Expires", "From", "Host", "If-Match", "If-Modified-Since", @@ -150,32 +153,6 @@ public class HttpTestUtils { return (-1 == i2.read()); } - /* - * Assert.asserts that the components of two status lines match in a way - * that differs only by hop-by-hop information. "2.1 Proxy Behavior ...We - * remind the reader that HTTP version numbers are hop-by-hop components of - * HTTP meesages, and are not end-to-end." - * - * @see http://www.ietf.org/rfc/rfc2145.txt - */ - public static boolean semanticallyTransparent(final StatusLine l1, final StatusLine l2) { - return (l1.getReasonPhrase().equals(l2.getReasonPhrase()) && l1.getStatusCode() == l2 - .getStatusCode()); - } - - /* Assert.asserts that the components of two status lines match. */ - public static boolean equivalent(final StatusLine l1, final StatusLine l2) { - return (l1.getProtocolVersion().equals(l2.getProtocolVersion()) && semanticallyTransparent( - l1, l2)); - } - - /* Assert.asserts that the components of two request lines match. */ - public static boolean equivalent(final RequestLine l1, final RequestLine l2) { - return (l1.getMethod().equals(l2.getMethod()) - && l1.getProtocolVersion().equals(l2.getProtocolVersion()) && l1.getUri().equals( - l2.getUri())); - } - /* * Retrieves the full header value by combining multiple headers and * separating with commas, canonicalizing whitespace along the way. @@ -225,31 +202,39 @@ public class HttpTestUtils { * * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec1.html#sec1.3 */ - public static boolean semanticallyTransparent(final HttpResponse r1, final HttpResponse r2) - throws Exception { + public static boolean semanticallyTransparent( + final ClassicHttpResponse r1, final ClassicHttpResponse r2) throws Exception { final boolean entitiesEquivalent = equivalent(r1.getEntity(), r2.getEntity()); if (!entitiesEquivalent) { return false; } - final boolean statusLinesEquivalent = semanticallyTransparent(r1.getStatusLine(), r2.getStatusLine()); + final boolean statusLinesEquivalent = LangUtils.equals(r1.getReasonPhrase(), r2.getReasonPhrase()) + && r1.getCode() == r2.getCode(); if (!statusLinesEquivalent) { return false; } - final boolean e2eHeadersEquivalentSubset = isEndToEndHeaderSubset( - r1, r2); - return e2eHeadersEquivalentSubset; + return isEndToEndHeaderSubset(r1, r2); + } + + /* Assert.asserts that protocol versions equivalent. */ + public static boolean equivalent(final ProtocolVersion v1, final ProtocolVersion v2) { + return LangUtils.equals(v1 != null ? v1 : HttpVersion.DEFAULT, v2 != null ? v2 : HttpVersion.DEFAULT ); } /* Assert.asserts that two requests are morally equivalent. */ public static boolean equivalent(final HttpRequest r1, final HttpRequest r2) { - return (equivalent(r1.getRequestLine(), r2.getRequestLine()) && isEndToEndHeaderSubset(r1, - r2)); + return equivalent(r1.getVersion(), r2.getVersion()) && + LangUtils.equals(r1.getMethod(), r2.getMethod()) && + LangUtils.equals(r1.getRequestUri(), r2.getRequestUri()) && + isEndToEndHeaderSubset(r1, r2); } /* Assert.asserts that two requests are morally equivalent. */ public static boolean equivalent(final HttpResponse r1, final HttpResponse r2) { - return (equivalent(r1.getStatusLine(), r2.getStatusLine()) && isEndToEndHeaderSubset(r1, - r2)); + return equivalent(r1.getVersion(), r2.getVersion()) && + r1.getCode() == r2.getCode() && + LangUtils.equals(r1.getReasonPhrase(), r2.getReasonPhrase()) && + isEndToEndHeaderSubset(r1, r2); } public static byte[] getRandomBytes(final int nbytes) { @@ -301,7 +286,7 @@ public class HttpTestUtils { public static HttpCacheEntry makeCacheEntry(final Date requestDate, final Date responseDate, final Header[] headers, final byte[] bytes, final Map variantMap) { - return new HttpCacheEntry(requestDate, responseDate, makeStatusLine(), headers, new HeapResource(bytes), variantMap, HeaderConstants.GET_METHOD); + return new HttpCacheEntry(requestDate, responseDate, HttpStatus.SC_OK, headers, new HeapResource(bytes), variantMap); } public static HttpCacheEntry makeCacheEntry(final Header[] headers, final byte[] bytes) { @@ -324,39 +309,31 @@ public class HttpTestUtils { public static HttpCacheEntry makeCacheEntryWithNoRequestMethodOrEntity(final Header[] headers) { final Date now = new Date(); - return new HttpCacheEntry(now, now, makeStatusLine(), headers, null, null, null); + return new HttpCacheEntry(now, now, HttpStatus.SC_OK, headers, null, null); } public static HttpCacheEntry makeCacheEntryWithNoRequestMethod(final Header[] headers) { final Date now = new Date(); - return new HttpCacheEntry(now, now, makeStatusLine(), headers, new HeapResource(getRandomBytes(128)), null, null); + return new HttpCacheEntry(now, now, HttpStatus.SC_OK, headers, new HeapResource(getRandomBytes(128)), null); } public static HttpCacheEntry make204CacheEntryWithNoRequestMethod(final Header[] headers) { final Date now = new Date(); - return new HttpCacheEntry(now, now, make204StatusLine(), headers, null, null, HeaderConstants.HEAD_METHOD); + return new HttpCacheEntry(now, now, HttpStatus.SC_NO_CONTENT, headers, null, null); } public static HttpCacheEntry makeHeadCacheEntry(final Header[] headers) { final Date now = new Date(); - return new HttpCacheEntry(now, now, makeStatusLine(), headers, null, null, HeaderConstants.HEAD_METHOD); + return new HttpCacheEntry(now, now, HttpStatus.SC_OK, headers, null, null); } public static HttpCacheEntry makeHeadCacheEntryWithNoRequestMethod(final Header[] headers) { final Date now = new Date(); - return new HttpCacheEntry(now, now, makeStatusLine(), headers, null, null, null); + return new HttpCacheEntry(now, now, HttpStatus.SC_OK, headers, null, null); } - public static StatusLine makeStatusLine() { - return new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); - } - - public static StatusLine make204StatusLine() { - return new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_NO_CONTENT, "OK"); - } - - public static HttpResponse make200Response() { - final HttpResponse out = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); + public static ClassicHttpResponse make200Response() { + final ClassicHttpResponse out = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); out.setHeader("Date", DateUtils.formatDate(new Date())); out.setHeader("Server", "MockOrigin/1.0"); out.setHeader("Content-Length", "128"); @@ -364,39 +341,42 @@ public class HttpTestUtils { return out; } - public static final HttpResponse make200Response(final Date date, final String cacheControl) { - final HttpResponse response = HttpTestUtils.make200Response(); + public static final ClassicHttpResponse make200Response(final Date date, final String cacheControl) { + final ClassicHttpResponse response = HttpTestUtils.make200Response(); response.setHeader("Date", DateUtils.formatDate(date)); response.setHeader("Cache-Control",cacheControl); response.setHeader("Etag","\"etag\""); return response; } + public static ClassicHttpResponse make304Response() { + return new BasicClassicHttpResponse(HttpStatus.SC_NOT_MODIFIED, "Not modified"); + } + public static final void assert110WarningFound(final HttpResponse response) { boolean found110Warning = false; - for(final Header h : response.getHeaders("Warning")) { - for(final HeaderElement elt : h.getElements()) { - final String[] parts = elt.getName().split("\\s"); - if ("110".equals(parts[0])) { - found110Warning = true; - break; - } + final Iterator 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; } } Assert.assertTrue(found110Warning); } - public static HttpRequest makeDefaultRequest() { - return new BasicHttpRequest("GET","/",HttpVersion.HTTP_1_1); + public static ClassicHttpRequest makeDefaultRequest() { + return new BasicClassicHttpRequest("GET", "/"); } - public static HttpRequest makeDefaultHEADRequest() { - return new BasicHttpRequest("HEAD","/",HttpVersion.HTTP_1_1); + public static ClassicHttpRequest makeDefaultHEADRequest() { + return new BasicClassicHttpRequest("HEAD", "/"); } - public static HttpResponse make500Response() { - return new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_INTERNAL_SERVER_ERROR, "Internal Server Error"); + public static ClassicHttpResponse make500Response() { + return new BasicClassicHttpResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Internal Server Error"); } public static Map makeDefaultVariantMap(final String key, final String value) { diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/OKStatus.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/OKStatus.java deleted file mode 100644 index 7b2a64179..000000000 --- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/OKStatus.java +++ /dev/null @@ -1,41 +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 - * . - * - */ -package org.apache.hc.client5.http.impl.cache; - -import org.apache.hc.core5.http.HttpStatus; -import org.apache.hc.core5.http.HttpVersion; -import org.apache.hc.core5.http.message.BasicStatusLine; - -public class OKStatus extends BasicStatusLine { - - private static final long serialVersionUID = -1639872615816850272L; - - public OKStatus() { - super(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); - } - -} diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestAsynchronousValidationRequest.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestAsynchronousValidationRequest.java index 942945ee9..2ddc62723 100644 --- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestAsynchronousValidationRequest.java +++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestAsynchronousValidationRequest.java @@ -35,15 +35,14 @@ import java.io.IOException; import org.apache.hc.client5.http.HttpRoute; import org.apache.hc.client5.http.cache.HeaderConstants; import org.apache.hc.client5.http.cache.HttpCacheEntry; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpExecutionAware; import org.apache.hc.client5.http.methods.HttpGet; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.HttpClientContext; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.ProtocolException; -import org.apache.hc.core5.http.StatusLine; import org.apache.hc.core5.http.message.BasicHeader; import org.junit.Before; import org.junit.Test; @@ -55,12 +54,11 @@ public class TestAsynchronousValidationRequest { private CachingExec mockClient; private HttpHost host; private HttpRoute route; - private HttpRequestWrapper request; + private RoutedHttpRequest request; private HttpClientContext context; private HttpExecutionAware mockExecAware; private HttpCacheEntry mockCacheEntry; - private CloseableHttpResponse mockResponse; - private StatusLine mockStatusLine; + private ClassicHttpResponse mockResponse; @Before public void setUp() { @@ -68,12 +66,11 @@ public class TestAsynchronousValidationRequest { mockClient = mock(CachingExec.class); host = new HttpHost("foo.example.com", 80); route = new HttpRoute(host); - request = HttpRequestWrapper.wrap(new HttpGet("/"), host); + request = RoutedHttpRequest.adapt(new HttpGet("/"), route); context = HttpClientContext.create(); mockExecAware = mock(HttpExecutionAware.class); mockCacheEntry = mock(HttpCacheEntry.class); - mockResponse = mock(CloseableHttpResponse.class); - mockStatusLine = mock(StatusLine.class); + mockResponse = mock(ClassicHttpResponse.class); } @Test @@ -81,20 +78,18 @@ public class TestAsynchronousValidationRequest { final String identifier = "foo"; final AsynchronousValidationRequest impl = new AsynchronousValidationRequest( - mockParent, mockClient, route, request, context, mockExecAware, mockCacheEntry, + mockParent, mockClient, request, context, mockExecAware, mockCacheEntry, identifier, 0); when( mockClient.revalidateCacheEntry( - route, request, context, mockExecAware, mockCacheEntry)).thenReturn(mockResponse); - when(mockResponse.getStatusLine()).thenReturn(mockStatusLine); - when(mockStatusLine.getStatusCode()).thenReturn(200); + request, context, mockExecAware, mockCacheEntry)).thenReturn(mockResponse); + when(mockResponse.getCode()).thenReturn(200); impl.run(); verify(mockClient).revalidateCacheEntry( - route, request, context, mockExecAware, mockCacheEntry); - verify(mockResponse).getStatusLine(); + request, context, mockExecAware, mockCacheEntry); verify(mockParent).markComplete(identifier); verify(mockParent).jobSuccessful(identifier); } @@ -104,21 +99,18 @@ public class TestAsynchronousValidationRequest { final String identifier = "foo"; final AsynchronousValidationRequest impl = new AsynchronousValidationRequest( - mockParent, mockClient, route, request, context, mockExecAware, mockCacheEntry, + mockParent, mockClient, request, context, mockExecAware, mockCacheEntry, identifier, 0); when( mockClient.revalidateCacheEntry( - route, request, context, mockExecAware, mockCacheEntry)).thenReturn(mockResponse); - when(mockResponse.getStatusLine()).thenReturn(mockStatusLine); - when(mockStatusLine.getStatusCode()).thenReturn(200); + request, context, mockExecAware, mockCacheEntry)).thenReturn(mockResponse); + when(mockResponse.getCode()).thenReturn(200); impl.run(); verify(mockClient).revalidateCacheEntry( - route, request, context, mockExecAware, mockCacheEntry); - verify(mockResponse).getStatusLine(); - verify(mockStatusLine).getStatusCode(); + request, context, mockExecAware, mockCacheEntry); verify(mockParent).markComplete(identifier); verify(mockParent).jobSuccessful(identifier); } @@ -129,22 +121,19 @@ public class TestAsynchronousValidationRequest { final Header[] warning = new Header[] {new BasicHeader(HeaderConstants.WARNING, "110 localhost \"Response is stale\"")}; final AsynchronousValidationRequest impl = new AsynchronousValidationRequest( - mockParent, mockClient, route, request, context, mockExecAware, mockCacheEntry, + mockParent, mockClient, request, context, mockExecAware, mockCacheEntry, identifier, 0); when( mockClient.revalidateCacheEntry( - route, request, context, mockExecAware, mockCacheEntry)).thenReturn(mockResponse); - when(mockResponse.getStatusLine()).thenReturn(mockStatusLine); - when(mockStatusLine.getStatusCode()).thenReturn(200); + request, context, mockExecAware, mockCacheEntry)).thenReturn(mockResponse); + when(mockResponse.getCode()).thenReturn(200); when(mockResponse.getHeaders(HeaderConstants.WARNING)).thenReturn(warning); impl.run(); verify(mockClient).revalidateCacheEntry( - route, request, context, mockExecAware, mockCacheEntry); - verify(mockResponse).getStatusLine(); - verify(mockStatusLine).getStatusCode(); + request, context, mockExecAware, mockCacheEntry); verify(mockResponse).getHeaders(HeaderConstants.WARNING); verify(mockParent).markComplete(identifier); verify(mockParent).jobFailed(identifier); @@ -155,18 +144,18 @@ public class TestAsynchronousValidationRequest { final String identifier = "foo"; final AsynchronousValidationRequest impl = new AsynchronousValidationRequest( - mockParent, mockClient, route, request, context, mockExecAware, mockCacheEntry, + mockParent, mockClient, request, context, mockExecAware, mockCacheEntry, identifier, 0); when( mockClient.revalidateCacheEntry( - route, request, context, mockExecAware, mockCacheEntry)).thenThrow( + request, context, mockExecAware, mockCacheEntry)).thenThrow( new ProtocolException()); impl.run(); verify(mockClient).revalidateCacheEntry( - route, request, context, mockExecAware, mockCacheEntry); + request, context, mockExecAware, mockCacheEntry); verify(mockParent).markComplete(identifier); verify(mockParent).jobFailed(identifier); } @@ -176,18 +165,18 @@ public class TestAsynchronousValidationRequest { final String identifier = "foo"; final AsynchronousValidationRequest impl = new AsynchronousValidationRequest( - mockParent, mockClient, route, request, context, mockExecAware, mockCacheEntry, + mockParent, mockClient, request, context, mockExecAware, mockCacheEntry, identifier, 0); when( mockClient.revalidateCacheEntry( - route, request, context, mockExecAware, mockCacheEntry)).thenThrow( + request, context, mockExecAware, mockCacheEntry)).thenThrow( new IOException()); impl.run(); verify(mockClient).revalidateCacheEntry( - route, request, context, mockExecAware, mockCacheEntry); + request, context, mockExecAware, mockCacheEntry); verify(mockParent).markComplete(identifier); verify(mockParent).jobFailed(identifier); } @@ -197,18 +186,18 @@ public class TestAsynchronousValidationRequest { final String identifier = "foo"; final AsynchronousValidationRequest impl = new AsynchronousValidationRequest( - mockParent, mockClient, route, request, context, mockExecAware, mockCacheEntry, + mockParent, mockClient, request, context, mockExecAware, mockCacheEntry, identifier, 0); when( mockClient.revalidateCacheEntry( - route, request, context, mockExecAware, mockCacheEntry)).thenThrow( + request, context, mockExecAware, mockCacheEntry)).thenThrow( new RuntimeException()); impl.run(); verify(mockClient).revalidateCacheEntry( - route, request, context, mockExecAware, mockCacheEntry); + request, context, mockExecAware, mockCacheEntry); verify(mockParent).markComplete(identifier); verify(mockParent).jobFailed(identifier); } diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestAsynchronousValidator.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestAsynchronousValidator.java index c83973229..ac24c540c 100644 --- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestAsynchronousValidator.java +++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestAsynchronousValidator.java @@ -42,12 +42,13 @@ import org.apache.hc.client5.http.cache.HeaderConstants; import org.apache.hc.client5.http.cache.HttpCacheEntry; import org.apache.hc.client5.http.methods.HttpExecutionAware; import org.apache.hc.client5.http.methods.HttpGet; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.HttpClientContext; +import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpHost; -import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.message.BasicHeader; +import org.apache.hc.core5.http.message.BasicHeaderIterator; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -61,7 +62,7 @@ public class TestAsynchronousValidator { private CachingExec mockClient; private HttpHost host; private HttpRoute route; - private HttpRequestWrapper request; + private RoutedHttpRequest request; private HttpClientContext context; private HttpExecutionAware mockExecAware; private HttpCacheEntry mockCacheEntry; @@ -73,9 +74,8 @@ public class TestAsynchronousValidator { mockClient = mock(CachingExec.class); host = new HttpHost("foo.example.com", 80); route = new HttpRoute(host); - request = HttpRequestWrapper.wrap(new HttpGet("/"), host); + request = RoutedHttpRequest.adapt(new HttpGet("/"), route); context = HttpClientContext.create(); - context.setTargetHost(new HttpHost("foo.example.com")); mockExecAware = mock(HttpExecutionAware.class); mockCacheEntry = mock(HttpCacheEntry.class); mockSchedulingStrategy = mock(SchedulingStrategy.class); @@ -87,7 +87,7 @@ public class TestAsynchronousValidator { when(mockCacheEntry.hasVariants()).thenReturn(false); - impl.revalidateCacheEntry(mockClient, route, request, context, mockExecAware, mockCacheEntry); + impl.revalidateCacheEntry(mockClient, request, context, mockExecAware, mockCacheEntry); verify(mockCacheEntry).hasVariants(); verify(mockSchedulingStrategy).schedule(isA(AsynchronousValidationRequest.class)); @@ -101,7 +101,7 @@ public class TestAsynchronousValidator { when(mockCacheEntry.hasVariants()).thenReturn(false); - impl.revalidateCacheEntry(mockClient, route, request, context, mockExecAware, mockCacheEntry); + impl.revalidateCacheEntry(mockClient, request, context, mockExecAware, mockCacheEntry); final ArgumentCaptor cap = ArgumentCaptor.forClass(AsynchronousValidationRequest.class); verify(mockCacheEntry).hasVariants(); @@ -121,7 +121,7 @@ public class TestAsynchronousValidator { when(mockCacheEntry.hasVariants()).thenReturn(false); doThrow(new RejectedExecutionException()).when(mockSchedulingStrategy).schedule(isA(AsynchronousValidationRequest.class)); - impl.revalidateCacheEntry(mockClient, route, request, context, mockExecAware, mockCacheEntry); + impl.revalidateCacheEntry(mockClient, request, context, mockExecAware, mockCacheEntry); verify(mockCacheEntry).hasVariants(); @@ -135,8 +135,8 @@ public class TestAsynchronousValidator { when(mockCacheEntry.hasVariants()).thenReturn(false); - impl.revalidateCacheEntry(mockClient, route, request, context, mockExecAware, mockCacheEntry); - impl.revalidateCacheEntry(mockClient, route, request, context, mockExecAware, mockCacheEntry); + impl.revalidateCacheEntry(mockClient, request, context, mockExecAware, mockCacheEntry); + impl.revalidateCacheEntry(mockClient, request, context, mockExecAware, mockCacheEntry); verify(mockCacheEntry, times(2)).hasVariants(); verify(mockSchedulingStrategy).schedule(isA(AsynchronousValidationRequest.class)); @@ -148,10 +148,10 @@ public class TestAsynchronousValidator { public void testVariantsBothRevalidated() { impl = new AsynchronousValidator(mockSchedulingStrategy); - final HttpRequest req1 = new HttpGet("/"); + final ClassicHttpRequest req1 = new HttpGet("/"); req1.addHeader(new BasicHeader("Accept-Encoding", "identity")); - final HttpRequest req2 = new HttpGet("/"); + final ClassicHttpRequest req2 = new HttpGet("/"); req2.addHeader(new BasicHeader("Accept-Encoding", "gzip")); final Header[] variantHeaders = new Header[] { @@ -159,14 +159,15 @@ public class TestAsynchronousValidator { }; when(mockCacheEntry.hasVariants()).thenReturn(true); - when(mockCacheEntry.getHeaders(HeaderConstants.VARY)).thenReturn(variantHeaders); + when(mockCacheEntry.headerIterator(HeaderConstants.VARY)).thenReturn( + new BasicHeaderIterator(variantHeaders, HeaderConstants.VARY)); mockSchedulingStrategy.schedule(isA(AsynchronousValidationRequest.class)); - impl.revalidateCacheEntry(mockClient, route, HttpRequestWrapper.wrap(req1, host), context, mockExecAware, mockCacheEntry); - impl.revalidateCacheEntry(mockClient, route, HttpRequestWrapper.wrap(req2, host), context, mockExecAware, mockCacheEntry); + impl.revalidateCacheEntry(mockClient, RoutedHttpRequest.adapt(req1, route), context, mockExecAware, mockCacheEntry); + impl.revalidateCacheEntry(mockClient, RoutedHttpRequest.adapt(req2, route), context, mockExecAware, mockCacheEntry); verify(mockCacheEntry, times(2)).hasVariants(); - verify(mockCacheEntry, times(2)).getHeaders(HeaderConstants.VARY); + verify(mockCacheEntry, times(2)).headerIterator(HeaderConstants.VARY); verify(mockSchedulingStrategy, times(2)).schedule(isA(AsynchronousValidationRequest.class)); Assert.assertEquals(2, impl.getScheduledIdentifiers().size()); @@ -183,9 +184,9 @@ public class TestAsynchronousValidator { when(mockCacheEntry.hasVariants()).thenReturn(false); when(mockClient.revalidateCacheEntry( - route, request, context, mockExecAware, mockCacheEntry)).thenReturn(null); + request, context, mockExecAware, mockCacheEntry)).thenReturn(null); - impl.revalidateCacheEntry(mockClient, route, request, context, mockExecAware, mockCacheEntry); + impl.revalidateCacheEntry(mockClient, request, context, mockExecAware, mockCacheEntry); try { // shut down backend executor and make sure all finishes properly, 1 second should be sufficient @@ -195,7 +196,7 @@ public class TestAsynchronousValidator { } finally { verify(mockCacheEntry).hasVariants(); - verify(mockClient).revalidateCacheEntry(route, request, context, mockExecAware, mockCacheEntry); + verify(mockClient).revalidateCacheEntry(request, context, mockExecAware, mockCacheEntry); Assert.assertEquals(0, impl.getScheduledIdentifiers().size()); } diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestBasicHttpCache.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestBasicHttpCache.java index 0890da145..95dc2bcde 100644 --- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestBasicHttpCache.java +++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestBasicHttpCache.java @@ -51,17 +51,16 @@ import org.apache.hc.client5.http.methods.HttpOptions; import org.apache.hc.client5.http.methods.HttpPost; import org.apache.hc.client5.http.methods.HttpTrace; import org.apache.hc.client5.http.utils.DateUtils; +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.HttpHost; 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.HttpVersion; -import org.apache.hc.core5.http.entity.BasicHttpEntity; -import org.apache.hc.core5.http.entity.ByteArrayEntity; +import org.apache.hc.core5.http.io.entity.BasicHttpEntity; +import org.apache.hc.core5.http.io.entity.ByteArrayEntity; +import org.apache.hc.core5.http.message.BasicClassicHttpResponse; import org.apache.hc.core5.http.message.BasicHeader; -import org.apache.hc.core5.http.message.BasicHttpResponse; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -81,7 +80,7 @@ public class TestBasicHttpCache { public void testDoNotFlushCacheEntriesOnGet() throws Exception { final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest req = new HttpGet("/bar"); - final String key = (new CacheKeyGenerator()).getURI(host, req); + final String key = (new CacheKeyGenerator()).generateKey(host, req); final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(); backing.map.put(key, entry); @@ -95,7 +94,7 @@ public class TestBasicHttpCache { public void testDoNotFlushCacheEntriesOnHead() throws Exception { final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest req = new HttpHead("/bar"); - final String key = (new CacheKeyGenerator()).getURI(host, req); + final String key = (new CacheKeyGenerator()).generateKey(host, req); final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(); backing.map.put(key, entry); @@ -109,7 +108,7 @@ public class TestBasicHttpCache { public void testDoNotFlushCacheEntriesOnOptions() throws Exception { final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest req = new HttpOptions("/bar"); - final String key = (new CacheKeyGenerator()).getURI(host, req); + final String key = (new CacheKeyGenerator()).generateKey(host, req); final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(); backing.map.put(key, entry); @@ -123,7 +122,7 @@ public class TestBasicHttpCache { public void testDoNotFlushCacheEntriesOnTrace() throws Exception { final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest req = new HttpTrace("/bar"); - final String key = (new CacheKeyGenerator()).getURI(host, req); + final String key = (new CacheKeyGenerator()).generateKey(host, req); final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(); backing.map.put(key, entry); @@ -138,10 +137,10 @@ public class TestBasicHttpCache { throws Exception { final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest req = new HttpPost("/foo"); - final HttpResponse resp = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp = HttpTestUtils.make200Response(); resp.setHeader("Content-Location", "/bar"); resp.setHeader(HeaderConstants.ETAG, "\"etag\""); - final String key = (new CacheKeyGenerator()).getURI(host, new HttpGet("/bar")); + final String key = (new CacheKeyGenerator()).generateKey(host, new HttpGet("/bar")); final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(new Header[] { new BasicHeader("Date", DateUtils.formatDate(new Date())), @@ -160,9 +159,9 @@ public class TestBasicHttpCache { throws Exception { final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest req = new HttpGet("/foo"); - final HttpResponse resp = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp = HttpTestUtils.make200Response(); resp.setHeader("Content-Location", "/bar"); - final String key = (new CacheKeyGenerator()).getURI(host, new HttpGet("/bar")); + final String key = (new CacheKeyGenerator()).generateKey(host, new HttpGet("/bar")); final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(new Header[] { new BasicHeader("Date", DateUtils.formatDate(new Date())), @@ -180,7 +179,7 @@ public class TestBasicHttpCache { public void testCanFlushCacheEntriesAtUri() throws Exception { final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest req = new HttpDelete("/bar"); - final String key = (new CacheKeyGenerator()).getURI(host, req); + final String key = (new CacheKeyGenerator()).generateKey(host, req); final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(); backing.map.put(key, entry); @@ -193,7 +192,7 @@ public class TestBasicHttpCache { @Test public void testRecognizesComplete200Response() throws Exception { - final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); + final ClassicHttpResponse resp = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); final byte[] bytes = HttpTestUtils.getRandomBytes(128); resp.setEntity(new ByteArrayEntity(bytes)); resp.setHeader("Content-Length","128"); @@ -205,7 +204,7 @@ public class TestBasicHttpCache { @Test public void testRecognizesComplete206Response() throws Exception { - final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); + final ClassicHttpResponse resp = new BasicClassicHttpResponse(HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); final byte[] bytes = HttpTestUtils.getRandomBytes(128); final Resource resource = new HeapResource(bytes); resp.setEntity(new ByteArrayEntity(bytes)); @@ -218,7 +217,7 @@ public class TestBasicHttpCache { @Test public void testRecognizesIncomplete200Response() throws Exception { - final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); + final ClassicHttpResponse resp = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); final byte[] bytes = HttpTestUtils.getRandomBytes(128); final Resource resource = new HeapResource(bytes); resp.setEntity(new ByteArrayEntity(bytes)); @@ -230,7 +229,7 @@ public class TestBasicHttpCache { @Test public void testIgnoresIncompleteNon200Or206Responses() throws Exception { - final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_FORBIDDEN, "Forbidden"); + final ClassicHttpResponse resp = new BasicClassicHttpResponse(HttpStatus.SC_FORBIDDEN, "Forbidden"); final byte[] bytes = HttpTestUtils.getRandomBytes(128); final Resource resource = new HeapResource(bytes); resp.setEntity(new ByteArrayEntity(bytes)); @@ -242,7 +241,7 @@ public class TestBasicHttpCache { @Test public void testResponsesWithoutExplicitContentLengthAreComplete() throws Exception { - final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); + final ClassicHttpResponse resp = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); final byte[] bytes = HttpTestUtils.getRandomBytes(128); final Resource resource = new HeapResource(bytes); resp.setEntity(new ByteArrayEntity(bytes)); @@ -253,7 +252,7 @@ public class TestBasicHttpCache { @Test public void testResponsesWithUnparseableContentLengthHeaderAreComplete() throws Exception { - final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); + final ClassicHttpResponse resp = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); final byte[] bytes = HttpTestUtils.getRandomBytes(128); final Resource resource = new HeapResource(bytes); resp.setHeader("Content-Length","foo"); @@ -265,7 +264,7 @@ public class TestBasicHttpCache { @Test public void testNullResourcesAreComplete() throws Exception { - final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); + final ClassicHttpResponse resp = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp.setHeader("Content-Length","256"); assertFalse(impl.isIncompleteResponse(resp, null)); @@ -274,13 +273,13 @@ public class TestBasicHttpCache { @Test public void testIncompleteResponseErrorProvidesPlainTextErrorMessage() throws Exception { - final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); + final ClassicHttpResponse resp = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); final byte[] bytes = HttpTestUtils.getRandomBytes(128); final Resource resource = new HeapResource(bytes); resp.setEntity(new ByteArrayEntity(bytes)); resp.setHeader("Content-Length","256"); - final HttpResponse result = impl.generateIncompleteResponseError(resp, resource); + final ClassicHttpResponse result = impl.generateIncompleteResponseError(resp, resource); final Header ctype = result.getFirstHeader("Content-Type"); assertEquals("text/plain;charset=UTF-8", ctype.getValue()); } @@ -288,13 +287,13 @@ public class TestBasicHttpCache { @Test public void testIncompleteResponseErrorProvidesNonEmptyErrorMessage() throws Exception { - final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); + final ClassicHttpResponse resp = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); final byte[] bytes = HttpTestUtils.getRandomBytes(128); final Resource resource = new HeapResource(bytes); resp.setEntity(new ByteArrayEntity(bytes)); resp.setHeader("Content-Length","256"); - final HttpResponse result = impl.generateIncompleteResponseError(resp, resource); + final ClassicHttpResponse result = impl.generateIncompleteResponseError(resp, resource); final int clen = Integer.parseInt(result.getFirstHeader("Content-Length").getValue()); assertTrue(clen > 0); final HttpEntity body = result.getEntity(); @@ -336,7 +335,7 @@ public class TestBasicHttpCache { assertFalse(entry.hasVariants()); final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest req = new HttpGet("http://foo.example.com/bar"); - final String key = (new CacheKeyGenerator()).getURI(host, req); + final String key = (new CacheKeyGenerator()).generateKey(host, req); impl.storeInCache(host, req, entry); assertSame(entry, backing.map.get(key)); @@ -352,13 +351,13 @@ public class TestBasicHttpCache { final Date responseGenerated = new Date(now.getTime() - 2 * 1000L); final Date responseReceived = new Date(now.getTime() - 1 * 1000L); - final HttpResponse originResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); + final ClassicHttpResponse originResponse = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); originResponse.setEntity(HttpTestUtils.makeBody(CacheConfig.DEFAULT_MAX_OBJECT_SIZE_BYTES + 1)); originResponse.setHeader("Cache-Control","public, max-age=3600"); originResponse.setHeader("Date", DateUtils.formatDate(responseGenerated)); originResponse.setHeader("ETag", "\"etag\""); - final HttpResponse result = impl.cacheAndReturnResponse(host, request, originResponse, requestSent, responseReceived); + final ClassicHttpResponse result = impl.cacheAndReturnResponse(host, request, originResponse, requestSent, responseReceived); assertEquals(0, backing.map.size()); assertTrue(HttpTestUtils.semanticallyTransparent(originResponse, result)); } @@ -374,15 +373,15 @@ public class TestBasicHttpCache { final Date responseGenerated = new Date(now.getTime() - 2 * 1000L); final Date responseReceived = new Date(now.getTime() - 1 * 1000L); - final HttpResponse originResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); + final ClassicHttpResponse originResponse = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); originResponse.setEntity(HttpTestUtils.makeBody(CacheConfig.DEFAULT_MAX_OBJECT_SIZE_BYTES - 1)); originResponse.setHeader("Cache-Control","public, max-age=3600"); originResponse.setHeader("Date", DateUtils.formatDate(responseGenerated)); originResponse.setHeader("ETag", "\"etag\""); - final HttpResponse result = impl.cacheAndReturnResponse(host, request, originResponse, requestSent, responseReceived); + final ClassicHttpResponse result = impl.cacheAndReturnResponse(host, request, originResponse, requestSent, responseReceived); assertEquals(1, backing.map.size()); - assertTrue(backing.map.containsKey((new CacheKeyGenerator()).getURI(host, request))); + assertTrue(backing.map.containsKey((new CacheKeyGenerator()).generateKey(host, request))); assertTrue(HttpTestUtils.semanticallyTransparent(originResponse, result)); } @@ -401,7 +400,7 @@ public class TestBasicHttpCache { final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest request = new HttpGet("http://foo.example.com/bar"); - final String key = (new CacheKeyGenerator()).getURI(host, request); + final String key = (new CacheKeyGenerator()).generateKey(host, request); backing.map.put(key,entry); @@ -417,7 +416,7 @@ public class TestBasicHttpCache { final HttpRequest origRequest = new HttpGet("http://foo.example.com/bar"); origRequest.setHeader("Accept-Encoding","gzip"); - final HttpResponse origResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); + final ClassicHttpResponse origResponse = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); origResponse.setEntity(HttpTestUtils.makeBody(128)); origResponse.setHeader("Date", DateUtils.formatDate(new Date())); origResponse.setHeader("Cache-Control", "max-age=3600, public"); @@ -439,7 +438,7 @@ public class TestBasicHttpCache { final HttpRequest origRequest = new HttpGet("http://foo.example.com/bar"); origRequest.setHeader("Accept-Encoding","gzip"); - final HttpResponse origResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); + final ClassicHttpResponse origResponse = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); origResponse.setEntity(HttpTestUtils.makeBody(128)); origResponse.setHeader("Date", DateUtils.formatDate(new Date())); origResponse.setHeader("Cache-Control", "max-age=3600, public"); @@ -469,7 +468,7 @@ public class TestBasicHttpCache { final HttpRequest req1 = new HttpGet("http://foo.example.com/bar"); req1.setHeader("Accept-Encoding", "gzip"); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Date", DateUtils.formatDate(new Date())); resp1.setHeader("Cache-Control", "max-age=3600, public"); resp1.setHeader("ETag", "\"etag1\""); @@ -480,7 +479,7 @@ public class TestBasicHttpCache { final HttpRequest req2 = new HttpGet("http://foo.example.com/bar"); req2.setHeader("Accept-Encoding", "identity"); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); resp2.setHeader("Date", DateUtils.formatDate(new Date())); resp2.setHeader("Cache-Control", "max-age=3600, public"); resp2.setHeader("ETag", "\"etag2\""); @@ -508,7 +507,7 @@ public class TestBasicHttpCache { final Date responseGenerated = new Date(now.getTime() - 2 * 1000L); final Date responseReceived = new Date(now.getTime() - 1 * 1000L); - final HttpResponse originResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); + final ClassicHttpResponse originResponse = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); final BasicHttpEntity entity = new BasicHttpEntity(); final ConsumableInputStream inputStream = new ConsumableInputStream(new ByteArrayInputStream(HttpTestUtils.getRandomBytes(CacheConfig.DEFAULT_MAX_OBJECT_SIZE_BYTES - 1))); entity.setContent(inputStream); @@ -517,7 +516,7 @@ public class TestBasicHttpCache { originResponse.setHeader("Date", DateUtils.formatDate(responseGenerated)); originResponse.setHeader("ETag", "\"etag\""); - final HttpResponse result = impl.cacheAndReturnResponse(host, request, originResponse, requestSent, responseReceived); + final ClassicHttpResponse result = impl.cacheAndReturnResponse(host, request, originResponse, requestSent, responseReceived); IOUtils.consume(result.getEntity()); assertTrue(inputStream.wasClosed()); } @@ -577,7 +576,7 @@ public class TestBasicHttpCache { final HttpRequest origRequest = new HttpGet("http://foo.example.com/bar"); origRequest.setHeader("Accept-Encoding","gzip"); - final HttpResponse origResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); + final ClassicHttpResponse origResponse = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); origResponse.setEntity(HttpTestUtils.makeBody(128)); origResponse.setHeader("Date", DateUtils.formatDate(new Date())); origResponse.setHeader("Cache-Control", "max-age=3600, public"); @@ -585,7 +584,7 @@ public class TestBasicHttpCache { origResponse.setHeader("Vary", "Accept-Encoding"); origResponse.setHeader("Content-Encoding","gzip"); - final HttpResponse response = impl.cacheAndReturnResponse( + final ClassicHttpResponse response = impl.cacheAndReturnResponse( host, origRequest, origResponse, new Date(), new Date()); final HttpEntity entity = response.getEntity(); Assert.assertNotNull(entity); diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCacheEntryUpdater.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCacheEntryUpdater.java index 732fdc146..bd04b98ed 100644 --- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCacheEntryUpdater.java +++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCacheEntryUpdater.java @@ -38,7 +38,6 @@ import org.apache.hc.client5.http.utils.DateUtils; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.HttpStatus; -import org.apache.hc.core5.http.HttpVersion; import org.apache.hc.core5.http.message.BasicHeader; import org.apache.hc.core5.http.message.BasicHttpResponse; import org.junit.Before; @@ -69,8 +68,7 @@ public class TestCacheEntryUpdater { eightSecondsAgo = new Date(now.getTime() - 8000L); tenSecondsAgo = new Date(now.getTime() - 10000L); - response = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_NOT_MODIFIED, "Not Modified"); + response = new BasicHttpResponse(HttpStatus.SC_NOT_MODIFIED, "Not Modified"); impl = new CacheEntryUpdater(); } @@ -227,8 +225,7 @@ public class TestCacheEntryUpdater { @Test public void cannotUpdateFromANon304OriginResponse() throws Exception { entry = HttpTestUtils.makeCacheEntry(); - response = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_OK, "OK"); + response = new BasicHttpResponse(HttpStatus.SC_OK, "OK"); try { impl.updateCacheEntry("A", entry, new Date(), new Date(), response); diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCacheInvalidator.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCacheInvalidator.java index 947af26b2..64647c1e1 100644 --- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCacheInvalidator.java +++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCacheInvalidator.java @@ -32,6 +32,7 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import java.io.IOException; +import java.net.URL; import java.util.Date; import java.util.HashMap; import java.util.Map; @@ -39,16 +40,15 @@ import java.util.Map; import org.apache.hc.client5.http.cache.HttpCacheEntry; import org.apache.hc.client5.http.cache.HttpCacheStorage; 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.HttpHost; -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.HttpVersion; import org.apache.hc.core5.http.ProtocolVersion; +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.BasicHttpRequest; -import org.apache.hc.core5.http.message.BasicHttpResponse; import org.junit.Before; import org.junit.Test; @@ -61,8 +61,8 @@ public class TestCacheInvalidator { private HttpHost host; private CacheKeyGenerator cacheKeyGenerator; private HttpCacheEntry mockEntry; - private HttpRequest request; - private HttpResponse response; + private ClassicHttpRequest request; + private ClassicHttpResponse response; private Date now; private Date tenSecondsAgo; @@ -85,7 +85,7 @@ public class TestCacheInvalidator { // Tests @Test public void testInvalidatesRequestsThatArentGETorHEAD() throws Exception { - request = new BasicHttpRequest("POST","/path", HTTP_1_1); + request = new BasicClassicHttpRequest("POST","/path"); final String theUri = "http://foo.example.com:80/path"; final Map variantMap = new HashMap<>(); cacheEntryHasVariantMap(variantMap); @@ -101,7 +101,7 @@ public class TestCacheInvalidator { @Test public void testInvalidatesUrisInContentLocationHeadersOnPUTs() throws Exception { - final HttpRequest putRequest = new BasicHttpRequest("PUT","/",HTTP_1_1); + final ClassicHttpRequest putRequest = new BasicClassicHttpRequest("PUT","/"); putRequest.setEntity(HttpTestUtils.makeBody(128)); putRequest.setHeader("Content-Length","128"); @@ -123,7 +123,7 @@ public class TestCacheInvalidator { @Test public void testInvalidatesUrisInLocationHeadersOnPUTs() throws Exception { - final HttpRequest putRequest = new BasicHttpRequest("PUT","/",HTTP_1_1); + final ClassicHttpRequest putRequest = new BasicClassicHttpRequest("PUT","/"); putRequest.setEntity(HttpTestUtils.makeBody(128)); putRequest.setHeader("Content-Length","128"); @@ -140,12 +140,12 @@ public class TestCacheInvalidator { verify(mockEntry).getVariantMap(); verify(mockStorage).getEntry(theUri); verify(mockStorage).removeEntry(theUri); - verify(mockStorage).removeEntry(cacheKeyGenerator.canonicalizeUri(contentLocation)); + verify(mockStorage).removeEntry(cacheKeyGenerator.generateKey(new URL(contentLocation))); } @Test public void testInvalidatesRelativeUrisInContentLocationHeadersOnPUTs() throws Exception { - final HttpRequest putRequest = new BasicHttpRequest("PUT","/",HTTP_1_1); + final ClassicHttpRequest putRequest = new BasicClassicHttpRequest("PUT","/"); putRequest.setEntity(HttpTestUtils.makeBody(128)); putRequest.setHeader("Content-Length","128"); @@ -167,7 +167,7 @@ public class TestCacheInvalidator { @Test public void testDoesNotInvalidateUrisInContentLocationHeadersOnPUTsToDifferentHosts() throws Exception { - final HttpRequest putRequest = new BasicHttpRequest("PUT","/",HTTP_1_1); + final ClassicHttpRequest putRequest = new BasicClassicHttpRequest("PUT","/"); putRequest.setEntity(HttpTestUtils.makeBody(128)); putRequest.setHeader("Content-Length","128"); @@ -188,7 +188,7 @@ public class TestCacheInvalidator { @Test public void testDoesNotInvalidateGETRequest() throws Exception { - request = new BasicHttpRequest("GET","/",HTTP_1_1); + request = new BasicClassicHttpRequest("GET","/"); impl.flushInvalidatedCacheEntries(host, request); verify(mockStorage).getEntry("http://foo.example.com:80/"); @@ -197,7 +197,7 @@ public class TestCacheInvalidator { @Test public void testDoesNotInvalidateHEADRequest() throws Exception { - request = new BasicHttpRequest("HEAD","/",HTTP_1_1); + request = new BasicClassicHttpRequest("HEAD","/"); impl.flushInvalidatedCacheEntries(host, request); verify(mockStorage).getEntry("http://foo.example.com:80/"); @@ -208,7 +208,7 @@ public class TestCacheInvalidator { public void testInvalidatesHEADCacheEntryIfSubsequentGETRequestsAreMadeToTheSameURI() throws Exception { impl = new CacheInvalidator(cacheKeyGenerator, mockStorage); final String theURI = "http://foo.example.com:80/"; - request = new BasicHttpRequest("GET", theURI,HTTP_1_1); + request = new BasicClassicHttpRequest("GET", theURI); cacheEntryisForMethod("HEAD"); cacheEntryHasVariantMap(new HashMap()); @@ -226,7 +226,7 @@ public class TestCacheInvalidator { public void testInvalidatesVariantHEADCacheEntriesIfSubsequentGETRequestsAreMadeToTheSameURI() throws Exception { impl = new CacheInvalidator(cacheKeyGenerator, mockStorage); final String theURI = "http://foo.example.com:80/"; - request = new BasicHttpRequest("GET", theURI,HTTP_1_1); + request = new BasicClassicHttpRequest("GET", theURI); final String theVariantKey = "{Accept-Encoding=gzip%2Cdeflate&User-Agent=Apache-HttpClient}"; final String theVariantURI = "{Accept-Encoding=gzip%2Cdeflate&User-Agent=Apache-HttpClient}http://foo.example.com:80/"; final Map variants = HttpTestUtils.makeDefaultVariantMap(theVariantKey, theVariantURI); @@ -247,7 +247,7 @@ public class TestCacheInvalidator { @Test public void testDoesNotInvalidateHEADCacheEntry() throws Exception { final String theURI = "http://foo.example.com:80/"; - request = new BasicHttpRequest("HEAD", theURI,HTTP_1_1); + request = new BasicClassicHttpRequest("HEAD", theURI); cacheReturnsEntryForUri(theURI); @@ -261,7 +261,7 @@ public class TestCacheInvalidator { public void testDoesNotInvalidateHEADCacheEntryIfSubsequentHEADRequestsAreMadeToTheSameURI() throws Exception { impl = new CacheInvalidator(cacheKeyGenerator, mockStorage); final String theURI = "http://foo.example.com:80/"; - request = new BasicHttpRequest("HEAD", theURI,HTTP_1_1); + request = new BasicClassicHttpRequest("HEAD", theURI); cacheReturnsEntryForUri(theURI); @@ -275,7 +275,7 @@ public class TestCacheInvalidator { public void testDoesNotInvalidateGETCacheEntryIfSubsequentGETRequestsAreMadeToTheSameURI() throws Exception { impl = new CacheInvalidator(cacheKeyGenerator, mockStorage); final String theURI = "http://foo.example.com:80/"; - request = new BasicHttpRequest("GET", theURI,HTTP_1_1); + request = new BasicClassicHttpRequest("GET", theURI); cacheEntryisForMethod("GET"); cacheReturnsEntryForUri(theURI); @@ -289,7 +289,7 @@ public class TestCacheInvalidator { @Test public void testDoesNotInvalidateRequestsWithClientCacheControlHeaders() throws Exception { - request = new BasicHttpRequest("GET","/",HTTP_1_1); + request = new BasicClassicHttpRequest("GET","/"); request.setHeader("Cache-Control","no-cache"); impl.flushInvalidatedCacheEntries(host, request); @@ -300,7 +300,7 @@ public class TestCacheInvalidator { @Test public void testDoesNotInvalidateRequestsWithClientPragmaHeaders() throws Exception { - request = new BasicHttpRequest("GET","/",HTTP_1_1); + request = new BasicClassicHttpRequest("GET","/"); request.setHeader("Pragma","no-cache"); impl.flushInvalidatedCacheEntries(host, request); @@ -311,7 +311,7 @@ public class TestCacheInvalidator { @Test public void testVariantURIsAreFlushedAlso() throws Exception { - request = new BasicHttpRequest("POST","/",HTTP_1_1); + request = new BasicClassicHttpRequest("POST","/"); final String theUri = "http://foo.example.com:80/"; final String variantUri = "theVariantURI"; final Map mapOfURIs = HttpTestUtils.makeDefaultVariantMap(variantUri, variantUri); @@ -329,7 +329,7 @@ public class TestCacheInvalidator { @Test public void testCacheFlushException() throws Exception { - request = new BasicHttpRequest("POST","/",HTTP_1_1); + request = new BasicClassicHttpRequest("POST","/"); final String theURI = "http://foo.example.com:80/"; cacheReturnsExceptionForUri(theURI); @@ -372,7 +372,7 @@ public class TestCacheInvalidator { @Test public void flushesEntryIfFresherAndSpecifiedByLocation() throws Exception { - response.setStatusCode(201); + response.setCode(201); response.setHeader("ETag","\"new-etag\""); response.setHeader("Date", DateUtils.formatDate(now)); final String theURI = "http://foo.example.com:80/bar"; @@ -394,7 +394,7 @@ public class TestCacheInvalidator { @Test public void doesNotFlushEntryForUnsuccessfulResponse() throws Exception { - response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_BAD_REQUEST, "Bad Request"); + response = new BasicClassicHttpResponse(HttpStatus.SC_BAD_REQUEST, "Bad Request"); response.setHeader("ETag","\"new-etag\""); response.setHeader("Date", DateUtils.formatDate(now)); final String theURI = "http://foo.example.com:80/bar"; diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCacheKeyGenerator.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCacheKeyGenerator.java index 413dcb1c3..808250e83 100644 --- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCacheKeyGenerator.java +++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCacheKeyGenerator.java @@ -35,8 +35,8 @@ import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpRequest; -import org.apache.hc.core5.http.HttpVersion; import org.apache.hc.core5.http.message.BasicHeader; +import org.apache.hc.core5.http.message.BasicHeaderIterator; import org.apache.hc.core5.http.message.BasicHttpRequest; import org.junit.Assert; import org.junit.Before; @@ -66,50 +66,50 @@ public class TestCacheKeyGenerator { public void testExtractsUriFromAbsoluteUriInRequest() { final HttpHost host = new HttpHost("bar.example.com"); final HttpRequest req = new HttpGet("http://foo.example.com/"); - Assert.assertEquals("http://foo.example.com:80/", extractor.getURI(host, req)); + Assert.assertEquals("http://foo.example.com:80/", extractor.generateKey(host, req)); } @Test public void testGetURIWithDefaultPortAndScheme() { - Assert.assertEquals("http://www.comcast.net:80/", extractor.getURI(new HttpHost( + Assert.assertEquals("http://www.comcast.net:80/", extractor.generateKey(new HttpHost( "www.comcast.net"), REQUEST_ROOT)); - Assert.assertEquals("http://www.fancast.com:80/full_episodes", extractor.getURI(new HttpHost( + Assert.assertEquals("http://www.fancast.com:80/full_episodes", extractor.generateKey(new HttpHost( "www.fancast.com"), REQUEST_FULL_EPISODES)); } @Test public void testGetURIWithDifferentScheme() { - Assert.assertEquals("https://www.comcast.net:443/", extractor.getURI(new HttpHost( + Assert.assertEquals("https://www.comcast.net:443/", extractor.generateKey(new HttpHost( "www.comcast.net", -1, "https"), REQUEST_ROOT)); - Assert.assertEquals("myhttp://www.fancast.com/full_episodes", extractor.getURI( + Assert.assertEquals("myhttp://www.fancast.com/full_episodes", extractor.generateKey( new HttpHost("www.fancast.com", -1, "myhttp"), REQUEST_FULL_EPISODES)); } @Test public void testGetURIWithDifferentPort() { - Assert.assertEquals("http://www.comcast.net:8080/", extractor.getURI(new HttpHost( + Assert.assertEquals("http://www.comcast.net:8080/", extractor.generateKey(new HttpHost( "www.comcast.net", 8080), REQUEST_ROOT)); - Assert.assertEquals("http://www.fancast.com:9999/full_episodes", extractor.getURI( + Assert.assertEquals("http://www.fancast.com:9999/full_episodes", extractor.generateKey( new HttpHost("www.fancast.com", 9999), REQUEST_FULL_EPISODES)); } @Test public void testGetURIWithDifferentPortAndScheme() { - Assert.assertEquals("https://www.comcast.net:8080/", extractor.getURI(new HttpHost( + Assert.assertEquals("https://www.comcast.net:8080/", extractor.generateKey(new HttpHost( "www.comcast.net", 8080, "https"), REQUEST_ROOT)); - Assert.assertEquals("myhttp://www.fancast.com:9999/full_episodes", extractor.getURI( + Assert.assertEquals("myhttp://www.fancast.com:9999/full_episodes", extractor.generateKey( new HttpHost("www.fancast.com", 9999, "myhttp"), REQUEST_FULL_EPISODES)); } @Test public void testGetURIWithQueryParameters() { - Assert.assertEquals("http://www.comcast.net:80/?foo=bar", extractor.getURI(new HttpHost( + Assert.assertEquals("http://www.comcast.net:80/?foo=bar", extractor.generateKey(new HttpHost( "www.comcast.net", -1, "http"), new BasicHttpRequest("GET", "/?foo=bar"))); - Assert.assertEquals("http://www.fancast.com:80/full_episodes?foo=bar", extractor.getURI( + Assert.assertEquals("http://www.fancast.com:80/full_episodes?foo=bar", extractor.generateKey( new HttpHost("www.fancast.com", -1, "http"), new BasicHttpRequest("GET", "/full_episodes?foo=bar"))); } @@ -120,14 +120,14 @@ public class TestCacheKeyGenerator { when(mockEntry.hasVariants()).thenReturn(false); extractor = new CacheKeyGenerator() { @Override - public String getURI(final HttpHost h, final HttpRequest req) { + public String generateKey(final HttpHost h, final HttpRequest req) { Assert.assertSame(defaultHost, h); Assert.assertSame(mockRequest, req); return theURI; } }; - final String result = extractor.getVariantURI(defaultHost, mockRequest, mockEntry); + final String result = extractor.generateVariantURI(defaultHost, mockRequest, mockEntry); verify(mockEntry).hasVariants(); Assert.assertSame(theURI, result); } @@ -140,21 +140,20 @@ public class TestCacheKeyGenerator { extractor = new CacheKeyGenerator() { @Override - public String getURI(final HttpHost h, final HttpRequest req) { + public String generateKey(final HttpHost h, final HttpRequest req) { Assert.assertSame(defaultHost, h); Assert.assertSame(mockRequest, req); return theURI; } }; when(mockEntry.hasVariants()).thenReturn(true); - when(mockEntry.getHeaders("Vary")).thenReturn(varyHeaders); - when(mockRequest.getHeaders("Accept-Encoding")).thenReturn( - encHeaders); + when(mockEntry.headerIterator("Vary")).thenReturn(new BasicHeaderIterator(varyHeaders, "Vary")); + when(mockRequest.getHeaders("Accept-Encoding")).thenReturn(encHeaders); - final String result = extractor.getVariantURI(defaultHost, mockRequest, mockEntry); + final String result = extractor.generateVariantURI(defaultHost, mockRequest, mockEntry); verify(mockEntry).hasVariants(); - verify(mockEntry).getHeaders("Vary"); + verify(mockEntry).headerIterator("Vary"); verify(mockRequest).getHeaders("Accept-Encoding"); Assert.assertEquals("{Accept-Encoding=gzip}" + theURI, result); } @@ -166,21 +165,21 @@ public class TestCacheKeyGenerator { final Header[] varyHeaders = { new BasicHeader("Vary", "Accept-Encoding") }; extractor = new CacheKeyGenerator() { @Override - public String getURI(final HttpHost h, final HttpRequest req) { + public String generateKey(final HttpHost h, final HttpRequest req) { Assert.assertSame(defaultHost, h); Assert.assertSame(mockRequest, req); return theURI; } }; when(mockEntry.hasVariants()).thenReturn(true); - when(mockEntry.getHeaders("Vary")).thenReturn(varyHeaders); + when(mockEntry.headerIterator("Vary")).thenReturn(new BasicHeaderIterator(varyHeaders, "Vary")); when(mockRequest.getHeaders("Accept-Encoding")) .thenReturn(noHeaders); - final String result = extractor.getVariantURI(defaultHost, mockRequest, mockEntry); + final String result = extractor.generateVariantURI(defaultHost, mockRequest, mockEntry); verify(mockEntry).hasVariants(); - verify(mockEntry).getHeaders("Vary"); + verify(mockEntry).headerIterator("Vary"); verify(mockRequest).getHeaders("Accept-Encoding"); Assert.assertEquals("{Accept-Encoding=}" + theURI, result); } @@ -193,22 +192,21 @@ public class TestCacheKeyGenerator { final Header[] uaHeaders = { new BasicHeader("User-Agent", "browser") }; extractor = new CacheKeyGenerator() { @Override - public String getURI(final HttpHost h, final HttpRequest req) { + public String generateKey(final HttpHost h, final HttpRequest req) { Assert.assertSame(defaultHost, h); Assert.assertSame(mockRequest, req); return theURI; } }; when(mockEntry.hasVariants()).thenReturn(true); - when(mockEntry.getHeaders("Vary")).thenReturn(varyHeaders); - when(mockRequest.getHeaders("Accept-Encoding")).thenReturn( - encHeaders); + when(mockEntry.headerIterator("Vary")).thenReturn(new BasicHeaderIterator(varyHeaders, "Vary")); + when(mockRequest.getHeaders("Accept-Encoding")).thenReturn(encHeaders); when(mockRequest.getHeaders("User-Agent")).thenReturn(uaHeaders); - final String result = extractor.getVariantURI(defaultHost, mockRequest, mockEntry); + final String result = extractor.generateVariantURI(defaultHost, mockRequest, mockEntry); verify(mockEntry).hasVariants(); - verify(mockEntry).getHeaders("Vary"); + verify(mockEntry).headerIterator("Vary"); verify(mockRequest).getHeaders("Accept-Encoding"); verify(mockRequest).getHeaders("User-Agent"); Assert.assertEquals("{Accept-Encoding=gzip&User-Agent=browser}" + theURI, result); @@ -223,21 +221,21 @@ public class TestCacheKeyGenerator { final Header[] uaHeaders = { new BasicHeader("User-Agent", "browser") }; extractor = new CacheKeyGenerator() { @Override - public String getURI(final HttpHost h, final HttpRequest req) { + public String generateKey(final HttpHost h, final HttpRequest req) { Assert.assertSame(defaultHost, h); Assert.assertSame(mockRequest, req); return theURI; } }; when(mockEntry.hasVariants()).thenReturn(true); - when(mockEntry.getHeaders("Vary")).thenReturn(varyHeaders); + when(mockEntry.headerIterator("Vary")).thenReturn(new BasicHeaderIterator(varyHeaders, "Vary")); when(mockRequest.getHeaders("Accept-Encoding")).thenReturn(encHeaders); when(mockRequest.getHeaders("User-Agent")).thenReturn(uaHeaders); - final String result = extractor.getVariantURI(defaultHost, mockRequest, mockEntry); + final String result = extractor.generateVariantURI(defaultHost, mockRequest, mockEntry); verify(mockEntry).hasVariants(); - verify(mockEntry).getHeaders("Vary"); + verify(mockEntry).headerIterator("Vary"); verify(mockRequest).getHeaders("Accept-Encoding"); verify(mockRequest).getHeaders("User-Agent"); Assert.assertEquals("{Accept-Encoding=gzip&User-Agent=browser}" + theURI, result); @@ -252,26 +250,24 @@ public class TestCacheKeyGenerator { final Header[] uaHeaders = { new BasicHeader("User-Agent", "browser") }; extractor = new CacheKeyGenerator() { @Override - public String getURI(final HttpHost h, final HttpRequest req) { + public String generateKey(final HttpHost h, final HttpRequest req) { Assert.assertSame(defaultHost, h); Assert.assertSame(mockRequest, req); return theURI; } }; when(mockEntry.hasVariants()).thenReturn(true); - when(mockEntry.getHeaders("Vary")).thenReturn(varyHeaders); + when(mockEntry.headerIterator("Vary")).thenReturn(new BasicHeaderIterator(varyHeaders, "Vary")); when(mockRequest.getHeaders("Accept-Encoding")).thenReturn(encHeaders); when(mockRequest.getHeaders("User-Agent")).thenReturn(uaHeaders); - final String result = extractor.getVariantURI(defaultHost, mockRequest, mockEntry); + final String result = extractor.generateVariantURI(defaultHost, mockRequest, mockEntry); verify(mockEntry).hasVariants(); - verify(mockEntry).getHeaders("Vary"); + verify(mockEntry).headerIterator("Vary"); verify(mockRequest).getHeaders("Accept-Encoding"); verify(mockRequest).getHeaders("User-Agent"); - Assert - .assertEquals("{Accept-Encoding=gzip%2C+deflate&User-Agent=browser}" + theURI, - result); + Assert.assertEquals("{Accept-Encoding=gzip%2C+deflate&User-Agent=browser}" + theURI, result); } /* @@ -292,17 +288,17 @@ public class TestCacheKeyGenerator { public void testEmptyPortEquivalentToDefaultPortForHttp() { final HttpHost host1 = new HttpHost("foo.example.com:"); final HttpHost host2 = new HttpHost("foo.example.com:80"); - final HttpRequest req = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); - Assert.assertEquals(extractor.getURI(host1, req), extractor.getURI(host2, req)); + final HttpRequest req = new BasicHttpRequest("GET", "/"); + Assert.assertEquals(extractor.generateKey(host1, req), extractor.generateKey(host2, req)); } @Test public void testEmptyPortEquivalentToDefaultPortForHttps() { final HttpHost host1 = new HttpHost("foo.example.com", -1, "https"); final HttpHost host2 = new HttpHost("foo.example.com", 443, "https"); - final HttpRequest req = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); - final String uri1 = extractor.getURI(host1, req); - final String uri2 = extractor.getURI(host2, req); + final HttpRequest req = new BasicHttpRequest("GET", "/"); + final String uri1 = extractor.generateKey(host1, req); + final String uri2 = extractor.generateKey(host2, req); Assert.assertEquals(uri1, uri2); } @@ -311,8 +307,8 @@ public class TestCacheKeyGenerator { final HttpHost host = new HttpHost("foo.example.com", -1, "https"); final HttpGet get1 = new HttpGet("https://bar.example.com:/"); final HttpGet get2 = new HttpGet("https://bar.example.com:443/"); - final String uri1 = extractor.getURI(host, get1); - final String uri2 = extractor.getURI(host, get2); + final String uri1 = extractor.generateKey(host, get1); + final String uri2 = extractor.generateKey(host, get2); Assert.assertEquals(uri1, uri2); } @@ -321,8 +317,8 @@ public class TestCacheKeyGenerator { final HttpHost host = new HttpHost("foo.example.com", -1, "https"); final HttpGet get1 = new HttpGet("https://bar.example.com/"); final HttpGet get2 = new HttpGet("https://bar.example.com:443/"); - final String uri1 = extractor.getURI(host, get1); - final String uri2 = extractor.getURI(host, get2); + final String uri1 = extractor.generateKey(host, get1); + final String uri2 = extractor.generateKey(host, get2); Assert.assertEquals(uri1, uri2); } @@ -330,95 +326,95 @@ public class TestCacheKeyGenerator { public void testNotProvidedPortEquivalentToDefaultPortForHttp() { final HttpHost host1 = new HttpHost("foo.example.com"); final HttpHost host2 = new HttpHost("foo.example.com:80"); - final HttpRequest req = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); - Assert.assertEquals(extractor.getURI(host1, req), extractor.getURI(host2, req)); + final HttpRequest req = new BasicHttpRequest("GET", "/"); + Assert.assertEquals(extractor.generateKey(host1, req), extractor.generateKey(host2, req)); } @Test public void testHostNameComparisonsAreCaseInsensitive() { final HttpHost host1 = new HttpHost("foo.example.com"); final HttpHost host2 = new HttpHost("FOO.EXAMPLE.COM"); - final HttpRequest req = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); - Assert.assertEquals(extractor.getURI(host1, req), extractor.getURI(host2, req)); + final HttpRequest req = new BasicHttpRequest("GET", "/"); + Assert.assertEquals(extractor.generateKey(host1, req), extractor.generateKey(host2, req)); } @Test public void testSchemeNameComparisonsAreCaseInsensitive() { final HttpHost host1 = new HttpHost("foo.example.com", -1, "http"); final HttpHost host2 = new HttpHost("foo.example.com", -1, "HTTP"); - final HttpRequest req = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); - Assert.assertEquals(extractor.getURI(host1, req), extractor.getURI(host2, req)); + final HttpRequest req = new BasicHttpRequest("GET", "/"); + Assert.assertEquals(extractor.generateKey(host1, req), extractor.generateKey(host2, req)); } @Test public void testEmptyAbsPathIsEquivalentToSlash() { final HttpHost host = new HttpHost("foo.example.com"); - final HttpRequest req1 = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); + final HttpRequest req1 = new BasicHttpRequest("GET", "/"); final HttpRequest req2 = new HttpGet("http://foo.example.com"); - Assert.assertEquals(extractor.getURI(host, req1), extractor.getURI(host, req2)); + Assert.assertEquals(extractor.generateKey(host, req1), extractor.generateKey(host, req2)); } @Test public void testExtraDotSegmentsAreIgnored() { final HttpHost host = new HttpHost("foo.example.com"); - final HttpRequest req1 = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); + final HttpRequest req1 = new BasicHttpRequest("GET", "/"); final HttpRequest req2 = new HttpGet("http://foo.example.com/./"); - Assert.assertEquals(extractor.getURI(host, req1), extractor.getURI(host, req2)); + Assert.assertEquals(extractor.generateKey(host, req1), extractor.generateKey(host, req2)); } @Test public void testExtraDotDotSegmentsAreIgnored() { final HttpHost host = new HttpHost("foo.example.com"); - final HttpRequest req1 = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); + final HttpRequest req1 = new BasicHttpRequest("GET", "/"); final HttpRequest req2 = new HttpGet("http://foo.example.com/.././../"); - Assert.assertEquals(extractor.getURI(host, req1), extractor.getURI(host, req2)); + Assert.assertEquals(extractor.generateKey(host, req1), extractor.generateKey(host, req2)); } @Test public void testIntermidateDotDotSegementsAreEquivalent() { final HttpHost host = new HttpHost("foo.example.com"); - final HttpRequest req1 = new BasicHttpRequest("GET", "/home.html", HttpVersion.HTTP_1_1); - final HttpRequest req2 = new BasicHttpRequest("GET", "/%7Esmith/../home.html", HttpVersion.HTTP_1_1); - Assert.assertEquals(extractor.getURI(host, req1), extractor.getURI(host, req2)); + final HttpRequest req1 = new BasicHttpRequest("GET", "/home.html"); + final HttpRequest req2 = new BasicHttpRequest("GET", "/%7Esmith/../home.html"); + Assert.assertEquals(extractor.generateKey(host, req1), extractor.generateKey(host, req2)); } @Test public void testIntermidateEncodedDotDotSegementsAreEquivalent() { final HttpHost host = new HttpHost("foo.example.com"); - final HttpRequest req1 = new BasicHttpRequest("GET", "/home.html", HttpVersion.HTTP_1_1); - final HttpRequest req2 = new BasicHttpRequest("GET", "/%7Esmith%2F../home.html", HttpVersion.HTTP_1_1); - Assert.assertEquals(extractor.getURI(host, req1), extractor.getURI(host, req2)); + final HttpRequest req1 = new BasicHttpRequest("GET", "/home.html"); + final HttpRequest req2 = new BasicHttpRequest("GET", "/%7Esmith%2F../home.html"); + Assert.assertEquals(extractor.generateKey(host, req1), extractor.generateKey(host, req2)); } @Test public void testIntermidateDotSegementsAreEquivalent() { final HttpHost host = new HttpHost("foo.example.com"); - final HttpRequest req1 = new BasicHttpRequest("GET", "/~smith/home.html", HttpVersion.HTTP_1_1); - final HttpRequest req2 = new BasicHttpRequest("GET", "/%7Esmith/./home.html", HttpVersion.HTTP_1_1); - Assert.assertEquals(extractor.getURI(host, req1), extractor.getURI(host, req2)); + final HttpRequest req1 = new BasicHttpRequest("GET", "/~smith/home.html"); + final HttpRequest req2 = new BasicHttpRequest("GET", "/%7Esmith/./home.html"); + Assert.assertEquals(extractor.generateKey(host, req1), extractor.generateKey(host, req2)); } @Test public void testEquivalentPathEncodingsAreEquivalent() { final HttpHost host = new HttpHost("foo.example.com"); - final HttpRequest req1 = new BasicHttpRequest("GET", "/~smith/home.html", HttpVersion.HTTP_1_1); - final HttpRequest req2 = new BasicHttpRequest("GET", "/%7Esmith/home.html", HttpVersion.HTTP_1_1); - Assert.assertEquals(extractor.getURI(host, req1), extractor.getURI(host, req2)); + final HttpRequest req1 = new BasicHttpRequest("GET", "/~smith/home.html"); + final HttpRequest req2 = new BasicHttpRequest("GET", "/%7Esmith/home.html"); + Assert.assertEquals(extractor.generateKey(host, req1), extractor.generateKey(host, req2)); } @Test public void testEquivalentExtraPathEncodingsAreEquivalent() { final HttpHost host = new HttpHost("foo.example.com"); - final HttpRequest req1 = new BasicHttpRequest("GET", "/~smith/home.html", HttpVersion.HTTP_1_1); - final HttpRequest req2 = new BasicHttpRequest("GET", "/%7Esmith%2Fhome.html", HttpVersion.HTTP_1_1); - Assert.assertEquals(extractor.getURI(host, req1), extractor.getURI(host, req2)); + final HttpRequest req1 = new BasicHttpRequest("GET", "/~smith/home.html"); + final HttpRequest req2 = new BasicHttpRequest("GET", "/%7Esmith%2Fhome.html"); + Assert.assertEquals(extractor.generateKey(host, req1), extractor.generateKey(host, req2)); } @Test public void testEquivalentExtraPathEncodingsWithPercentAreEquivalent() { final HttpHost host = new HttpHost("foo.example.com"); - final HttpRequest req1 = new BasicHttpRequest("GET", "/~smith/home%20folder.html", HttpVersion.HTTP_1_1); - final HttpRequest req2 = new BasicHttpRequest("GET", "/%7Esmith%2Fhome%20folder.html", HttpVersion.HTTP_1_1); - Assert.assertEquals(extractor.getURI(host, req1), extractor.getURI(host, req2)); + final HttpRequest req1 = new BasicHttpRequest("GET", "/~smith/home%20folder.html"); + final HttpRequest req2 = new BasicHttpRequest("GET", "/%7Esmith%2Fhome%20folder.html"); + Assert.assertEquals(extractor.generateKey(host, req1), extractor.generateKey(host, req2)); } } diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCacheValidityPolicy.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCacheValidityPolicy.java index ceae1693d..7f9255560 100644 --- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCacheValidityPolicy.java +++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCacheValidityPolicy.java @@ -39,7 +39,6 @@ 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.HttpRequest; -import org.apache.hc.core5.http.HttpVersion; import org.apache.hc.core5.http.message.BasicHeader; import org.apache.hc.core5.http.message.BasicHttpRequest; import org.junit.Before; @@ -432,7 +431,7 @@ public class TestCacheValidityPolicy { new BasicHeader("Cache-Control", "max-age=5, stale-if-error=15") }; final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(now, now, headers); - final HttpRequest req = new BasicHttpRequest("GET","/",HttpVersion.HTTP_1_1); + final HttpRequest req = new BasicHttpRequest("GET","/"); assertTrue(impl.mayReturnStaleIfError(req, entry, now)); } @@ -443,7 +442,7 @@ public class TestCacheValidityPolicy { new BasicHeader("Cache-Control", "max-age=5") }; final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(now, now, headers); - final HttpRequest req = new BasicHttpRequest("GET","/",HttpVersion.HTTP_1_1); + final HttpRequest req = new BasicHttpRequest("GET","/"); req.setHeader("Cache-Control","stale-if-error=15"); assertTrue(impl.mayReturnStaleIfError(req, entry, now)); } @@ -455,7 +454,7 @@ public class TestCacheValidityPolicy { new BasicHeader("Cache-Control", "max-age=5, stale-if-error=1") }; final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(now, now, headers); - final HttpRequest req = new BasicHttpRequest("GET","/",HttpVersion.HTTP_1_1); + final HttpRequest req = new BasicHttpRequest("GET","/"); assertFalse(impl.mayReturnStaleIfError(req, entry, now)); } @@ -466,7 +465,7 @@ public class TestCacheValidityPolicy { new BasicHeader("Cache-Control", "max-age=5") }; final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(now, now, headers); - final HttpRequest req = new BasicHttpRequest("GET","/",HttpVersion.HTTP_1_1); + final HttpRequest req = new BasicHttpRequest("GET","/"); req.setHeader("Cache-Control","stale-if-error=1"); assertFalse(impl.mayReturnStaleIfError(req, entry, now)); } diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCachedHttpResponseGenerator.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCachedHttpResponseGenerator.java index ef3b795b3..78a2a93a7 100644 --- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCachedHttpResponseGenerator.java +++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCachedHttpResponseGenerator.java @@ -35,11 +35,12 @@ import static org.mockito.Mockito.when; import java.util.Date; import java.util.HashMap; +import org.apache.hc.client5.http.HttpRoute; import org.apache.hc.client5.http.cache.HttpCacheEntry; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpHost; -import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.message.BasicHeader; import org.junit.Assert; import org.junit.Before; @@ -49,16 +50,18 @@ import org.junit.Test; public class TestCachedHttpResponseGenerator { private HttpHost host; + private HttpRoute route; private HttpCacheEntry entry; - private HttpRequestWrapper request; + private RoutedHttpRequest request; private CacheValidityPolicy mockValidityPolicy; private CachedHttpResponseGenerator impl; @Before public void setUp() { host = new HttpHost("foo.example.com", 80); + route = new HttpRoute(host); entry = HttpTestUtils.makeCacheEntry(new HashMap()); - request = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); + request = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); mockValidityPolicy = mock(CacheValidityPolicy.class); impl = new CachedHttpResponseGenerator(mockValidityPolicy); } @@ -68,7 +71,7 @@ public class TestCachedHttpResponseGenerator { final byte[] buf = new byte[] { 1, 2, 3, 4, 5 }; final HttpCacheEntry entry1 = HttpTestUtils.makeCacheEntry(buf); - final HttpResponse response = impl.generateResponse(request, entry1); + final ClassicHttpResponse response = impl.generateResponse(request, entry1); final Header length = response.getFirstHeader("Content-Length"); Assert.assertNotNull("Content-Length Header is missing", length); @@ -84,7 +87,7 @@ public class TestCachedHttpResponseGenerator { final byte[] buf = new byte[] { 1, 2, 3, 4, 5 }; final HttpCacheEntry entry1 = HttpTestUtils.makeCacheEntry(hdrs, buf); - final HttpResponse response = impl.generateResponse(request, entry1); + final ClassicHttpResponse response = impl.generateResponse(request, entry1); final Header length = response.getFirstHeader("Content-Length"); @@ -93,27 +96,27 @@ public class TestCachedHttpResponseGenerator { @Test public void testResponseMatchesCacheEntry() { - final HttpResponse response = impl.generateResponse(request, entry); + final ClassicHttpResponse response = impl.generateResponse(request, entry); Assert.assertTrue(response.containsHeader("Content-Length")); - Assert.assertSame("HTTP", response.getProtocolVersion().getProtocol()); - Assert.assertEquals(1, response.getProtocolVersion().getMajor()); - Assert.assertEquals(1, response.getProtocolVersion().getMinor()); + Assert.assertSame("HTTP", response.getVersion().getProtocol()); + Assert.assertEquals(1, response.getVersion().getMajor()); + Assert.assertEquals(1, response.getVersion().getMinor()); } @Test public void testResponseStatusCodeMatchesCacheEntry() { - final HttpResponse response = impl.generateResponse(request, entry); + final ClassicHttpResponse response = impl.generateResponse(request, entry); - Assert.assertEquals(entry.getStatusCode(), response.getStatusLine().getStatusCode()); + Assert.assertEquals(entry.getStatus(), response.getCode()); } @Test public void testAgeHeaderIsPopulatedWithCurrentAgeOfCacheEntryIfNonZero() { currentAge(10L); - final HttpResponse response = impl.generateResponse(request, entry); + final ClassicHttpResponse response = impl.generateResponse(request, entry); verify(mockValidityPolicy).getCurrentAgeSecs(same(entry), isA(Date.class)); @@ -126,7 +129,7 @@ public class TestCachedHttpResponseGenerator { public void testAgeHeaderIsNotPopulatedIfCurrentAgeOfCacheEntryIsZero() { currentAge(0L); - final HttpResponse response = impl.generateResponse(request, entry); + final ClassicHttpResponse response = impl.generateResponse(request, entry); verify(mockValidityPolicy).getCurrentAgeSecs(same(entry), isA(Date.class)); @@ -138,7 +141,7 @@ public class TestCachedHttpResponseGenerator { public void testAgeHeaderIsPopulatedWithMaxAgeIfCurrentAgeTooBig() { currentAge(CacheValidityPolicy.MAX_AGE + 1L); - final HttpResponse response = impl.generateResponse(request, entry); + final ClassicHttpResponse response = impl.generateResponse(request, entry); verify(mockValidityPolicy).getCurrentAgeSecs(same(entry), isA(Date.class)); @@ -155,15 +158,15 @@ public class TestCachedHttpResponseGenerator { @Test public void testResponseContainsEntityToServeGETRequestIfEntryContainsResource() throws Exception { - final HttpResponse response = impl.generateResponse(request, entry); + final ClassicHttpResponse response = impl.generateResponse(request, entry); Assert.assertNotNull(response.getEntity()); } @Test public void testResponseDoesNotContainEntityToServeHEADRequestIfEntryContainsResource() throws Exception { - final HttpRequestWrapper headRequest = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultHEADRequest(), host); - final HttpResponse response = impl.generateResponse(headRequest, entry); + final RoutedHttpRequest headRequest = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultHEADRequest(), route); + final ClassicHttpResponse response = impl.generateResponse(headRequest, entry); Assert.assertNull(response.getEntity()); } diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCachedResponseSuitabilityChecker.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCachedResponseSuitabilityChecker.java index d381cdc40..65b28b72b 100644 --- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCachedResponseSuitabilityChecker.java +++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCachedResponseSuitabilityChecker.java @@ -33,7 +33,6 @@ import org.apache.hc.client5.http.utils.DateUtils; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpRequest; -import org.apache.hc.core5.http.HttpVersion; import org.apache.hc.core5.http.message.BasicHeader; import org.apache.hc.core5.http.message.BasicHttpRequest; import org.junit.Assert; @@ -60,7 +59,7 @@ public class TestCachedResponseSuitabilityChecker { nineSecondsAgo = new Date(now.getTime() - 9 * 1000L); host = new HttpHost("foo.example.com"); - request = new BasicHttpRequest("GET", "/foo", HttpVersion.HTTP_1_1); + request = new BasicHttpRequest("GET", "/foo"); entry = HttpTestUtils.makeCacheEntry(); impl = new CachedResponseSuitabilityChecker(CacheConfig.DEFAULT); @@ -253,7 +252,7 @@ public class TestCachedResponseSuitabilityChecker { @Test public void testSuitableIfRequestMethodisHEAD() { - final HttpRequest headRequest = new BasicHttpRequest("HEAD", "/foo", HttpVersion.HTTP_1_1); + final HttpRequest headRequest = new BasicHttpRequest("HEAD", "/foo"); final Header[] headers = { new BasicHeader("Date", DateUtils.formatDate(tenSecondsAgo)), new BasicHeader("Cache-Control", "max-age=3600"), @@ -316,7 +315,7 @@ public class TestCachedResponseSuitabilityChecker { @Test public void testSuitableForHEADIfHeadResponseCachingEnabledAndEntryDoesNotSpecifyARequestMethod() { - final HttpRequest headRequest = new BasicHttpRequest("HEAD", "/foo", HttpVersion.HTTP_1_1); + final HttpRequest headRequest = new BasicHttpRequest("HEAD", "/foo"); impl = new CachedResponseSuitabilityChecker(CacheConfig.custom().build()); final Header[] headers = { new BasicHeader("Date", DateUtils.formatDate(tenSecondsAgo)), diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCachingExec.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCachingExec.java index 89a3fec0b..c71d71f3c 100644 --- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCachingExec.java +++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCachingExec.java @@ -45,15 +45,14 @@ import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; -import org.apache.hc.client5.http.HttpRoute; import org.apache.hc.client5.http.cache.HttpCacheEntry; import org.apache.hc.client5.http.impl.sync.ClientExecChain; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpExecutionAware; import org.apache.hc.client5.http.methods.HttpGet; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.utils.DateUtils; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HeaderElements; import org.apache.hc.core5.http.HttpHeaders; import org.apache.hc.core5.http.HttpHost; @@ -61,10 +60,9 @@ 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.HttpVersion; -import org.apache.hc.core5.http.entity.InputStreamEntity; -import org.apache.hc.core5.http.message.BasicHttpRequest; -import org.apache.hc.core5.http.message.BasicHttpResponse; -import org.apache.hc.core5.http.message.BasicStatusLine; +import org.apache.hc.core5.http.io.entity.InputStreamEntity; +import org.apache.hc.core5.http.message.BasicClassicHttpRequest; +import org.apache.hc.core5.http.message.BasicClassicHttpResponse; import org.easymock.EasyMock; import org.easymock.IExpectationSetters; import org.junit.Assert; @@ -85,7 +83,7 @@ public class TestCachingExec extends TestCachingExecChain { private CachingExec impl; private boolean mockedImpl; - private CloseableHttpResponse mockBackendResponse; + private ClassicHttpResponse mockBackendResponse; private Date requestDate; private Date responseDate; @@ -95,7 +93,7 @@ public class TestCachingExec extends TestCachingExecChain { public void setUp() { super.setUp(); - mockBackendResponse = createNiceMock(CloseableHttpResponse.class); + mockBackendResponse = createNiceMock(ClassicHttpResponse.class); requestDate = new Date(System.currentTimeMillis() - 1000); responseDate = new Date(); @@ -162,7 +160,7 @@ public class TestCachingExec extends TestCachingExecChain { requestIsFatallyNonCompliant(null); replayMocks(); - final HttpResponse result = impl.execute(route, request, context); + final HttpResponse result = impl.execute(request, context); verifyMocks(); Assert.assertSame(mockBackendResponse, result); @@ -181,7 +179,7 @@ public class TestCachingExec extends TestCachingExecChain { implExpectsAnyRequestAndReturn(mockBackendResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context); + final HttpResponse result = impl.execute(request, context); verifyMocks(); Assert.assertSame(mockBackendResponse, result); @@ -203,12 +201,11 @@ public class TestCachingExec extends TestCachingExecChain { expect(mockConditionalRequestBuilder.buildConditionalRequest(request, mockCacheEntry)) .andReturn(request); backendExpectsRequestAndReturn(request, mockBackendResponse); - expect(mockBackendResponse.getProtocolVersion()).andReturn(HttpVersion.HTTP_1_1); - expect(mockBackendResponse.getStatusLine()).andReturn( - new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "Ok")); + expect(mockBackendResponse.getVersion()).andReturn(HttpVersion.HTTP_1_1).anyTimes(); + expect(mockBackendResponse.getCode()).andReturn(200); replayMocks(); - final HttpResponse result = impl.execute(route, request, context); + final HttpResponse result = impl.execute(request, context); verifyMocks(); Assert.assertSame(mockBackendResponse, result); @@ -232,14 +229,13 @@ public class TestCachingExec extends TestCachingExecChain { mayReturnStaleWhileRevalidating(false); expect(impl.revalidateCacheEntry( - isA(HttpRoute.class), - isA(HttpRequestWrapper.class), + isA(RoutedHttpRequest.class), isA(HttpClientContext.class), (HttpExecutionAware) isNull(), isA(HttpCacheEntry.class))).andReturn(mockBackendResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context); + final HttpResponse result = impl.execute(request, context); verifyMocks(); Assert.assertSame(mockBackendResponse, result); @@ -252,12 +248,10 @@ public class TestCachingExec extends TestCachingExecChain { public void testRevalidationCallsHandleBackEndResponseWhenNot200Or304() throws Exception { mockImplMethods(GET_CURRENT_DATE, HANDLE_BACKEND_RESPONSE); - final HttpRequestWrapper validate = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final CloseableHttpResponse originResponse = Proxies.enhanceResponse( - new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_FOUND, "Not Found")); - final CloseableHttpResponse finalResponse = Proxies.enhanceResponse( - HttpTestUtils.make200Response()); + final RoutedHttpRequest validate = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse originResponse = new BasicClassicHttpResponse(HttpStatus.SC_NOT_FOUND, "Not Found"); + final ClassicHttpResponse finalResponse = HttpTestUtils.make200Response(); conditionalRequestBuilderReturns(validate); getCurrentDateReturns(requestDate); @@ -272,7 +266,7 @@ public class TestCachingExec extends TestCachingExecChain { replayMocks(); final HttpResponse result = - impl.revalidateCacheEntry(route, request, context, null, entry); + impl.revalidateCacheEntry(request, context, null, entry); verifyMocks(); Assert.assertSame(finalResponse, result); @@ -284,10 +278,9 @@ public class TestCachingExec extends TestCachingExecChain { mockImplMethods(GET_CURRENT_DATE); - final HttpRequestWrapper validate = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse originResponse = Proxies.enhanceResponse( - new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_MODIFIED, "Not Modified")); + final RoutedHttpRequest validate = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse originResponse = HttpTestUtils.make304Response(); final HttpCacheEntry updatedEntry = HttpTestUtils.makeCacheEntry(); conditionalRequestBuilderReturns(validate); @@ -306,7 +299,7 @@ public class TestCachingExec extends TestCachingExecChain { responseIsGeneratedFromCache(); replayMocks(); - impl.revalidateCacheEntry(route, request, context, null, entry); + impl.revalidateCacheEntry(request, context, null, entry); verifyMocks(); } @@ -318,17 +311,16 @@ public class TestCachingExec extends TestCachingExecChain { // Fail on an unexpected request, rather than causing a later NPE EasyMock.resetToStrict(mockBackend); - final HttpRequestWrapper validate = HttpRequestWrapper.wrap( - new HttpGet("http://foo.example.com/resource"), host); - final HttpRequestWrapper relativeValidate = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/resource", HttpVersion.HTTP_1_1), host); - final CloseableHttpResponse originResponse = Proxies.enhanceResponse( - new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "Okay")); + final RoutedHttpRequest validate = RoutedHttpRequest.adapt( + new HttpGet("http://foo.example.com/resource"), route); + final RoutedHttpRequest relativeValidate = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/resource"), route); + final ClassicHttpResponse originResponse = new BasicClassicHttpResponse(HttpStatus.SC_OK, "Okay"); conditionalRequestBuilderReturns(validate); getCurrentDateReturns(requestDate); - final CloseableHttpResponse resp = mockBackend.execute(EasyMock.isA(HttpRoute.class), + final ClassicHttpResponse resp = mockBackend.execute( eqRequest(relativeValidate), EasyMock.isA(HttpClientContext.class), EasyMock. isNull()); expect(resp).andReturn(originResponse); @@ -336,7 +328,7 @@ public class TestCachingExec extends TestCachingExecChain { getCurrentDateReturns(responseDate); replayMocks(); - impl.revalidateCacheEntry(route, request, context, null, entry); + impl.revalidateCacheEntry(request, context, null, entry); verifyMocks(); } @@ -344,7 +336,7 @@ public class TestCachingExec extends TestCachingExecChain { public void testEndlessResponsesArePassedThrough() throws Exception { impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp1.setHeader("Date", DateUtils.formatDate(new Date())); resp1.setHeader("Server", "MockOrigin/1.0"); resp1.setHeader(HttpHeaders.TRANSFER_ENCODING, HeaderElements.CHUNKED_ENCODING); @@ -374,17 +366,16 @@ public class TestCachingExec extends TestCachingExecChain { } }, -1)); - final CloseableHttpResponse resp = mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + final ClassicHttpResponse resp = mockBackend.execute( + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull()); - EasyMock.expect(resp).andReturn(Proxies.enhanceResponse(resp1)); + EasyMock.expect(resp).andReturn(resp1); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); replayMocks(); - final CloseableHttpResponse resp2 = impl.execute(route, req1, context, null); + final ClassicHttpResponse resp2 = impl.execute(req1, context, null); maxlength.set(size.get() * 2); verifyMocks(); assertTrue(HttpTestUtils.semanticallyTransparent(resp1, resp2)); @@ -393,7 +384,7 @@ public class TestCachingExec extends TestCachingExecChain { @Test public void testCallBackendMakesBackEndRequestAndHandlesResponse() throws Exception { mockImplMethods(GET_CURRENT_DATE, HANDLE_BACKEND_RESPONSE); - final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); + final ClassicHttpResponse resp = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); getCurrentDateReturns(requestDate); backendExpectsRequestAndReturn(request, resp); getCurrentDateReturns(responseDate); @@ -401,16 +392,15 @@ public class TestCachingExec extends TestCachingExecChain { replayMocks(); - impl.callBackend(route, request, context, null); + impl.callBackend(request, context, null); verifyMocks(); } - private IExpectationSetters implExpectsAnyRequestAndReturn( - final CloseableHttpResponse response) throws Exception { - final CloseableHttpResponse resp = impl.callBackend( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + private IExpectationSetters implExpectsAnyRequestAndReturn( + final ClassicHttpResponse response) throws Exception { + final ClassicHttpResponse resp = impl.callBackend( + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull()); return EasyMock.expect(resp).andReturn(response); @@ -430,7 +420,7 @@ public class TestCachingExec extends TestCachingExecChain { expect(impl.getCurrentDate()).andReturn(date); } - private void handleBackendResponseReturnsResponse(final HttpRequestWrapper request, final HttpResponse response) + private void handleBackendResponseReturnsResponse(final RoutedHttpRequest request, final ClassicHttpResponse response) throws IOException { expect( impl.handleBackendResponse( @@ -438,8 +428,7 @@ public class TestCachingExec extends TestCachingExecChain { isA(HttpClientContext.class), isA(Date.class), isA(Date.class), - isA(CloseableHttpResponse.class))).andReturn( - Proxies.enhanceResponse(response)); + isA(ClassicHttpResponse.class))).andReturn(response); } private void mockImplMethods(final String... methods) { 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 be0906ed8..118496b70 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 @@ -54,28 +54,29 @@ import org.apache.hc.client5.http.cache.HttpCacheContext; import org.apache.hc.client5.http.cache.HttpCacheEntry; import org.apache.hc.client5.http.cache.HttpCacheStorage; import org.apache.hc.client5.http.impl.sync.ClientExecChain; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpExecutionAware; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.client5.http.methods.HttpOptions; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; import org.apache.hc.client5.http.methods.HttpUriRequest; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.ClientProtocolException; import org.apache.hc.client5.http.protocol.HttpClientContext; -import org.apache.hc.client5.http.sync.ResponseHandler; 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.HttpHost; 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.HttpVersion; -import org.apache.hc.core5.http.StatusLine; -import org.apache.hc.core5.http.entity.EntityUtils; -import org.apache.hc.core5.http.entity.InputStreamEntity; +import org.apache.hc.core5.http.io.ResponseHandler; +import org.apache.hc.core5.http.io.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.InputStreamEntity; +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.BasicHttpRequest; -import org.apache.hc.core5.http.message.BasicHttpResponse; +import org.apache.hc.core5.net.URIAuthority; import org.easymock.Capture; import org.easymock.EasyMock; import org.easymock.IExpectationSetters; @@ -101,10 +102,9 @@ public abstract class TestCachingExecChain { protected CachedHttpResponseGenerator mockResponseGenerator; private ResponseHandler mockHandler; private HttpUriRequest mockUriRequest; - private CloseableHttpResponse mockCachedResponse; + private ClassicHttpResponse mockCachedResponse; protected ConditionalRequestBuilder mockConditionalRequestBuilder; private HttpRequest mockConditionalRequest; - private StatusLine mockStatusLine; protected ResponseProtocolCompliance mockResponseProtocolCompliance; protected RequestProtocolCompliance mockRequestProtocolCompliance; protected CacheConfig config; @@ -112,7 +112,7 @@ public abstract class TestCachingExecChain { protected HttpRoute route; protected HttpHost host; - protected HttpRequestWrapper request; + protected RoutedHttpRequest request; protected HttpCacheContext context; protected HttpCacheEntry entry; @@ -129,10 +129,9 @@ public abstract class TestCachingExecChain { mockUriRequest = createNiceMock(HttpUriRequest.class); mockCacheEntry = createNiceMock(HttpCacheEntry.class); mockResponseGenerator = createNiceMock(CachedHttpResponseGenerator.class); - mockCachedResponse = createNiceMock(CloseableHttpResponse.class); + mockCachedResponse = createNiceMock(ClassicHttpResponse.class); mockConditionalRequestBuilder = createNiceMock(ConditionalRequestBuilder.class); mockConditionalRequest = createNiceMock(HttpRequest.class); - mockStatusLine = createNiceMock(StatusLine.class); mockResponseProtocolCompliance = createNiceMock(ResponseProtocolCompliance.class); mockRequestProtocolCompliance = createNiceMock(RequestProtocolCompliance.class); mockStorage = createNiceMock(HttpCacheStorage.class); @@ -141,10 +140,8 @@ public abstract class TestCachingExecChain { host = new HttpHost("foo.example.com", 80); route = new HttpRoute(host); - request = HttpRequestWrapper.wrap(new BasicHttpRequest("GET", "/stuff", - HttpVersion.HTTP_1_1), host); + request = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("GET", "/stuff"), route); context = HttpCacheContext.create(); - context.setTargetHost(host); entry = HttpTestUtils.makeCacheEntry(); impl = createCachingExecChain(mockBackend, mockCache, mockValidityPolicy, mockResponsePolicy, mockResponseGenerator, mockRequestPolicy, mockSuitabilityChecker, @@ -164,7 +161,7 @@ public abstract class TestCachingExecChain { public abstract ClientExecChain createCachingExecChain(ClientExecChain backend, HttpCache cache, CacheConfig config); - public static HttpRequestWrapper eqRequest(final HttpRequestWrapper in) { + public static RoutedHttpRequest eqRequest(final RoutedHttpRequest in) { EasyMock.reportMatcher(new RequestEquivalent(in)); return null; } @@ -188,7 +185,6 @@ public abstract class TestCachingExecChain { replay(mockCachedResponse); replay(mockConditionalRequestBuilder); replay(mockConditionalRequest); - replay(mockStatusLine); replay(mockResponseProtocolCompliance); replay(mockRequestProtocolCompliance); replay(mockStorage); @@ -208,7 +204,6 @@ public abstract class TestCachingExecChain { verify(mockCachedResponse); verify(mockConditionalRequestBuilder); verify(mockConditionalRequest); - verify(mockStatusLine); verify(mockResponseProtocolCompliance); verify(mockRequestProtocolCompliance); verify(mockStorage); @@ -218,17 +213,17 @@ public abstract class TestCachingExecChain { public void testCacheableResponsesGoIntoCache() throws Exception { impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Cache-Control", "max-age=3600"); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); verifyMocks(); } @@ -238,29 +233,29 @@ public abstract class TestCachingExecChain { final Date now = new Date(); final Date fiveSecondsAgo = new Date(now.getTime() - 5 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Date", DateUtils.formatDate(now)); resp1.setHeader("Cache-Control", "max-age=3600"); resp1.setHeader("Etag", "\"new-etag\""); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); req2.setHeader("Cache-Control", "no-cache"); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); resp2.setHeader("ETag", "\"old-etag\""); resp2.setHeader("Date", DateUtils.formatDate(fiveSecondsAgo)); resp2.setHeader("Cache-Control", "max-age=3600"); backendExpectsAnyRequestAndReturn(resp2); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); - final HttpResponse result = impl.execute(route, req3, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); + final ClassicHttpResponse result = impl.execute(req3, context, null); verifyMocks(); assertEquals("\"new-etag\"", result.getFirstHeader("ETag").getValue()); @@ -272,29 +267,29 @@ public abstract class TestCachingExecChain { final Date now = new Date(); final Date fiveSecondsAgo = new Date(now.getTime() - 5 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Date", DateUtils.formatDate(fiveSecondsAgo)); resp1.setHeader("Cache-Control", "max-age=3600"); resp1.setHeader("Etag", "\"old-etag\""); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); req2.setHeader("Cache-Control", "max-age=0"); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); resp2.setHeader("ETag", "\"new-etag\""); resp2.setHeader("Date", DateUtils.formatDate(now)); resp2.setHeader("Cache-Control", "max-age=3600"); backendExpectsAnyRequestAndReturn(resp2); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); - final HttpResponse result = impl.execute(route, req3, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); + final ClassicHttpResponse result = impl.execute(req3, context, null); verifyMocks(); assertEquals("\"new-etag\"", result.getFirstHeader("ETag").getValue()); @@ -320,7 +315,7 @@ public abstract class TestCachingExecChain { entryHasStaleness(0L); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); Assert.assertSame(mockCachedResponse, result); @@ -332,8 +327,8 @@ public abstract class TestCachingExecChain { impl = createCachingExecChain(mockBackend, new BasicHttpCache(new HeapResourceFactory(), mockStorage, configDefault), configDefault); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Cache-Control", "no-cache"); expect(mockStorage.getEntry(isA(String.class))).andReturn(null).anyTimes(); @@ -342,7 +337,7 @@ public abstract class TestCachingExecChain { backendExpectsAnyRequestAndReturn(resp1); replayMocks(); - final HttpResponse result = impl.execute(route, req1, context, null); + final ClassicHttpResponse result = impl.execute(req1, context, null); verifyMocks(); assertTrue(HttpTestUtils.semanticallyTransparent(resp1, result)); @@ -360,7 +355,7 @@ public abstract class TestCachingExecChain { entryHasStaleness(0L); replayMocks(); - impl.execute(route, request, context, null); + impl.execute(request, context, null); verifyMocks(); } @@ -370,13 +365,13 @@ public abstract class TestCachingExecChain { final ClientProtocolException expected = new ClientProtocolException("ouch"); requestIsFatallyNonCompliant(null); - mockRequestProtocolCompliance.makeRequestCompliant((HttpRequestWrapper) anyObject()); + mockRequestProtocolCompliance.makeRequestCompliant((RoutedHttpRequest) anyObject()); expectLastCall().andThrow(expected); boolean gotException = false; replayMocks(); try { - impl.execute(route, request, context, null); + impl.execute(request, context, null); } catch (final ClientProtocolException ex) { Assert.assertSame(expected, ex); gotException = true; @@ -388,44 +383,41 @@ public abstract class TestCachingExecChain { @Test public void testSetsModuleGeneratedResponseContextForCacheOptionsResponse() throws Exception { impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); - final HttpRequestWrapper req = HttpRequestWrapper.wrap(new BasicHttpRequest("OPTIONS", "*", - HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("OPTIONS", "*"), route); req.setHeader("Max-Forwards", "0"); - impl.execute(route, req, context, null); + impl.execute(req, context, null); Assert.assertEquals(CacheResponseStatus.CACHE_MODULE_RESPONSE, context.getCacheResponseStatus()); } @Test - public void testSetsModuleGeneratedResponseContextForFatallyNoncompliantRequest() - throws Exception { + public void testSetsModuleGeneratedResponseContextForFatallyNoncompliantRequest() throws Exception { impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); - final HttpRequestWrapper req = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); + final RoutedHttpRequest req = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); req.setHeader("Range", "bytes=0-50"); req.setHeader("If-Range", "W/\"weak-etag\""); - impl.execute(route, req, context, null); + impl.execute(req, context, null); Assert.assertEquals(CacheResponseStatus.CACHE_MODULE_RESPONSE, context.getCacheResponseStatus()); } @Test - public void testRecordsClientProtocolInViaHeaderIfRequestNotServableFromCache() - throws Exception { + public void testRecordsClientProtocolInViaHeaderIfRequestNotServableFromCache() throws Exception { impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); - final HttpRequestWrapper req = HttpRequestWrapper.wrap(new BasicHttpRequest("GET", "/", - HttpVersion.HTTP_1_0), host); + final ClassicHttpRequest originalRequest = new BasicClassicHttpRequest("GET", "/"); + originalRequest.setVersion(HttpVersion.HTTP_1_0); + final RoutedHttpRequest req = RoutedHttpRequest.adapt(originalRequest, route); req.setHeader("Cache-Control", "no-cache"); - final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_NO_CONTENT, "No Content"); - final Capture cap = new Capture<>(); + final ClassicHttpResponse resp = new BasicClassicHttpResponse(HttpStatus.SC_NO_CONTENT, "No Content"); + final Capture cap = new Capture<>(); backendCaptureRequestAndReturn(cap, resp); replayMocks(); - impl.execute(route, req, context, null); + impl.execute(req, context, null); verifyMocks(); final HttpRequest captured = cap.getValue(); @@ -437,16 +429,15 @@ public abstract class TestCachingExecChain { @Test public void testSetsCacheMissContextIfRequestNotServableFromCache() throws Exception { impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); - final HttpRequestWrapper req = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); + final RoutedHttpRequest req = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); req.setHeader("Cache-Control", "no-cache"); - final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_NO_CONTENT, "No Content"); + final ClassicHttpResponse resp = new BasicClassicHttpResponse(HttpStatus.SC_NO_CONTENT, "No Content"); backendExpectsAnyRequestAndReturn(resp); replayMocks(); - impl.execute(route, req, context, null); + impl.execute(req, context, null); verifyMocks(); Assert.assertEquals(CacheResponseStatus.CACHE_MISS, context.getCacheResponseStatus()); } @@ -454,16 +445,15 @@ public abstract class TestCachingExecChain { @Test public void testSetsViaHeaderOnResponseIfRequestNotServableFromCache() throws Exception { impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); - final HttpRequestWrapper req = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); + final RoutedHttpRequest req = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); req.setHeader("Cache-Control", "no-cache"); - final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_NO_CONTENT, "No Content"); + final ClassicHttpResponse resp = new BasicClassicHttpResponse(HttpStatus.SC_NO_CONTENT, "No Content"); backendExpectsAnyRequestAndReturn(resp); replayMocks(); - final HttpResponse result = impl.execute(route, req, context, null); + final ClassicHttpResponse result = impl.execute(req, context, null); verifyMocks(); Assert.assertNotNull(result.getFirstHeader("Via")); } @@ -471,9 +461,9 @@ public abstract class TestCachingExecChain { @Test public void testSetsViaHeaderOnResponseForCacheMiss() throws Exception { impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp1.setEntity(HttpTestUtils.makeBody(128)); resp1.setHeader("Content-Length", "128"); @@ -484,7 +474,7 @@ public abstract class TestCachingExecChain { backendExpectsAnyRequestAndReturn(resp1); replayMocks(); - final HttpResponse result = impl.execute(route, req1, context, null); + final ClassicHttpResponse result = impl.execute(req1, context, null); verifyMocks(); Assert.assertNotNull(result.getFirstHeader("Via")); } @@ -492,11 +482,11 @@ public abstract class TestCachingExecChain { @Test public void testSetsCacheHitContextIfRequestServedFromCache() throws Exception { impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp1.setEntity(HttpTestUtils.makeBody(128)); resp1.setHeader("Content-Length", "128"); @@ -507,8 +497,8 @@ public abstract class TestCachingExecChain { backendExpectsAnyRequestAndReturn(resp1); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); verifyMocks(); Assert.assertEquals(CacheResponseStatus.CACHE_HIT, context.getCacheResponseStatus()); } @@ -516,11 +506,11 @@ public abstract class TestCachingExecChain { @Test public void testSetsViaHeaderOnResponseIfRequestServedFromCache() throws Exception { impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp1.setEntity(HttpTestUtils.makeBody(128)); resp1.setHeader("Content-Length", "128"); @@ -531,8 +521,8 @@ public abstract class TestCachingExecChain { backendExpectsAnyRequestAndReturn(resp1); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); Assert.assertNotNull(result.getFirstHeader("Via")); } @@ -542,12 +532,12 @@ public abstract class TestCachingExecChain { final Date now = new Date(); final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); req2.addHeader("If-Modified-Since", DateUtils.formatDate(now)); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp1.setEntity(HttpTestUtils.makeBody(128)); resp1.setHeader("Content-Length", "128"); @@ -559,10 +549,10 @@ public abstract class TestCachingExecChain { backendExpectsAnyRequestAndReturn(resp1); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getCode()); } @@ -572,34 +562,32 @@ public abstract class TestCachingExecChain { final Date oneHourAgo = new Date(now.getTime() - 3600 * 1000L); final Date inTenMinutes = new Date(now.getTime() + 600 * 1000L); impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); req1.addHeader("If-Modified-Since", DateUtils.formatDate(oneHourAgo)); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); req2.addHeader("If-Modified-Since", DateUtils.formatDate(oneHourAgo)); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_NOT_MODIFIED, "Not modified"); + final ClassicHttpResponse resp1 = HttpTestUtils.make304Response(); resp1.setHeader("Date", DateUtils.formatDate(now)); resp1.setHeader("Cache-control", "max-age=600"); resp1.setHeader("Expires", DateUtils.formatDate(inTenMinutes)); expect( - mockBackend.execute(eq(route), isA(HttpRequestWrapper.class), - isA(HttpClientContext.class), (HttpExecutionAware) isNull())).andReturn( - Proxies.enhanceResponse(resp1)).once(); + mockBackend.execute(isA(RoutedHttpRequest.class), + isA(HttpClientContext.class), (HttpExecutionAware) isNull())).andReturn(resp1).once(); expect( - mockBackend.execute(eq(route), isA(HttpRequestWrapper.class), + mockBackend.execute(isA(RoutedHttpRequest.class), isA(HttpClientContext.class), (HttpExecutionAware) isNull())).andThrow( new AssertionFailedError("Should have reused cached 304 response")).anyTimes(); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getCode()); Assert.assertFalse(result.containsHeader("Last-Modified")); } @@ -608,12 +596,12 @@ public abstract class TestCachingExecChain { final Date now = new Date(); final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp1.setEntity(HttpTestUtils.makeBody(128)); resp1.setHeader("Content-Length", "128"); @@ -625,16 +613,16 @@ public abstract class TestCachingExecChain { // The variant has been modified since this date req2.addHeader("If-Modified-Since", DateUtils.formatDate(tenSecondsAgo)); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); backendExpectsAnyRequestAndReturn(resp1); backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - Assert.assertEquals(HttpStatus.SC_OK, result.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_OK, result.getCode()); } @@ -643,12 +631,12 @@ public abstract class TestCachingExecChain { final Date now = new Date(); final Date tenSecondsAfter = new Date(now.getTime() + 10 * 1000L); impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp1.setEntity(HttpTestUtils.makeBody(128)); resp1.setHeader("Content-Length", "128"); @@ -663,22 +651,22 @@ public abstract class TestCachingExecChain { backendExpectsAnyRequestAndReturn(resp1).times(2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - Assert.assertEquals(HttpStatus.SC_OK, result.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_OK, result.getCode()); } @Test public void testReturns304ForIfNoneMatchHeaderIfRequestServedFromCache() throws Exception { impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); req2.addHeader("If-None-Match", "*"); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp1.setEntity(HttpTestUtils.makeBody(128)); resp1.setHeader("Content-Length", "128"); @@ -689,22 +677,22 @@ public abstract class TestCachingExecChain { backendExpectsAnyRequestAndReturn(resp1); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getCode()); } @Test public void testReturns200ForIfNoneMatchHeaderFails() throws Exception { impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp1.setEntity(HttpTestUtils.makeBody(128)); resp1.setHeader("Content-Length", "128"); @@ -714,31 +702,30 @@ public abstract class TestCachingExecChain { req2.addHeader("If-None-Match", "\"abc\""); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); backendExpectsAnyRequestAndReturn(resp1); backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - Assert.assertEquals(200, result.getStatusLine().getStatusCode()); + Assert.assertEquals(200, result.getCode()); } @Test - public void testReturns304ForIfNoneMatchHeaderAndIfModifiedSinceIfRequestServedFromCache() - throws Exception { + public void testReturns304ForIfNoneMatchHeaderAndIfModifiedSinceIfRequestServedFromCache() throws Exception { impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); final Date now = new Date(); final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp1.setEntity(HttpTestUtils.makeBody(128)); resp1.setHeader("Content-Length", "128"); @@ -753,10 +740,10 @@ public abstract class TestCachingExecChain { backendExpectsAnyRequestAndReturn(resp1); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getCode()); } @@ -765,13 +752,13 @@ public abstract class TestCachingExecChain { impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); final Date now = new Date(); final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); req2.addHeader("If-None-Match", "\"abc\""); req2.addHeader("If-Modified-Since", DateUtils.formatDate(now)); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp1.setEntity(HttpTestUtils.makeBody(128)); resp1.setHeader("Content-Length", "128"); @@ -784,33 +771,31 @@ public abstract class TestCachingExecChain { backendExpectsAnyRequestAndReturn(resp1); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - Assert.assertEquals(200, result.getStatusLine().getStatusCode()); + Assert.assertEquals(200, result.getCode()); } @Test - public void testReturns200ForOptionsFollowedByGetIfAuthorizationHeaderAndSharedCache() - throws Exception { + public void testReturns200ForOptionsFollowedByGetIfAuthorizationHeaderAndSharedCache() throws Exception { impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.custom() .setSharedCache(true).build()); final Date now = new Date(); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpOptions( - "http://foo.example.com/"), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new HttpOptions( + "http://foo.example.com/"), route); req1.setHeader("Authorization", "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); req2.setHeader("Authorization", "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_NO_CONTENT, "No Content"); + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_NO_CONTENT, "No Content"); resp1.setHeader("Content-Length", "0"); resp1.setHeader("ETag", "\"options-etag\""); resp1.setHeader("Date", DateUtils.formatDate(now)); resp1.setHeader("Cache-Control", "public, max-age=3600"); resp1.setHeader("Last-Modified", DateUtils.formatDate(now)); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp1.setEntity(HttpTestUtils.makeBody(128)); resp1.setHeader("Content-Length", "128"); @@ -823,10 +808,10 @@ public abstract class TestCachingExecChain { backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - Assert.assertEquals(200, result.getStatusLine().getStatusCode()); + Assert.assertEquals(200, result.getCode()); } @Test @@ -835,12 +820,12 @@ public abstract class TestCachingExecChain { final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp1.setEntity(HttpTestUtils.makeBody(128)); resp1.setHeader("Content-Length", "128"); @@ -848,7 +833,7 @@ public abstract class TestCachingExecChain { resp1.setHeader("Date", DateUtils.formatDate(tenSecondsAgo)); resp1.setHeader("Cache-Control", "public, max-age=5"); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp2.setEntity(HttpTestUtils.makeBody(128)); resp2.setHeader("Content-Length", "128"); @@ -860,8 +845,8 @@ public abstract class TestCachingExecChain { backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); verifyMocks(); Assert.assertEquals(CacheResponseStatus.VALIDATED, context.getCacheResponseStatus()); } @@ -872,12 +857,12 @@ public abstract class TestCachingExecChain { final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp1.setEntity(HttpTestUtils.makeBody(128)); resp1.setHeader("Content-Length", "128"); @@ -885,7 +870,7 @@ public abstract class TestCachingExecChain { resp1.setHeader("Date", DateUtils.formatDate(tenSecondsAgo)); resp1.setHeader("Cache-Control", "public, max-age=5"); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp2.setEntity(HttpTestUtils.makeBody(128)); resp2.setHeader("Content-Length", "128"); @@ -897,8 +882,8 @@ public abstract class TestCachingExecChain { backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); Assert.assertNotNull(result.getFirstHeader("Via")); } @@ -909,12 +894,12 @@ public abstract class TestCachingExecChain { final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp1.setEntity(HttpTestUtils.makeBody(128)); resp1.setHeader("Content-Length", "128"); @@ -926,8 +911,8 @@ public abstract class TestCachingExecChain { backendExpectsAnyRequestAndThrows(new IOException()); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); verifyMocks(); Assert.assertEquals(CacheResponseStatus.CACHE_MODULE_RESPONSE, context.getCacheResponseStatus()); @@ -939,12 +924,12 @@ public abstract class TestCachingExecChain { final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp1.setEntity(HttpTestUtils.makeBody(128)); resp1.setHeader("Content-Length", "128"); @@ -956,8 +941,8 @@ public abstract class TestCachingExecChain { backendExpectsAnyRequestAndThrows(new IOException()); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); verifyMocks(); Assert.assertEquals(CacheResponseStatus.CACHE_HIT, context.getCacheResponseStatus()); } @@ -968,12 +953,12 @@ public abstract class TestCachingExecChain { final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp1.setEntity(HttpTestUtils.makeBody(128)); resp1.setHeader("Content-Length", "128"); @@ -985,8 +970,8 @@ public abstract class TestCachingExecChain { backendExpectsAnyRequestAndThrows(new IOException()); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); Assert.assertNotNull(result.getFirstHeader("Via")); } @@ -998,12 +983,12 @@ public abstract class TestCachingExecChain { final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp1.setEntity(HttpTestUtils.makeBody(128)); resp1.setHeader("Content-Length", "128"); @@ -1012,8 +997,7 @@ public abstract class TestCachingExecChain { resp1.setHeader("Cache-Control", "public, max-age=5"); req2.addHeader("If-None-Match", "\"etag\""); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_NOT_MODIFIED, "Not Modified"); + final ClassicHttpResponse resp2 = HttpTestUtils.make304Response(); resp2.setHeader("ETag", "\"etag\""); resp2.setHeader("Date", DateUtils.formatDate(now)); resp2.setHeader("Cache-Control", "public, max-age=5"); @@ -1021,11 +1005,11 @@ public abstract class TestCachingExecChain { backendExpectsAnyRequestAndReturn(resp1); backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getCode()); } @Test @@ -1035,12 +1019,12 @@ public abstract class TestCachingExecChain { final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp1.setEntity(HttpTestUtils.makeBody(128)); resp1.setHeader("Content-Length", "128"); @@ -1049,7 +1033,7 @@ public abstract class TestCachingExecChain { resp1.setHeader("Cache-Control", "public, max-age=5"); req2.addHeader("If-None-Match", "\"etag\""); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp2.setEntity(HttpTestUtils.makeBody(128)); resp2.setHeader("Content-Length", "128"); @@ -1061,11 +1045,11 @@ public abstract class TestCachingExecChain { backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - Assert.assertEquals(HttpStatus.SC_OK, result.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_OK, result.getCode()); } @Test @@ -1075,12 +1059,12 @@ public abstract class TestCachingExecChain { final Date now = new Date(); final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp1.setEntity(HttpTestUtils.makeBody(128)); resp1.setHeader("Content-Length", "128"); @@ -1090,8 +1074,7 @@ public abstract class TestCachingExecChain { resp1.setHeader("Cache-Control", "public, max-age=5"); req2.addHeader("If-Modified-Since", DateUtils.formatDate(tenSecondsAgo)); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_NOT_MODIFIED, "Not Modified"); + final ClassicHttpResponse resp2 = HttpTestUtils.make304Response(); resp2.setHeader("ETag", "\"etag\""); resp2.setHeader("Date", DateUtils.formatDate(tenSecondsAgo)); resp1.setHeader("Last-Modified", DateUtils.formatDate(tenSecondsAgo)); @@ -1101,11 +1084,11 @@ public abstract class TestCachingExecChain { backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getCode()); } @Test @@ -1114,12 +1097,12 @@ public abstract class TestCachingExecChain { final Date now = new Date(); final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp1.setEntity(HttpTestUtils.makeBody(128)); resp1.setHeader("Content-Length", "128"); @@ -1129,7 +1112,7 @@ public abstract class TestCachingExecChain { resp1.setHeader("Cache-Control", "public, max-age=5"); req2.addHeader("If-Modified-Since", DateUtils.formatDate(tenSecondsAgo)); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp2.setEntity(HttpTestUtils.makeBody(128)); resp2.setHeader("Content-Length", "128"); @@ -1142,11 +1125,11 @@ public abstract class TestCachingExecChain { backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - Assert.assertEquals(HttpStatus.SC_OK, result.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_OK, result.getCode()); } @Test @@ -1154,11 +1137,11 @@ public abstract class TestCachingExecChain { impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); final Date now = new Date(); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com"), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com"), route); req1.addHeader("Accept-Encoding", "gzip"); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp1.setEntity(HttpTestUtils.makeBody(128)); resp1.setHeader("Content-Length", "128"); @@ -1167,16 +1150,16 @@ public abstract class TestCachingExecChain { resp1.setHeader("Vary", "Accept-Encoding"); resp1.setHeader("Cache-Control", "public, max-age=3600"); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com"), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com"), route); req2.addHeader("Accept-Encoding", "deflate"); - final HttpRequestWrapper req2Server = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com"), host); + final RoutedHttpRequest req2Server = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com"), route); req2Server.addHeader("Accept-Encoding", "deflate"); req2Server.addHeader("If-None-Match", "\"gzip_etag\""); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp2.setEntity(HttpTestUtils.makeBody(128)); resp2.setHeader("Content-Length", "128"); @@ -1185,16 +1168,16 @@ public abstract class TestCachingExecChain { resp2.setHeader("Vary", "Accept-Encoding"); resp2.setHeader("Cache-Control", "public, max-age=3600"); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com"), host); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com"), route); req3.addHeader("Accept-Encoding", "gzip,deflate"); - final HttpRequestWrapper req3Server = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com"), host); + final RoutedHttpRequest req3Server = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com"), route); req3Server.addHeader("Accept-Encoding", "gzip,deflate"); req3Server.addHeader("If-None-Match", "\"gzip_etag\",\"deflate_etag\""); - final HttpResponse resp3 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final ClassicHttpResponse resp3 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp3.setEntity(HttpTestUtils.makeBody(128)); resp3.setHeader("Content-Length", "128"); @@ -1208,16 +1191,16 @@ public abstract class TestCachingExecChain { backendExpectsAnyRequestAndReturn(resp3); replayMocks(); - final HttpResponse result1 = impl.execute(route, req1, context, null); + final ClassicHttpResponse result1 = impl.execute(req1, context, null); - final HttpResponse result2 = impl.execute(route, req2, context, null); + final ClassicHttpResponse result2 = impl.execute(req2, context, null); - final HttpResponse result3 = impl.execute(route, req3, context, null); + final ClassicHttpResponse result3 = impl.execute(req3, context, null); verifyMocks(); - Assert.assertEquals(HttpStatus.SC_OK, result1.getStatusLine().getStatusCode()); - Assert.assertEquals(HttpStatus.SC_OK, result2.getStatusLine().getStatusCode()); - Assert.assertEquals(HttpStatus.SC_OK, result3.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_OK, result1.getCode()); + Assert.assertEquals(HttpStatus.SC_OK, result2.getCode()); + Assert.assertEquals(HttpStatus.SC_OK, result3.getCode()); } @Test @@ -1225,11 +1208,11 @@ public abstract class TestCachingExecChain { impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); final Date now = new Date(); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com"), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com"), route); req1.addHeader("Accept-Encoding", "gzip"); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp1.setEntity(HttpTestUtils.makeBody(128)); resp1.setHeader("Content-Length", "128"); @@ -1238,16 +1221,16 @@ public abstract class TestCachingExecChain { resp1.setHeader("Vary", "Accept-Encoding"); resp1.setHeader("Cache-Control", "public, max-age=3600"); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com"), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com"), route); req2.addHeader("Accept-Encoding", "deflate"); - final HttpRequestWrapper req2Server = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com"), host); + final RoutedHttpRequest req2Server = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com"), route); req2Server.addHeader("Accept-Encoding", "deflate"); req2Server.addHeader("If-None-Match", "\"gzip_etag\""); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp2.setEntity(HttpTestUtils.makeBody(128)); resp2.setHeader("Content-Length", "128"); @@ -1256,18 +1239,17 @@ public abstract class TestCachingExecChain { resp2.setHeader("Vary", "Accept-Encoding"); resp2.setHeader("Cache-Control", "public, max-age=3600"); - final HttpRequestWrapper req4 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com"), host); + final RoutedHttpRequest req4 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com"), route); req4.addHeader("Accept-Encoding", "gzip,identity"); req4.addHeader("If-None-Match", "\"gzip_etag\""); - final HttpRequestWrapper req4Server = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com"), host); + final RoutedHttpRequest req4Server = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com"), route); req4Server.addHeader("Accept-Encoding", "gzip,identity"); req4Server.addHeader("If-None-Match", "\"gzip_etag\""); - final HttpResponse resp4 = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_NOT_MODIFIED, "Not Modified"); + final ClassicHttpResponse resp4 = HttpTestUtils.make304Response(); resp4.setHeader("Etag", "\"gzip_etag\""); resp4.setHeader("Date", DateUtils.formatDate(now)); resp4.setHeader("Vary", "Accept-Encoding"); @@ -1278,15 +1260,15 @@ public abstract class TestCachingExecChain { backendExpectsAnyRequestAndReturn(resp4); replayMocks(); - final HttpResponse result1 = impl.execute(route, req1, context, null); + final ClassicHttpResponse result1 = impl.execute(req1, context, null); - final HttpResponse result2 = impl.execute(route, req2, context, null); + final ClassicHttpResponse result2 = impl.execute(req2, context, null); - final HttpResponse result4 = impl.execute(route, req4, context, null); + final ClassicHttpResponse result4 = impl.execute(req4, context, null); verifyMocks(); - Assert.assertEquals(HttpStatus.SC_OK, result1.getStatusLine().getStatusCode()); - Assert.assertEquals(HttpStatus.SC_OK, result2.getStatusLine().getStatusCode()); - Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result4.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_OK, result1.getCode()); + Assert.assertEquals(HttpStatus.SC_OK, result2.getCode()); + Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result4.getCode()); } @@ -1295,10 +1277,10 @@ public abstract class TestCachingExecChain { impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); final Date now = new Date(); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com"), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com"), route); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp1.setEntity(new InputStreamEntity(new InputStream() { private boolean closed = false; @@ -1322,7 +1304,7 @@ public abstract class TestCachingExecChain { replayMocks(); try { - final HttpResponse result1 = impl.execute(route, req1, context, null); + final ClassicHttpResponse result1 = impl.execute(req1, context, null); EntityUtils.toString(result1.getEntity()); Assert.fail("We should have had a SocketTimeoutException"); } catch (final SocketTimeoutException e) { @@ -1340,7 +1322,7 @@ public abstract class TestCachingExecChain { public void testTreatsCacheIOExceptionsAsCacheMiss() throws Exception { impl = createCachingExecChain(mockBackend, mockCache, CacheConfig.DEFAULT); - final CloseableHttpResponse resp = Proxies.enhanceResponse(HttpTestUtils.make200Response()); + final ClassicHttpResponse resp = HttpTestUtils.make200Response(); mockCache.flushInvalidatedCacheEntriesFor(host, request); expectLastCall().andThrow(new IOException()).anyTimes(); @@ -1353,14 +1335,14 @@ public abstract class TestCachingExecChain { .andThrow(new IOException()).anyTimes(); expect( mockCache.cacheAndReturnResponse(eq(host), isA(HttpRequest.class), - isA(CloseableHttpResponse.class), isA(Date.class), isA(Date.class))) + isA(ClassicHttpResponse.class), isA(Date.class), isA(Date.class))) .andReturn(resp).anyTimes(); expect( - mockBackend.execute(eq(route), isA(HttpRequestWrapper.class), + mockBackend.execute(isA(RoutedHttpRequest.class), isA(HttpClientContext.class), (HttpExecutionAware) isNull())).andReturn(resp); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); Assert.assertSame(resp, result); } @@ -1371,9 +1353,9 @@ public abstract class TestCachingExecChain { request.addHeader("Cache-Control", "only-if-cached"); - final HttpResponse resp = impl.execute(route, request, context, null); + final ClassicHttpResponse resp = impl.execute(request, context, null); - Assert.assertEquals(HttpStatus.SC_GATEWAY_TIMEOUT, resp.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_GATEWAY_TIMEOUT, resp.getCode()); } @Test @@ -1391,10 +1373,10 @@ public abstract class TestCachingExecChain { cacheEntrySuitable(false); replayMocks(); - final HttpResponse resp = impl.execute(route, request, context, null); + final ClassicHttpResponse resp = impl.execute(request, context, null); verifyMocks(); - Assert.assertEquals(HttpStatus.SC_GATEWAY_TIMEOUT, resp.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_GATEWAY_TIMEOUT, resp.getCode()); } @Test @@ -1411,7 +1393,7 @@ public abstract class TestCachingExecChain { entryHasStaleness(0); replayMocks(); - final HttpResponse resp = impl.execute(route, request, context, null); + final ClassicHttpResponse resp = impl.execute(request, context, null); verifyMocks(); Assert.assertSame(mockCachedResponse, resp); @@ -1420,56 +1402,51 @@ public abstract class TestCachingExecChain { @Test public void testDoesNotSetConnectionInContextOnCacheHit() throws Exception { final DummyBackend backend = new DummyBackend(); - final HttpResponse response = HttpTestUtils.make200Response(); + final ClassicHttpResponse response = HttpTestUtils.make200Response(); response.setHeader("Cache-Control", "max-age=3600"); backend.setResponse(response); impl = createCachingExecChain(backend, new BasicHttpCache(), CacheConfig.DEFAULT); final HttpClientContext ctx = HttpClientContext.create(); - ctx.setTargetHost(host); - impl.execute(route, request, context, null); - impl.execute(route, request, ctx, null); + impl.execute(request, context, null); + impl.execute(request, ctx, null); assertNull(ctx.getConnection()); } @Test public void testSetsTargetHostInContextOnCacheHit() throws Exception { final DummyBackend backend = new DummyBackend(); - final HttpResponse response = HttpTestUtils.make200Response(); + final ClassicHttpResponse response = HttpTestUtils.make200Response(); response.setHeader("Cache-Control", "max-age=3600"); backend.setResponse(response); impl = createCachingExecChain(backend, new BasicHttpCache(), CacheConfig.DEFAULT); final HttpClientContext ctx = HttpClientContext.create(); - ctx.setTargetHost(host); - impl.execute(route, request, context, null); - impl.execute(route, request, ctx, null); - assertSame(host, ctx.getTargetHost()); + impl.execute(request, context, null); + impl.execute(request, ctx, null); } @Test public void testSetsRouteInContextOnCacheHit() throws Exception { final DummyBackend backend = new DummyBackend(); - final HttpResponse response = HttpTestUtils.make200Response(); + final ClassicHttpResponse response = HttpTestUtils.make200Response(); response.setHeader("Cache-Control", "max-age=3600"); backend.setResponse(response); impl = createCachingExecChain(backend, new BasicHttpCache(), CacheConfig.DEFAULT); final HttpClientContext ctx = HttpClientContext.create(); - ctx.setTargetHost(host); - impl.execute(route, request, context, null); - impl.execute(route, request, ctx, null); + impl.execute(request, context, null); + impl.execute(request, ctx, null); assertEquals(route, ctx.getHttpRoute()); } @Test public void testSetsRequestInContextOnCacheHit() throws Exception { final DummyBackend backend = new DummyBackend(); - final HttpResponse response = HttpTestUtils.make200Response(); + final ClassicHttpResponse response = HttpTestUtils.make200Response(); response.setHeader("Cache-Control", "max-age=3600"); backend.setResponse(response); impl = createCachingExecChain(backend, new BasicHttpCache(), CacheConfig.DEFAULT); final HttpClientContext ctx = HttpClientContext.create(); - ctx.setTargetHost(host); - impl.execute(route, request, context, null); - impl.execute(route, request, ctx, null); + impl.execute(request, context, null); + impl.execute(request, ctx, null); if (!HttpTestUtils.equivalent(request, ctx.getRequest())) { assertSame(request, ctx.getRequest()); } @@ -1478,14 +1455,13 @@ public abstract class TestCachingExecChain { @Test public void testSetsResponseInContextOnCacheHit() throws Exception { final DummyBackend backend = new DummyBackend(); - final HttpResponse response = HttpTestUtils.make200Response(); + final ClassicHttpResponse response = HttpTestUtils.make200Response(); response.setHeader("Cache-Control", "max-age=3600"); backend.setResponse(response); impl = createCachingExecChain(backend, new BasicHttpCache(), CacheConfig.DEFAULT); final HttpClientContext ctx = HttpClientContext.create(); - ctx.setTargetHost(host); - impl.execute(route, request, context, null); - final HttpResponse result = impl.execute(route, request, ctx, null); + impl.execute(request, context, null); + final ClassicHttpResponse result = impl.execute(request, ctx, null); if (!HttpTestUtils.equivalent(result, ctx.getResponse())) { assertSame(result, ctx.getResponse()); } @@ -1494,27 +1470,25 @@ public abstract class TestCachingExecChain { @Test public void testSetsRequestSentInContextOnCacheHit() throws Exception { final DummyBackend backend = new DummyBackend(); - final HttpResponse response = HttpTestUtils.make200Response(); + final ClassicHttpResponse response = HttpTestUtils.make200Response(); response.setHeader("Cache-Control", "max-age=3600"); backend.setResponse(response); impl = createCachingExecChain(backend, new BasicHttpCache(), CacheConfig.DEFAULT); final HttpClientContext ctx = HttpClientContext.create(); - ctx.setTargetHost(host); - impl.execute(route, request, context, null); - impl.execute(route, request, ctx, null); + impl.execute(request, context, null); + impl.execute(request, ctx, null); } @Test public void testCanCacheAResponseWithoutABody() throws Exception { - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_NO_CONTENT, "No Content"); + final ClassicHttpResponse response = new BasicClassicHttpResponse(HttpStatus.SC_NO_CONTENT, "No Content"); response.setHeader("Date", DateUtils.formatDate(new Date())); response.setHeader("Cache-Control", "max-age=300"); final DummyBackend backend = new DummyBackend(); backend.setResponse(response); impl = createCachingExecChain(backend, new BasicHttpCache(), CacheConfig.DEFAULT); - impl.execute(route, request, context, null); - impl.execute(route, request, context, null); + impl.execute(request, context, null); + impl.execute(request, context, null); assertEquals(1, backend.getExecutions()); } @@ -1525,12 +1499,11 @@ public abstract class TestCachingExecChain { final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); req1.addHeader("If-None-Match", "\"etag\""); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_NOT_MODIFIED, "Not modified"); + final ClassicHttpResponse resp1 = HttpTestUtils.make304Response(); resp1.setHeader("Content-Length", "128"); resp1.setHeader("ETag", "\"etag\""); resp1.setHeader("Date", DateUtils.formatDate(tenSecondsAgo)); @@ -1538,10 +1511,10 @@ public abstract class TestCachingExecChain { backendExpectsAnyRequestAndReturn(resp1); replayMocks(); - final HttpResponse result = impl.execute(route, req1, context, null); + final ClassicHttpResponse result = impl.execute(req1, context, null); verifyMocks(); - assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getStatusLine().getStatusCode()); + assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getCode()); assertNull("The 304 response messages MUST NOT contain a message-body", result.getEntity()); } @@ -1552,22 +1525,20 @@ public abstract class TestCachingExecChain { impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); req1.addHeader("If-None-Match", "etag"); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); req2.addHeader("If-None-Match", "etag"); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_NOT_MODIFIED, "Not modified"); + final ClassicHttpResponse resp1 = HttpTestUtils.make304Response(); resp1.setHeader("Date", DateUtils.formatDate(now)); resp1.setHeader("Cache-Control", "max-age=0"); resp1.setHeader("Etag", "etag"); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_NOT_MODIFIED, "Not modified"); + final ClassicHttpResponse resp2 = HttpTestUtils.make304Response(); resp2.setHeader("Date", DateUtils.formatDate(now)); resp2.setHeader("Cache-Control", "max-age=0"); resp1.setHeader("Etag", "etag"); @@ -1575,13 +1546,13 @@ public abstract class TestCachingExecChain { backendExpectsAnyRequestAndReturn(resp1); backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - final HttpResponse result1 = impl.execute(route, req1, context, null); - final HttpResponse result2 = impl.execute(route, req2, context, null); + final ClassicHttpResponse result1 = impl.execute(req1, context, null); + final ClassicHttpResponse result2 = impl.execute(req2, context, null); verifyMocks(); - assertEquals(HttpStatus.SC_NOT_MODIFIED, result1.getStatusLine().getStatusCode()); + assertEquals(HttpStatus.SC_NOT_MODIFIED, result1.getCode()); assertEquals("etag", result1.getFirstHeader("Etag").getValue()); - assertEquals(HttpStatus.SC_NOT_MODIFIED, result2.getStatusLine().getStatusCode()); + assertEquals(HttpStatus.SC_NOT_MODIFIED, result2.getCode()); assertEquals("etag", result2.getFirstHeader("Etag").getValue()); } @@ -1592,23 +1563,21 @@ public abstract class TestCachingExecChain { impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); req1.addHeader("If-None-Match", "etag"); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); req2.addHeader("If-None-Match", "etag"); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_NOT_MODIFIED, "Not modified"); + final ClassicHttpResponse resp1 = HttpTestUtils.make304Response(); resp1.setHeader("Date", DateUtils.formatDate(now)); resp1.setHeader("Cache-Control", "max-age=0"); resp1.setHeader("Etag", "etag"); resp1.setHeader("Vary", "Accept-Encoding"); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_NOT_MODIFIED, "Not modified"); + final ClassicHttpResponse resp2 = HttpTestUtils.make304Response(); resp2.setHeader("Date", DateUtils.formatDate(now)); resp2.setHeader("Cache-Control", "max-age=0"); resp1.setHeader("Etag", "etag"); @@ -1617,13 +1586,13 @@ public abstract class TestCachingExecChain { backendExpectsAnyRequestAndReturn(resp1); backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - final HttpResponse result1 = impl.execute(route, req1, context, null); - final HttpResponse result2 = impl.execute(route, req2, context, null); + final ClassicHttpResponse result1 = impl.execute(req1, context, null); + final ClassicHttpResponse result2 = impl.execute(req2, context, null); verifyMocks(); - assertEquals(HttpStatus.SC_NOT_MODIFIED, result1.getStatusLine().getStatusCode()); + assertEquals(HttpStatus.SC_NOT_MODIFIED, result1.getCode()); assertEquals("etag", result1.getFirstHeader("Etag").getValue()); - assertEquals(HttpStatus.SC_NOT_MODIFIED, result2.getStatusLine().getStatusCode()); + assertEquals(HttpStatus.SC_NOT_MODIFIED, result2.getCode()); assertEquals("etag", result2.getFirstHeader("Etag").getValue()); } @@ -1635,22 +1604,21 @@ public abstract class TestCachingExecChain { impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); req1.addHeader("If-None-Match", "etag"); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet( - "http://foo.example.com/"), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(new HttpGet( + "http://foo.example.com/"), route); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_NOT_MODIFIED, "Not modified"); + final ClassicHttpResponse resp1 = HttpTestUtils.make304Response(); resp1.setHeader("Date", DateUtils.formatDate(now)); resp1.setHeader("Cache-Control", "public, max-age=60"); resp1.setHeader("Expires", DateUtils.formatDate(inOneMinute)); resp1.setHeader("Etag", "etag"); resp1.setHeader("Vary", "Accept-Encoding"); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "Ok"); resp2.setHeader("Date", DateUtils.formatDate(now)); resp2.setHeader("Cache-Control", "public, max-age=60"); @@ -1662,70 +1630,62 @@ public abstract class TestCachingExecChain { backendExpectsAnyRequestAndReturn(resp1); backendExpectsAnyRequestAndReturn(resp2).anyTimes(); replayMocks(); - final HttpResponse result1 = impl.execute(route, req1, context, null); - final HttpResponse result2 = impl.execute(route, req2, context, null); + final ClassicHttpResponse result1 = impl.execute(req1, context, null); + final ClassicHttpResponse result2 = impl.execute(req2, context, null); verifyMocks(); - assertEquals(HttpStatus.SC_NOT_MODIFIED, result1.getStatusLine().getStatusCode()); + assertEquals(HttpStatus.SC_NOT_MODIFIED, result1.getCode()); assertNull(result1.getEntity()); - assertEquals(HttpStatus.SC_OK, result2.getStatusLine().getStatusCode()); + assertEquals(HttpStatus.SC_OK, result2.getCode()); Assert.assertNotNull(result2.getEntity()); } @Test public void testUsesVirtualHostForCacheKey() throws Exception { final DummyBackend backend = new DummyBackend(); - final HttpResponse response = HttpTestUtils.make200Response(); + final ClassicHttpResponse response = HttpTestUtils.make200Response(); response.setHeader("Cache-Control", "max-age=3600"); backend.setResponse(response); impl = createCachingExecChain(backend, new BasicHttpCache(), CacheConfig.DEFAULT); - impl.execute(route, request, context, null); + impl.execute(request, context, null); assertEquals(1, backend.getExecutions()); - context.setTargetHost(new HttpHost("bar.example.com")); - impl.execute(route, request, context, null); + request.setAuthority(new URIAuthority("bar.example.com")); + impl.execute(request, context, null); assertEquals(2, backend.getExecutions()); - impl.execute(route, request, context, null); + impl.execute(request, context, null); assertEquals(2, backend.getExecutions()); } - private IExpectationSetters backendExpectsAnyRequestAndReturn( - final HttpResponse response) throws Exception { - final CloseableHttpResponse resp = mockBackend.execute(EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), EasyMock.isA(HttpClientContext.class), - EasyMock. isNull()); - return EasyMock.expect(resp).andReturn(Proxies.enhanceResponse(response)); + protected IExpectationSetters backendExpectsRequestAndReturn( + final RoutedHttpRequest request, final ClassicHttpResponse response) throws Exception { + final ClassicHttpResponse resp = mockBackend.execute( + EasyMock.eq(request), EasyMock.isA(HttpClientContext.class), + EasyMock. isNull()); + return EasyMock.expect(resp).andReturn(response); } - protected IExpectationSetters backendExpectsRequestAndReturn( - final HttpRequestWrapper request, final HttpResponse response) throws Exception { - final CloseableHttpResponse resp = mockBackend.execute(EasyMock.isA(HttpRoute.class), - EasyMock.eq(request), EasyMock.isA(HttpClientContext.class), - EasyMock. isNull()); - return EasyMock.expect(resp).andReturn(Proxies.enhanceResponse(response)); - } - - protected IExpectationSetters backendExpectsRequestAndReturn( - final HttpRequestWrapper request, final CloseableHttpResponse response) throws Exception { - final CloseableHttpResponse resp = mockBackend.execute(EasyMock.isA(HttpRoute.class), - EasyMock.eq(request), EasyMock.isA(HttpClientContext.class), + private IExpectationSetters backendExpectsAnyRequestAndReturn( + final ClassicHttpResponse response) throws Exception { + final ClassicHttpResponse resp = mockBackend.execute( + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock. isNull()); return EasyMock.expect(resp).andReturn(response); } - protected IExpectationSetters backendExpectsAnyRequestAndThrows( + protected IExpectationSetters backendExpectsAnyRequestAndThrows( final Throwable throwable) throws Exception { - final CloseableHttpResponse resp = mockBackend.execute(EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), EasyMock.isA(HttpClientContext.class), + final ClassicHttpResponse resp = mockBackend.execute( + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock. isNull()); return EasyMock.expect(resp).andThrow(throwable); } - protected IExpectationSetters backendCaptureRequestAndReturn( - final Capture cap, final HttpResponse response) throws Exception { - final CloseableHttpResponse resp = mockBackend.execute(EasyMock.isA(HttpRoute.class), + protected IExpectationSetters backendCaptureRequestAndReturn( + final Capture cap, final ClassicHttpResponse response) throws Exception { + final ClassicHttpResponse resp = mockBackend.execute( EasyMock.capture(cap), EasyMock.isA(HttpClientContext.class), EasyMock. isNull()); - return EasyMock.expect(resp).andReturn(Proxies.enhanceResponse(response)); + return EasyMock.expect(resp).andReturn(response); } protected void getCacheEntryReturns(final HttpCacheEntry result) throws IOException { @@ -1756,8 +1716,7 @@ public abstract class TestCachingExecChain { (Date) anyObject())).andReturn(b); } - protected void conditionalRequestBuilderReturns(final HttpRequestWrapper validate) - throws Exception { + protected void conditionalRequestBuilderReturns(final RoutedHttpRequest validate) throws Exception { expect(mockConditionalRequestBuilder.buildConditionalRequest(request, entry)).andReturn( validate); } @@ -1781,7 +1740,7 @@ public abstract class TestCachingExecChain { protected void responseIsGeneratedFromCache() { expect( - mockResponseGenerator.generateResponse((HttpRequestWrapper) anyObject(), (HttpCacheEntry) anyObject())) + mockResponseGenerator.generateResponse((RoutedHttpRequest) anyObject(), (HttpCacheEntry) anyObject())) .andReturn(mockCachedResponse); } diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCombinedEntity.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCombinedEntity.java index 518c5c866..788c17660 100644 --- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCombinedEntity.java +++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCombinedEntity.java @@ -33,7 +33,7 @@ import static org.mockito.Mockito.when; import java.io.ByteArrayInputStream; import org.apache.hc.client5.http.cache.Resource; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.EntityUtils; import org.junit.Assert; import org.junit.Test; 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 b36246551..976bcb0d2 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 @@ -28,20 +28,23 @@ package org.apache.hc.client5.http.impl.cache; import java.util.Date; import java.util.HashMap; +import java.util.Iterator; import java.util.Map; +import org.apache.hc.client5.http.HttpRoute; import org.apache.hc.client5.http.cache.HeaderConstants; import org.apache.hc.client5.http.cache.HttpCacheEntry; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.utils.DateUtils; +import org.apache.hc.core5.http.message.MessageSupport; +import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HeaderElement; import org.apache.hc.core5.http.HttpHost; -import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.HttpVersion; import org.apache.hc.core5.http.ProtocolException; +import org.apache.hc.core5.http.message.BasicClassicHttpRequest; import org.apache.hc.core5.http.message.BasicHeader; -import org.apache.hc.core5.http.message.BasicHttpRequest; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -50,16 +53,15 @@ public class TestConditionalRequestBuilder { private ConditionalRequestBuilder impl; private HttpHost host; - private HttpRequestWrapper request; - private HttpCacheEntry entry; + private HttpRoute route; + private RoutedHttpRequest request; @Before public void setUp() throws Exception { impl = new ConditionalRequestBuilder(); host = new HttpHost("foo.example.com", 80); - request = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - entry = HttpTestUtils.makeCacheEntry(); + route = new HttpRoute(host); + request = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("GET", "/"), route); } @Test @@ -68,23 +70,21 @@ public class TestConditionalRequestBuilder { final String theUri = "/theuri"; final String lastModified = "this is my last modified date"; - final HttpRequest basicRequest = new BasicHttpRequest(theMethod, theUri); + final ClassicHttpRequest basicRequest = new BasicClassicHttpRequest(theMethod, theUri); basicRequest.addHeader("Accept-Encoding", "gzip"); - final HttpRequestWrapper requestWrapper = HttpRequestWrapper.wrap(basicRequest, host); + final RoutedHttpRequest requestWrapper = RoutedHttpRequest.adapt(basicRequest, route); final Header[] headers = new Header[] { new BasicHeader("Date", DateUtils.formatDate(new Date())), new BasicHeader("Last-Modified", lastModified) }; final HttpCacheEntry cacheEntry = HttpTestUtils.makeCacheEntry(headers); - final HttpRequestWrapper newRequest = impl.buildConditionalRequest(requestWrapper, cacheEntry); + final RoutedHttpRequest newRequest = impl.buildConditionalRequest(requestWrapper, cacheEntry); Assert.assertNotSame(basicRequest, newRequest); - Assert.assertEquals(theMethod, newRequest.getRequestLine().getMethod()); - Assert.assertEquals(theUri, newRequest.getRequestLine().getUri()); - Assert.assertEquals(basicRequest.getRequestLine().getProtocolVersion(), newRequest - .getRequestLine().getProtocolVersion()); + Assert.assertEquals(theMethod, newRequest.getMethod()); + Assert.assertEquals(theUri, newRequest.getRequestUri()); Assert.assertEquals(2, newRequest.getAllHeaders().length); Assert.assertEquals("Accept-Encoding", newRequest.getAllHeaders()[0].getName()); @@ -107,10 +107,10 @@ public class TestConditionalRequestBuilder { new BasicHeader("Last-Modified", lmDate), new BasicHeader("ETag", etag) }; - final HttpRequest basicRequest = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); - final HttpRequestWrapper requestWrapper = HttpRequestWrapper.wrap(basicRequest, host); + final ClassicHttpRequest basicRequest = new BasicClassicHttpRequest("GET", "/"); + final RoutedHttpRequest requestWrapper = RoutedHttpRequest.adapt(basicRequest, route); final HttpCacheEntry cacheEntry = HttpTestUtils.makeCacheEntry(headers); - final HttpRequest result = impl.buildConditionalRequest(requestWrapper, cacheEntry); + final ClassicHttpRequest result = impl.buildConditionalRequest(requestWrapper, cacheEntry); Assert.assertEquals(lmDate, result.getFirstHeader("If-Modified-Since").getValue()); Assert.assertEquals(etag, @@ -123,9 +123,9 @@ public class TestConditionalRequestBuilder { final String theUri = "/theuri"; final String theETag = "this is my eTag"; - final HttpRequest basicRequest = new BasicHttpRequest(theMethod, theUri); + final ClassicHttpRequest basicRequest = new BasicClassicHttpRequest(theMethod, theUri); basicRequest.addHeader("Accept-Encoding", "gzip"); - final HttpRequestWrapper requestWrapper = HttpRequestWrapper.wrap(basicRequest, host); + final RoutedHttpRequest requestWrapper = RoutedHttpRequest.adapt(basicRequest, route); final Header[] headers = new Header[] { new BasicHeader("Date", DateUtils.formatDate(new Date())), @@ -134,14 +134,12 @@ public class TestConditionalRequestBuilder { final HttpCacheEntry cacheEntry = HttpTestUtils.makeCacheEntry(headers); - final HttpRequest newRequest = impl.buildConditionalRequest(requestWrapper, cacheEntry); + final ClassicHttpRequest newRequest = impl.buildConditionalRequest(requestWrapper, cacheEntry); Assert.assertNotSame(basicRequest, newRequest); - Assert.assertEquals(theMethod, newRequest.getRequestLine().getMethod()); - Assert.assertEquals(theUri, newRequest.getRequestLine().getUri()); - Assert.assertEquals(basicRequest.getRequestLine().getProtocolVersion(), newRequest - .getRequestLine().getProtocolVersion()); + Assert.assertEquals(theMethod, newRequest.getMethod()); + Assert.assertEquals(theUri, newRequest.getRequestUri()); Assert.assertEquals(3, newRequest.getAllHeaders().length); @@ -154,8 +152,8 @@ public class TestConditionalRequestBuilder { @Test public void testCacheEntryWithMustRevalidateDoesEndToEndRevalidation() throws Exception { - final HttpRequest basicRequest = new BasicHttpRequest("GET","/",HttpVersion.HTTP_1_1); - final HttpRequestWrapper requestWrapper = HttpRequestWrapper.wrap(basicRequest, host); + final ClassicHttpRequest basicRequest = new BasicClassicHttpRequest("GET","/"); + final RoutedHttpRequest requestWrapper = RoutedHttpRequest.adapt(basicRequest, route); final Date now = new Date(); final Date elevenSecondsAgo = new Date(now.getTime() - 11 * 1000L); final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); @@ -167,15 +165,15 @@ public class TestConditionalRequestBuilder { new BasicHeader("Cache-Control","max-age=5, must-revalidate") }; final HttpCacheEntry cacheEntry = HttpTestUtils.makeCacheEntry(elevenSecondsAgo, nineSecondsAgo, cacheEntryHeaders); - final HttpRequest result = impl.buildConditionalRequest(requestWrapper, cacheEntry); + final ClassicHttpRequest result = impl.buildConditionalRequest(requestWrapper, cacheEntry); boolean foundMaxAge0 = false; - for(final Header h : result.getHeaders("Cache-Control")) { - for(final HeaderElement elt : h.getElements()) { - if ("max-age".equalsIgnoreCase(elt.getName()) - && "0".equals(elt.getValue())) { - foundMaxAge0 = true; - } + + final Iterator it = MessageSupport.iterate(result, HeaderConstants.CACHE_CONTROL); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + if ("max-age".equalsIgnoreCase(elt.getName()) && "0".equals(elt.getValue())) { + foundMaxAge0 = true; } } Assert.assertTrue(foundMaxAge0); @@ -183,8 +181,8 @@ public class TestConditionalRequestBuilder { @Test public void testCacheEntryWithProxyRevalidateDoesEndToEndRevalidation() throws Exception { - final HttpRequest basicRequest = new BasicHttpRequest("GET","/",HttpVersion.HTTP_1_1); - final HttpRequestWrapper requestWrapper = HttpRequestWrapper.wrap(basicRequest, host); + final ClassicHttpRequest basicRequest = new BasicClassicHttpRequest("GET", "/"); + final RoutedHttpRequest requestWrapper = RoutedHttpRequest.adapt(basicRequest, route); final Date now = new Date(); final Date elevenSecondsAgo = new Date(now.getTime() - 11 * 1000L); final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); @@ -196,15 +194,14 @@ public class TestConditionalRequestBuilder { new BasicHeader("Cache-Control","max-age=5, proxy-revalidate") }; final HttpCacheEntry cacheEntry = HttpTestUtils.makeCacheEntry(elevenSecondsAgo, nineSecondsAgo, cacheEntryHeaders); - final HttpRequest result = impl.buildConditionalRequest(requestWrapper, cacheEntry); + final ClassicHttpRequest result = impl.buildConditionalRequest(requestWrapper, cacheEntry); boolean foundMaxAge0 = false; - for(final Header h : result.getHeaders("Cache-Control")) { - for(final HeaderElement elt : h.getElements()) { - if ("max-age".equalsIgnoreCase(elt.getName()) - && "0".equals(elt.getValue())) { - foundMaxAge0 = true; - } + final Iterator it = MessageSupport.iterate(result, HeaderConstants.CACHE_CONTROL); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + if ("max-age".equalsIgnoreCase(elt.getName()) && "0".equals(elt.getValue())) { + foundMaxAge0 = true; } } Assert.assertTrue(foundMaxAge0); @@ -213,36 +210,36 @@ public class TestConditionalRequestBuilder { @Test public void testBuildUnconditionalRequestUsesGETMethod() throws Exception { - final HttpRequest result = impl.buildUnconditionalRequest(request, entry); - Assert.assertEquals("GET", result.getRequestLine().getMethod()); + final ClassicHttpRequest result = impl.buildUnconditionalRequest(request); + Assert.assertEquals("GET", result.getMethod()); } @Test public void testBuildUnconditionalRequestUsesRequestUri() throws Exception { final String uri = "/theURI"; - request = HttpRequestWrapper.wrap(new BasicHttpRequest("GET", uri, HttpVersion.HTTP_1_1), host); - final HttpRequest result = impl.buildUnconditionalRequest(request, entry); - Assert.assertEquals(uri, result.getRequestLine().getUri()); + request = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("GET", uri), route); + final ClassicHttpRequest result = impl.buildUnconditionalRequest(request); + Assert.assertEquals(uri, result.getRequestUri()); } @Test public void testBuildUnconditionalRequestUsesHTTP_1_1() throws Exception { - final HttpRequest result = impl.buildUnconditionalRequest(request, entry); - Assert.assertEquals(HttpVersion.HTTP_1_1, result.getProtocolVersion()); + final ClassicHttpRequest result = impl.buildUnconditionalRequest(request); + Assert.assertEquals(HttpVersion.HTTP_1_1, result.getVersion()); } @Test public void testBuildUnconditionalRequestAddsCacheControlNoCache() throws Exception { - final HttpRequest result = impl.buildUnconditionalRequest(request, entry); + final ClassicHttpRequest result = impl.buildUnconditionalRequest(request); boolean ccNoCacheFound = false; - for(final Header h : result.getHeaders("Cache-Control")) { - for(final HeaderElement elt : h.getElements()) { - if ("no-cache".equals(elt.getName())) { - ccNoCacheFound = true; - } + final Iterator it = MessageSupport.iterate(result, HeaderConstants.CACHE_CONTROL); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + if ("no-cache".equals(elt.getName())) { + ccNoCacheFound = true; } } Assert.assertTrue(ccNoCacheFound); @@ -251,13 +248,13 @@ public class TestConditionalRequestBuilder { @Test public void testBuildUnconditionalRequestAddsPragmaNoCache() throws Exception { - final HttpRequest result = impl.buildUnconditionalRequest(request, entry); + final ClassicHttpRequest result = impl.buildUnconditionalRequest(request); boolean ccNoCacheFound = false; - for(final Header h : result.getHeaders("Pragma")) { - for(final HeaderElement elt : h.getElements()) { - if ("no-cache".equals(elt.getName())) { - ccNoCacheFound = true; - } + final Iterator it = MessageSupport.iterate(result, HeaderConstants.PRAGMA); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + if ("no-cache".equals(elt.getName())) { + ccNoCacheFound = true; } } Assert.assertTrue(ccNoCacheFound); @@ -267,7 +264,7 @@ public class TestConditionalRequestBuilder { public void testBuildUnconditionalRequestDoesNotUseIfRange() throws Exception { request.addHeader("If-Range","\"etag\""); - final HttpRequest result = impl.buildUnconditionalRequest(request, entry); + final ClassicHttpRequest result = impl.buildUnconditionalRequest(request); Assert.assertNull(result.getFirstHeader("If-Range")); } @@ -275,7 +272,7 @@ public class TestConditionalRequestBuilder { public void testBuildUnconditionalRequestDoesNotUseIfMatch() throws Exception { request.addHeader("If-Match","\"etag\""); - final HttpRequest result = impl.buildUnconditionalRequest(request, entry); + final ClassicHttpRequest result = impl.buildUnconditionalRequest(request); Assert.assertNull(result.getFirstHeader("If-Match")); } @@ -283,7 +280,7 @@ public class TestConditionalRequestBuilder { public void testBuildUnconditionalRequestDoesNotUseIfNoneMatch() throws Exception { request.addHeader("If-None-Match","\"etag\""); - final HttpRequest result = impl.buildUnconditionalRequest(request, entry); + final ClassicHttpRequest result = impl.buildUnconditionalRequest(request); Assert.assertNull(result.getFirstHeader("If-None-Match")); } @@ -291,7 +288,7 @@ public class TestConditionalRequestBuilder { public void testBuildUnconditionalRequestDoesNotUseIfUnmodifiedSince() throws Exception { request.addHeader("If-Unmodified-Since", DateUtils.formatDate(new Date())); - final HttpRequest result = impl.buildUnconditionalRequest(request, entry); + final ClassicHttpRequest result = impl.buildUnconditionalRequest(request); Assert.assertNull(result.getFirstHeader("If-Unmodified-Since")); } @@ -299,7 +296,7 @@ public class TestConditionalRequestBuilder { public void testBuildUnconditionalRequestDoesNotUseIfModifiedSince() throws Exception { request.addHeader("If-Modified-Since", DateUtils.formatDate(new Date())); - final HttpRequest result = impl.buildUnconditionalRequest(request, entry); + final ClassicHttpRequest result = impl.buildUnconditionalRequest(request); Assert.assertNull(result.getFirstHeader("If-Modified-Since")); } @@ -307,7 +304,7 @@ public class TestConditionalRequestBuilder { public void testBuildUnconditionalRequestCarriesOtherRequestHeaders() throws Exception { request.addHeader("User-Agent","MyBrowser/1.0"); - final HttpRequest result = impl.buildUnconditionalRequest(request, entry); + final ClassicHttpRequest result = impl.buildUnconditionalRequest(request); Assert.assertEquals("MyBrowser/1.0", result.getFirstHeader("User-Agent").getValue()); } @@ -323,7 +320,7 @@ public class TestConditionalRequestBuilder { variantEntries.put(etag2, new Variant("C","D",HttpTestUtils.makeCacheEntry(new Header[] { new BasicHeader("ETag", etag2) }))); variantEntries.put(etag3, new Variant("E","F",HttpTestUtils.makeCacheEntry(new Header[] { new BasicHeader("ETag", etag3) }))); - final HttpRequest conditional = impl.buildConditionalRequestFromVariants(request, variantEntries); + final ClassicHttpRequest conditional = impl.buildConditionalRequestFromVariants(request, variantEntries); // seems like a lot of work, but necessary, check for existence and exclusiveness String ifNoneMatch = conditional.getFirstHeader(HeaderConstants.IF_NONE_MATCH).getValue(); diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestExponentialBackingOffSchedulingStrategy.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestExponentialBackingOffSchedulingStrategy.java index 711fe31f0..86105456a 100644 --- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestExponentialBackingOffSchedulingStrategy.java +++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestExponentialBackingOffSchedulingStrategy.java @@ -35,10 +35,10 @@ import java.util.concurrent.TimeUnit; import org.apache.hc.client5.http.HttpRoute; import org.apache.hc.client5.http.impl.sync.ClientExecChain; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.core5.http.HttpHost; -import org.apache.hc.core5.http.message.BasicHttpRequest; +import org.apache.hc.core5.http.message.BasicClassicHttpRequest; import org.junit.Before; import org.junit.Test; @@ -160,10 +160,10 @@ public class TestExponentialBackingOffSchedulingStrategy { final CachingExec cachingHttpClient = new CachingExec(clientExecChain); final AsynchronousValidator mockValidator = new AsynchronousValidator(impl); final HttpHost host = new HttpHost("foo.example.com", 80); - final HttpRoute httpRoute = new HttpRoute(host); - final HttpRequestWrapper httpRequestWrapper = HttpRequestWrapper.wrap(new BasicHttpRequest("GET", "/"), host); + final HttpRoute route = new HttpRoute(host); + final RoutedHttpRequest routedHttpRequest = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("GET", "/"), route); final HttpClientContext httpClientContext = new HttpClientContext(); - return new AsynchronousValidationRequest(mockValidator, cachingHttpClient, httpRoute, httpRequestWrapper, + return new AsynchronousValidationRequest(mockValidator, cachingHttpClient, routedHttpRequest, httpClientContext, null, null, "identifier", errorCount); } diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestHttpCacheEntrySerializers.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestHttpCacheEntrySerializers.java index c5fd3ee28..e3238ae59 100644 --- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestHttpCacheEntrySerializers.java +++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestHttpCacheEntrySerializers.java @@ -39,15 +39,12 @@ import java.util.HashMap; import java.util.Map; import org.apache.commons.codec.binary.Base64; -import org.apache.hc.client5.http.cache.HeaderConstants; import org.apache.hc.client5.http.cache.HttpCacheEntry; import org.apache.hc.client5.http.cache.HttpCacheEntrySerializer; import org.apache.hc.client5.http.cache.Resource; import org.apache.hc.core5.http.Header; -import org.apache.hc.core5.http.ProtocolVersion; -import org.apache.hc.core5.http.StatusLine; +import org.apache.hc.core5.http.HttpStatus; import org.apache.hc.core5.http.message.BasicHeader; -import org.apache.hc.core5.http.message.BasicStatusLine; import org.junit.Before; import org.junit.Test; @@ -87,14 +84,12 @@ public class TestHttpCacheEntrySerializers { } final String body = "Lorem ipsum dolor sit amet"; - final ProtocolVersion pvObj = new ProtocolVersion("HTTP", 1, 1); - final StatusLine slObj = new BasicStatusLine(pvObj, 200, "ok"); final Map variantMap = new HashMap<>(); variantMap.put("test variant 1","true"); variantMap.put("test variant 2","true"); final HttpCacheEntry cacheEntry = new HttpCacheEntry(new Date(), new Date(), - slObj, headers, new HeapResource(Base64.decodeBase64(body - .getBytes(UTF8))), variantMap, HeaderConstants.GET_METHOD); + HttpStatus.SC_OK, headers, + new HeapResource(Base64.decodeBase64(body.getBytes(UTF8))), variantMap); return cacheEntry; } @@ -109,9 +104,6 @@ public class TestHttpCacheEntrySerializers { .getResponseDate().getTime() / 1000))) { return false; } - if (!one.getProtocolVersion().equals(two.getProtocolVersion())) { - return false; - } final byte[] onesByteArray = resourceToBytes(one.getResource()); final byte[] twosByteArray = resourceToBytes(two.getResource()); diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestHttpCacheJiraNumber1147.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestHttpCacheJiraNumber1147.java index e7f20b693..d59c092af 100644 --- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestHttpCacheJiraNumber1147.java +++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestHttpCacheJiraNumber1147.java @@ -26,7 +26,6 @@ */ package org.apache.hc.client5.http.impl.cache; -import static org.mockito.Matchers.eq; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; @@ -42,13 +41,12 @@ import org.apache.hc.client5.http.cache.ResourceFactory; import org.apache.hc.client5.http.impl.sync.ClientExecChain; import org.apache.hc.client5.http.methods.HttpExecutionAware; import org.apache.hc.client5.http.methods.HttpGet; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.utils.DateUtils; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpHost; -import org.apache.hc.core5.http.HttpResponse; -import org.apache.hc.core5.http.HttpVersion; -import org.apache.hc.core5.http.message.BasicHttpResponse; +import org.apache.hc.core5.http.message.BasicClassicHttpResponse; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -95,17 +93,15 @@ public class TestHttpCacheJiraNumber1147 { final HttpCacheStorage httpCacheStorage = new ManagedHttpCacheStorage(cacheConfig); final ClientExecChain backend = mock(ClientExecChain.class); - final HttpRequestWrapper get = HttpRequestWrapper.wrap(new HttpGet("http://somehost/"), new HttpHost("somehost")); - final HttpClientContext context = HttpClientContext.create(); final HttpHost target = new HttpHost("somehost", 80); final HttpRoute route = new HttpRoute(target); - - context.setTargetHost(target); + final RoutedHttpRequest get = RoutedHttpRequest.adapt(new HttpGet("http://somehost/"), route); + final HttpClientContext context = HttpClientContext.create(); final Date now = new Date(); final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK"); response.setEntity(HttpTestUtils.makeBody(128)); response.setHeader("Content-Length", "128"); response.setHeader("ETag", "\"etag\""); @@ -113,21 +109,19 @@ public class TestHttpCacheJiraNumber1147 { response.setHeader("Last-Modified", DateUtils.formatDate(tenSecondsAgo)); when(backend.execute( - eq(route), - isA(HttpRequestWrapper.class), + isA(RoutedHttpRequest.class), isA(HttpClientContext.class), - (HttpExecutionAware) Matchers.isNull())).thenReturn(Proxies.enhanceResponse(response)); + (HttpExecutionAware) Matchers.isNull())).thenReturn(response); final BasicHttpCache cache = new BasicHttpCache(resourceFactory, httpCacheStorage, cacheConfig); final ClientExecChain t = createCachingExecChain(backend, cache, cacheConfig); - final HttpResponse response1 = t.execute(route, get, context, null); - Assert.assertEquals(200, response1.getStatusLine().getStatusCode()); + final ClassicHttpResponse response1 = t.execute(get, context, null); + Assert.assertEquals(200, response1.getCode()); IOUtils.consume(response1.getEntity()); verify(backend).execute( - eq(route), - isA(HttpRequestWrapper.class), + isA(RoutedHttpRequest.class), isA(HttpClientContext.class), (HttpExecutionAware) Matchers.isNull()); @@ -135,18 +129,16 @@ public class TestHttpCacheJiraNumber1147 { reset(backend); when(backend.execute( - eq(route), - isA(HttpRequestWrapper.class), + isA(RoutedHttpRequest.class), isA(HttpClientContext.class), - (HttpExecutionAware) Matchers.isNull())).thenReturn(Proxies.enhanceResponse(response)); + (HttpExecutionAware) Matchers.isNull())).thenReturn(response); - final HttpResponse response2 = t.execute(route, get, context, null); - Assert.assertEquals(200, response2.getStatusLine().getStatusCode()); + final ClassicHttpResponse response2 = t.execute(get, context, null); + Assert.assertEquals(200, response2.getCode()); IOUtils.consume(response2.getEntity()); verify(backend).execute( - eq(route), - isA(HttpRequestWrapper.class), + isA(RoutedHttpRequest.class), isA(HttpClientContext.class), (HttpExecutionAware) Matchers.isNull()); } diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolAllowedBehavior.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolAllowedBehavior.java index ab6f962e2..276fa4e9a 100644 --- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolAllowedBehavior.java +++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestProtocolAllowedBehavior.java @@ -29,27 +29,25 @@ package org.apache.hc.client5.http.impl.cache; import java.net.SocketTimeoutException; import java.util.Date; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.utils.DateUtils; import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.HttpStatus; -import org.apache.hc.core5.http.HttpVersion; -import org.apache.hc.core5.http.message.BasicHttpRequest; +import org.apache.hc.core5.http.message.BasicClassicHttpRequest; import org.junit.Assert; import org.junit.Test; /** * This class tests behavior that is allowed (MAY) by the HTTP/1.1 protocol - * specification and for which we have implemented the behavior in the - * {@link CachingHttpClient}. + * specification and for which we have implemented the behavior in HTTP cache. */ public class TestProtocolAllowedBehavior extends AbstractProtocolTest { @Test public void testNonSharedCacheReturnsStaleResponseWhenRevalidationFailsForProxyRevalidate() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET","/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET","/"), route); final Date now = new Date(); final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); originResponse.setHeader("Date", DateUtils.formatDate(tenSecondsAgo)); @@ -58,38 +56,38 @@ public class TestProtocolAllowedBehavior extends AbstractProtocolTest { backendExpectsAnyRequest().andReturn(originResponse); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET","/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET","/"), route); backendExpectsAnyRequest().andThrow(new SocketTimeoutException()); replayMocks(); behaveAsNonSharedCache(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final HttpResponse result = impl.execute(req2, context, null); verifyMocks(); - Assert.assertEquals(HttpStatus.SC_OK, result.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_OK, result.getCode()); } @Test public void testNonSharedCacheMayCacheResponsesWithCacheControlPrivate() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET","/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET","/"), route); originResponse.setHeader("Cache-Control","private,max-age=3600"); backendExpectsAnyRequest().andReturn(originResponse); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET","/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET","/"), route); replayMocks(); behaveAsNonSharedCache(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final HttpResponse result = impl.execute(req2, context, null); verifyMocks(); - Assert.assertEquals(HttpStatus.SC_OK, result.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_OK, result.getCode()); } } 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 e0933647c..b69c871e3 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 @@ -32,21 +32,22 @@ import java.util.Random; import org.apache.hc.client5.http.HttpRoute; import org.apache.hc.client5.http.cache.HttpCacheContext; import org.apache.hc.client5.http.impl.sync.ClientExecChain; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpExecutionAware; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.ClientProtocolException; 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.HttpEntity; import org.apache.hc.core5.http.HttpHost; 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.ProtocolVersion; -import org.apache.hc.core5.http.entity.ByteArrayEntity; -import org.apache.hc.core5.http.message.BasicHttpRequest; -import org.apache.hc.core5.http.message.BasicHttpResponse; +import org.apache.hc.core5.http.io.entity.ByteArrayEntity; +import org.apache.hc.core5.http.message.BasicClassicHttpRequest; +import org.apache.hc.core5.http.message.BasicClassicHttpResponse; import org.easymock.Capture; import org.easymock.EasyMock; import org.junit.Assert; @@ -83,9 +84,9 @@ public class TestProtocolDeviations { private HttpEntity mockEntity; private ClientExecChain mockBackend; private HttpCache mockCache; - private HttpRequest request; + private ClassicHttpRequest request; private HttpCacheContext context; - private CloseableHttpResponse originResponse; + private ClassicHttpResponse originResponse; private ClientExecChain impl; @@ -97,12 +98,11 @@ public class TestProtocolDeviations { body = makeBody(entityLength); - request = new BasicHttpRequest("GET", "/foo", HTTP_1_1); + request = new BasicClassicHttpRequest("GET", "/foo"); context = HttpCacheContext.create(); - context.setTargetHost(host); - originResponse = Proxies.enhanceResponse(make200Response()); + originResponse = make200Response(); final CacheConfig config = CacheConfig.custom() .setMaxCacheEntries(MAX_ENTRIES) @@ -122,8 +122,8 @@ public class TestProtocolDeviations { return new CachingExec(backend, cache, config); } - private HttpResponse make200Response() { - final HttpResponse out = new BasicHttpResponse(HTTP_1_1, HttpStatus.SC_OK, "OK"); + private ClassicHttpResponse make200Response() { + final ClassicHttpResponse out = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); out.setHeader("Date", DateUtils.formatDate(new Date())); out.setHeader("Server", "MockOrigin/1.0"); out.setEntity(makeBody(128)); @@ -172,19 +172,16 @@ public class TestProtocolDeviations { */ @Ignore public void testHTTP1_1RequestsWithBodiesOfKnownLengthMustHaveContentLength() throws Exception { - final BasicHttpRequest post = new BasicHttpRequest("POST", "/", - HTTP_1_1); + final ClassicHttpRequest post = new BasicClassicHttpRequest("POST", "/"); post.setEntity(mockEntity); replayMocks(); - final HttpResponse response = impl.execute(route, HttpRequestWrapper.wrap(post, host), context, null); + final HttpResponse response = impl.execute(RoutedHttpRequest.adapt(post, route), context, null); verifyMocks(); - Assert - .assertEquals(HttpStatus.SC_LENGTH_REQUIRED, response.getStatusLine() - .getStatusCode()); + Assert.assertEquals(HttpStatus.SC_LENGTH_REQUIRED, response.getCode()); } /* @@ -213,8 +210,7 @@ public class TestProtocolDeviations { @Ignore public void testHTTP1_1RequestsWithUnknownBodyLengthAreRejectedOrHaveContentLengthAdded() throws Exception { - final BasicHttpRequest post = new BasicHttpRequest("POST", "/", - HTTP_1_1); + final ClassicHttpRequest post = new BasicClassicHttpRequest("POST", "/"); final byte[] bytes = new byte[128]; new Random().nextBytes(bytes); @@ -224,10 +220,9 @@ public class TestProtocolDeviations { org.easymock.EasyMock.expect(mockBody.getContentLength()).andReturn(-1L).anyTimes(); post.setEntity(mockBody); - final Capture reqCap = new Capture<>(); + final Capture reqCap = new Capture<>(); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), EasyMock.capture(reqCap), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn( @@ -236,7 +231,7 @@ public class TestProtocolDeviations { replayMocks(); EasyMock.replay(mockBody); - final HttpResponse result = impl.execute(route, HttpRequestWrapper.wrap(post, host), context, null); + final HttpResponse result = impl.execute(RoutedHttpRequest.adapt(post, route), context, null); verifyMocks(); EasyMock.verify(mockBody); @@ -246,7 +241,7 @@ public class TestProtocolDeviations { final HttpRequest forwarded = reqCap.getValue(); Assert.assertNotNull(forwarded.getFirstHeader("Content-Length")); } else { - final int status = result.getStatusLine().getStatusCode(); + final int status = result.getCode(); Assert.assertTrue(HttpStatus.SC_LENGTH_REQUIRED == status || HttpStatus.SC_BAD_REQUEST == status); } @@ -261,25 +256,23 @@ public class TestProtocolDeviations { */ @Test public void testOPTIONSRequestsWithBodiesAndNoContentTypeHaveOneSupplied() throws Exception { - final BasicHttpRequest options = new BasicHttpRequest("OPTIONS", - "/", HTTP_1_1); + final ClassicHttpRequest options = new BasicClassicHttpRequest("OPTIONS", "/"); options.setEntity(body); options.setHeader("Content-Length", "1"); - final Capture reqCap = new Capture<>(); + final Capture reqCap = new Capture<>(); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), EasyMock.capture(reqCap), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - impl.execute(route, HttpRequestWrapper.wrap(options, host), context, null); + impl.execute(RoutedHttpRequest.adapt(options, route), context, null); verifyMocks(); - final HttpRequest reqWithBody = reqCap.getValue(); + final ClassicHttpRequest reqWithBody = reqCap.getValue(); final HttpEntity reqBody = reqWithBody.getEntity(); Assert.assertNotNull(reqBody); Assert.assertNotNull(reqBody.getContentType()); @@ -300,24 +293,20 @@ public class TestProtocolDeviations { // this situation, but it better not just pass the response // on. request.removeHeaders("Range"); - originResponse = Proxies.enhanceResponse( - new BasicHttpResponse(HTTP_1_1, HttpStatus.SC_PARTIAL_CONTENT, - "Partial Content")); + originResponse = new BasicClassicHttpResponse(HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); originResponse.setHeader("Content-Range", "bytes 0-499/1234"); originResponse.setEntity(makeBody(500)); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); try { - final HttpResponse result = impl.execute(route, HttpRequestWrapper.wrap(request, host), context, null); - Assert.assertTrue(HttpStatus.SC_PARTIAL_CONTENT != result.getStatusLine() - .getStatusCode()); + final HttpResponse result = impl.execute(RoutedHttpRequest.adapt(request, route), context, null); + Assert.assertTrue(HttpStatus.SC_PARTIAL_CONTENT != result.getCode()); } catch (final ClientProtocolException acceptableBehavior) { // this is probably ok } @@ -333,17 +322,15 @@ public class TestProtocolDeviations { @Test public void testPassesOnOrigin401ResponseWithoutWWWAuthenticateHeader() throws Exception { - originResponse = Proxies.enhanceResponse( - new BasicHttpResponse(HTTP_1_1, 401, "Unauthorized")); + originResponse = new BasicClassicHttpResponse(401, "Unauthorized"); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, HttpRequestWrapper.wrap(request, host), context, null); + final HttpResponse result = impl.execute(RoutedHttpRequest.adapt(request, route), context, null); verifyMocks(); Assert.assertSame(originResponse, result); } @@ -356,17 +343,15 @@ public class TestProtocolDeviations { */ @Test public void testPassesOnOrigin405WithoutAllowHeader() throws Exception { - originResponse = Proxies.enhanceResponse( - new BasicHttpResponse(HTTP_1_1, 405, "Method Not Allowed")); + originResponse = new BasicClassicHttpResponse(405, "Method Not Allowed"); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, HttpRequestWrapper.wrap(request, host), context, null); + final HttpResponse result = impl.execute(RoutedHttpRequest.adapt(request, route), context, null); verifyMocks(); Assert.assertSame(originResponse, result); } @@ -380,17 +365,15 @@ public class TestProtocolDeviations { */ @Test public void testPassesOnOrigin407WithoutAProxyAuthenticateHeader() throws Exception { - originResponse = Proxies.enhanceResponse( - new BasicHttpResponse(HTTP_1_1, 407, "Proxy Authentication Required")); + originResponse = new BasicClassicHttpResponse(407, "Proxy Authentication Required"); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, HttpRequestWrapper.wrap(request, host), context, null); + final HttpResponse result = impl.execute(RoutedHttpRequest.adapt(request, route), context, null); verifyMocks(); Assert.assertSame(originResponse, result); } 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 03b32f90f..1116f1ea8 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 @@ -35,22 +35,25 @@ import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.Arrays; import java.util.Date; +import java.util.Iterator; import java.util.List; import org.apache.hc.client5.http.methods.HttpExecutionAware; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.client5.http.methods.HttpPost; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; 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.HeaderElement; -import org.apache.hc.core5.http.HttpRequest; -import org.apache.hc.core5.http.HttpResponse; +import org.apache.hc.core5.http.HttpHeaders; import org.apache.hc.core5.http.HttpStatus; import org.apache.hc.core5.http.HttpVersion; -import org.apache.hc.core5.http.message.BasicHttpRequest; -import org.apache.hc.core5.http.message.BasicHttpResponse; +import org.apache.hc.core5.http.message.BasicClassicHttpRequest; +import org.apache.hc.core5.http.message.BasicClassicHttpResponse; +import org.apache.hc.core5.http.message.MessageSupport; import org.easymock.Capture; import org.easymock.EasyMock; import org.junit.Before; @@ -89,14 +92,14 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { originResponse.setHeader("Content-Encoding", "identity"); backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); boolean foundIdentity = false; - for(final Header h : result.getHeaders("Content-Encoding")) { - for(final HeaderElement elt : h.getElements()) { - if ("identity".equalsIgnoreCase(elt.getName())) { - foundIdentity = true; - } + final Iterator it = MessageSupport.iterate(result, HttpHeaders.CONTENT_ENCODING); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + if ("identity".equalsIgnoreCase(elt.getName())) { + foundIdentity = true; } } assertFalse(foundIdentity); @@ -112,23 +115,23 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { private void cacheGenerated304ForValidatorShouldNotContainEntityHeader( final String headerName, final String headerValue, final String validatorHeader, final String validator, final String conditionalHeader) throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Cache-Control","max-age=3600"); resp1.setHeader(validatorHeader, validator); resp1.setHeader(headerName, headerValue); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); req2.setHeader(conditionalHeader, validator); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - if (HttpStatus.SC_NOT_MODIFIED == result.getStatusLine().getStatusCode()) { + if (HttpStatus.SC_NOT_MODIFIED == result.getCode()) { assertNull(result.getFirstHeader(headerName)); } } @@ -219,42 +222,40 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { private void cacheGenerated304ForStrongValidatorShouldNotContainContentRange( final String validatorHeader, final String validator, final String conditionalHeader) throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); req1.setHeader("Range","bytes=0-127"); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); resp1.setHeader("Cache-Control","max-age=3600"); resp1.setHeader(validatorHeader, validator); resp1.setHeader("Content-Range", "bytes 0-127/256"); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); req2.setHeader("If-Range", validator); req2.setHeader("Range","bytes=0-127"); req2.setHeader(conditionalHeader, validator); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_MODIFIED, "Not Modified"); + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_NOT_MODIFIED, "Not Modified"); resp2.setHeader("Date", DateUtils.formatDate(now)); resp2.setHeader(validatorHeader, validator); // cache module does not currently deal with byte ranges, but we want // this test to work even if it does some day - final Capture cap = new Capture<>(); + final Capture cap = new Capture<>(); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), EasyMock.capture(cap), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp2)).times(0,1); + EasyMock.isNull())).andReturn(resp2).times(0,1); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); if (!cap.hasCaptured() - && HttpStatus.SC_NOT_MODIFIED == result.getStatusLine().getStatusCode()) { + && HttpStatus.SC_NOT_MODIFIED == result.getCode()) { // cache generated a 304 assertNull(result.getFirstHeader("Content-Range")); } @@ -304,10 +305,10 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { private void shouldStripEntityHeaderFromOrigin304ResponseToStrongValidation( final String entityHeader, final String entityHeaderValue) throws Exception { - final HttpRequestWrapper req = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); + final RoutedHttpRequest req = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); req.setHeader("If-None-Match", "\"etag\""); - final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_MODIFIED, "Not Modified"); + final ClassicHttpResponse resp = new BasicClassicHttpResponse(HttpStatus.SC_NOT_MODIFIED, "Not Modified"); resp.setHeader("Date", DateUtils.formatDate(now)); resp.setHeader("Etag", "\"etag\""); resp.setHeader(entityHeader, entityHeaderValue); @@ -315,7 +316,7 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp); replayMocks(); - final HttpResponse result = impl.execute(route, req, context, null); + final ClassicHttpResponse result = impl.execute(req, context, null); verifyMocks(); assertNull(result.getFirstHeader(entityHeader)); @@ -366,11 +367,11 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { @Test public void shouldStripContentRangeFromOrigin304ResponseToStringValidation() throws Exception { - final HttpRequestWrapper req = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); + final RoutedHttpRequest req = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); req.setHeader("If-Range","\"etag\""); req.setHeader("Range","bytes=0-127"); - final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_MODIFIED, "Not Modified"); + final ClassicHttpResponse resp = new BasicClassicHttpResponse(HttpStatus.SC_NOT_MODIFIED, "Not Modified"); resp.setHeader("Date", DateUtils.formatDate(now)); resp.setHeader("ETag", "\"etag\""); resp.setHeader("Content-Range", "bytes 0-127/256"); @@ -378,7 +379,7 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp); replayMocks(); - final HttpResponse result = impl.execute(route, req, context, null); + final ClassicHttpResponse result = impl.execute(req, context, null); verifyMocks(); assertNull(result.getFirstHeader("Content-Range")); @@ -396,10 +397,10 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { * client explicitly requests a first-hand or fresh one, unless it is * impossible to comply for technical or policy reasons." */ - private HttpRequestWrapper requestToPopulateStaleCacheEntry() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + private RoutedHttpRequest requestToPopulateStaleCacheEntry() throws Exception { + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Date", DateUtils.formatDate(tenSecondsAgo)); resp1.setHeader("Cache-Control","public,max-age=5"); resp1.setHeader("Etag","\"etag\""); @@ -408,31 +409,31 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { return req1; } - private void testDoesNotReturnStaleResponseOnError(final HttpRequestWrapper req2) + private void testDoesNotReturnStaleResponseOnError(final RoutedHttpRequest req2) throws Exception { - final HttpRequestWrapper req1 = requestToPopulateStaleCacheEntry(); + final RoutedHttpRequest req1 = requestToPopulateStaleCacheEntry(); backendExpectsAnyRequest().andThrow(new IOException()); replayMocks(); - impl.execute(route, req1, context, null); - HttpResponse result = null; + impl.execute(req1, context, null); + ClassicHttpResponse result = null; try { - result = impl.execute(route, req2, context, null); + result = impl.execute(req2, context, null); } catch (final IOException acceptable) { } verifyMocks(); if (result != null) { - assertFalse(result.getStatusLine().getStatusCode() == HttpStatus.SC_OK); + assertFalse(result.getCode() == HttpStatus.SC_OK); } } @Test public void testDoesNotReturnStaleResponseIfClientExplicitlyRequestsFirstHandOneWithCacheControl() throws Exception { - final HttpRequestWrapper req = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req.setHeader("Cache-Control","no-cache"); testDoesNotReturnStaleResponseOnError(req); } @@ -440,8 +441,8 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { @Test public void testDoesNotReturnStaleResponseIfClientExplicitlyRequestsFirstHandOneWithPragma() throws Exception { - final HttpRequestWrapper req = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req.setHeader("Pragma","no-cache"); testDoesNotReturnStaleResponseOnError(req); } @@ -449,8 +450,8 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { @Test public void testDoesNotReturnStaleResponseIfClientExplicitlyRequestsFreshWithMaxAge() throws Exception { - final HttpRequestWrapper req = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req.setHeader("Cache-Control","max-age=0"); testDoesNotReturnStaleResponseOnError(req); } @@ -458,8 +459,8 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { @Test public void testDoesNotReturnStaleResponseIfClientExplicitlySpecifiesLargerMaxAge() throws Exception { - final HttpRequestWrapper req = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req.setHeader("Cache-Control","max-age=20"); testDoesNotReturnStaleResponseOnError(req); } @@ -468,8 +469,8 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { @Test public void testDoesNotReturnStaleResponseIfClientExplicitlyRequestsFreshWithMinFresh() throws Exception { - final HttpRequestWrapper req = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req.setHeader("Cache-Control","min-fresh=2"); testDoesNotReturnStaleResponseOnError(req); @@ -478,8 +479,8 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { @Test public void testDoesNotReturnStaleResponseIfClientExplicitlyRequestsFreshWithMaxStale() throws Exception { - final HttpRequestWrapper req = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req.setHeader("Cache-Control","max-stale=2"); testDoesNotReturnStaleResponseOnError(req); @@ -488,19 +489,19 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { @Test public void testMayReturnStaleResponseIfClientExplicitlySpecifiesAcceptableMaxStale() throws Exception { - final HttpRequestWrapper req1 = requestToPopulateStaleCacheEntry(); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = requestToPopulateStaleCacheEntry(); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("Cache-Control","max-stale=20"); backendExpectsAnyRequest().andThrow(new IOException()).times(0,1); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - assertEquals(HttpStatus.SC_OK, result.getStatusLine().getStatusCode()); + assertEquals(HttpStatus.SC_OK, result.getCode()); assertNotNull(result.getFirstHeader("Warning")); } @@ -540,26 +541,26 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { @Test public void testReturnsCachedResponsesAppropriatelyWhenNoOriginCommunication() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Cache-Control", "public, max-age=5"); resp1.setHeader("ETag","\"etag\""); resp1.setHeader("Date", DateUtils.formatDate(tenSecondsAgo)); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); backendExpectsAnyRequest().andThrow(new IOException()).anyTimes(); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - assertEquals(HttpStatus.SC_OK, result.getStatusLine().getStatusCode()); + assertEquals(HttpStatus.SC_OK, result.getCode()); boolean warning111Found = false; for(final Header h : result.getHeaders("Warning")) { for(final WarningValue wv : WarningValue.getWarningValues(h)) { @@ -594,7 +595,7 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); assertNull(result.getFirstHeader("Warning")); @@ -613,7 +614,7 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); assertEquals(warning, result.getFirstHeader("Warning").getValue()); @@ -631,7 +632,7 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { .getCanonicalHeaderValue(originResponse, headerName); backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); assertEquals(headerValue, result.getFirstHeader(headerName).getValue()); @@ -640,15 +641,14 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { private void testDoesNotModifyHeaderOnRequests(final String headerName) throws Exception { final String headerValue = HttpTestUtils.getCanonicalHeaderValue(request, headerName); - final Capture cap = new Capture<>(); + final Capture cap = new Capture<>(); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), EasyMock.capture(cap), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - impl.execute(route, request, context, null); + impl.execute(request, context, null); verifyMocks(); assertEquals(headerValue, HttpTestUtils.getCanonicalHeaderValue(cap.getValue(), @@ -673,11 +673,10 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { @Test public void testDoesNotModifyContentLengthOnRequests() throws Exception { - final HttpRequest post = - new BasicHttpRequest("POST", "/", HttpVersion.HTTP_1_1); + final ClassicHttpRequest post = new BasicClassicHttpRequest("POST", "/"); post.setEntity(HttpTestUtils.makeBody(128)); post.setHeader("Content-Length","128"); - request = HttpRequestWrapper.wrap(post, host); + request = RoutedHttpRequest.adapt(post, route); testDoesNotModifyHeaderOnRequests("Content-Length"); } @@ -692,12 +691,11 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { @Test public void testDoesNotModifyContentMD5OnRequests() throws Exception { - final HttpRequest post = - new BasicHttpRequest("POST", "/", HttpVersion.HTTP_1_1); + final ClassicHttpRequest post = new BasicClassicHttpRequest("POST", "/"); post.setEntity(HttpTestUtils.makeBody(128)); post.setHeader("Content-Length","128"); post.setHeader("Content-MD5","Q2hlY2sgSW50ZWdyaXR5IQ=="); - request = HttpRequestWrapper.wrap(post, host); + request = RoutedHttpRequest.adapt(post, route); testDoesNotModifyHeaderOnRequests("Content-MD5"); } @@ -712,12 +710,11 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { @Test public void testDoesNotModifyContentRangeOnRequests() throws Exception { - final HttpRequest put = - new BasicHttpRequest("PUT", "/", HttpVersion.HTTP_1_1); + final ClassicHttpRequest put = new BasicClassicHttpRequest("PUT", "/"); put.setEntity(HttpTestUtils.makeBody(128)); put.setHeader("Content-Length","128"); put.setHeader("Content-Range","bytes 0-127/256"); - request = HttpRequestWrapper.wrap(put, host); + request = RoutedHttpRequest.adapt(put, route); testDoesNotModifyHeaderOnRequests("Content-Range"); } @@ -725,7 +722,7 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { public void testDoesNotModifyContentRangeOnResponses() throws Exception { request.setHeader("Range","bytes=0-128"); - originResponse.setStatusCode(HttpStatus.SC_PARTIAL_CONTENT); + originResponse.setCode(HttpStatus.SC_PARTIAL_CONTENT); originResponse.setReasonPhrase("Partial Content"); originResponse.setEntity(HttpTestUtils.makeBody(128)); originResponse.setHeader("Content-Range","bytes 0-127/256"); @@ -735,12 +732,11 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { @Test public void testDoesNotModifyContentTypeOnRequests() throws Exception { - final HttpRequest post = - new BasicHttpRequest("POST", "/", HttpVersion.HTTP_1_1); + final ClassicHttpRequest post = new BasicClassicHttpRequest("POST", "/"); post.setEntity(HttpTestUtils.makeBody(128)); post.setHeader("Content-Length","128"); post.setHeader("Content-Type","application/octet-stream"); - request = HttpRequestWrapper.wrap(post, host); + request = RoutedHttpRequest.adapt(post, route); testDoesNotModifyHeaderOnRequests("Content-Type"); } @@ -789,8 +785,8 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { @Test public void testDoesNotModifyIfMatchOnRequests() throws Exception { - request = HttpRequestWrapper.wrap( - new BasicHttpRequest("DELETE", "/", HttpVersion.HTTP_1_1), host); + request = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("DELETE", "/"), route); request.setHeader("If-Match", "\"etag\""); testDoesNotModifyHeaderOnRequests("If-Match"); } @@ -820,8 +816,8 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { @Test public void testDoesNotModifyIfUnmodifiedSinceOnRequests() throws Exception { - request = HttpRequestWrapper.wrap( - new BasicHttpRequest("DELETE", "/", HttpVersion.HTTP_1_1), host); + request = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("DELETE", "/"), route); request.setHeader("If-Unmodified-Since", DateUtils.formatDate(new Date())); testDoesNotModifyHeaderOnRequests("If-Unmodified-Since"); } @@ -836,7 +832,7 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { @Test public void testDoesNotModifyLocationOnResponses() throws Exception { - originResponse.setStatusCode(HttpStatus.SC_TEMPORARY_REDIRECT); + originResponse.setCode(HttpStatus.SC_TEMPORARY_REDIRECT); originResponse.setReasonPhrase("Temporary Redirect"); originResponse.setHeader("Location", "http://foo.example.com/bar"); testDoesNotModifyHeaderOnResponses("Location"); @@ -859,7 +855,7 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { @Test public void testDoesNotModifyRetryAfterOnResponses() throws Exception { - originResponse.setStatusCode(HttpStatus.SC_SERVICE_UNAVAILABLE); + originResponse.setCode(HttpStatus.SC_SERVICE_UNAVAILABLE); originResponse.setReasonPhrase("Service Unavailable"); originResponse.setHeader("Retry-After", "120"); testDoesNotModifyHeaderOnResponses("Retry-After"); @@ -915,34 +911,32 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { final Date twentySecondsAgo = new Date(now.getTime() - 20 * 1000L); final String lmDate = DateUtils.formatDate(twentySecondsAgo); - final HttpRequestWrapper req1 = - HttpRequestWrapper.wrap(new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = + RoutedHttpRequest.adapt(new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Date", DateUtils.formatDate(tenSecondsAgo)); resp1.setHeader("Last-Modified", lmDate); resp1.setHeader("Cache-Control","max-age=5"); backendExpectsAnyRequestAndReturn(resp1); - final Capture cap = new Capture<>(); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final Capture cap = new Capture<>(); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), EasyMock.capture(cap), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp2)); + EasyMock.isNull())).andReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); verifyMocks(); - final HttpRequest captured = cap.getValue(); + final ClassicHttpRequest captured = cap.getValue(); final Header ifModifiedSince = captured.getFirstHeader("If-Modified-Since"); assertEquals(lmDate, ifModifiedSince.getValue()); @@ -963,9 +957,9 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { final String lmDate = DateUtils.formatDate(twentySecondsAgo); final String etag = "\"etag\""; - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Date", DateUtils.formatDate(tenSecondsAgo)); resp1.setHeader("Last-Modified", lmDate); resp1.setHeader("Cache-Control","max-age=5"); @@ -973,25 +967,23 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp1); - final Capture cap = new Capture<>(); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final Capture cap = new Capture<>(); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), EasyMock.capture(cap), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp2)); + EasyMock.isNull())).andReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); verifyMocks(); - final HttpRequest captured = cap.getValue(); + final ClassicHttpRequest captured = cap.getValue(); final Header ifModifiedSince = captured.getFirstHeader("If-Modified-Since"); assertEquals(lmDate, ifModifiedSince.getValue()); @@ -1014,9 +1006,9 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { final Date oneSecondAgo = new Date(now.getTime() - 1 * 1000L); final Date oneSecondFromNow = new Date(now.getTime() + 1 * 1000L); final Date twoSecondsFromNow = new Date(now.getTime() + 2 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("ETag","\"etag\""); resp1.setHeader("Date", DateUtils.formatDate(now)); resp1.setHeader("Expires",DateUtils.formatDate(oneSecondAgo)); @@ -1024,33 +1016,30 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpRequestWrapper revalidate = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/",HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final RoutedHttpRequest revalidate = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); revalidate.setHeader("If-None-Match","\"etag\""); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_NOT_MODIFIED, "Not Modified"); + final ClassicHttpResponse resp2 = HttpTestUtils.make304Response(); resp2.setHeader("Date", DateUtils.formatDate(twoSecondsFromNow)); resp2.setHeader("Expires", DateUtils.formatDate(oneSecondFromNow)); resp2.setHeader("ETag","\"etag\""); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), eqRequest(revalidate), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp2)); + EasyMock.isNull())).andReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); assertEquals(HttpStatus.SC_OK, - result.getStatusLine().getStatusCode()); + result.getCode()); } /* "When a client tries to revalidate a cache entry, and the response @@ -1070,60 +1059,57 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { public void testRetriesValidationThatResultsInAnOlderDated304Response() throws Exception { final Date elevenSecondsAgo = new Date(now.getTime() - 11 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("ETag","\"etag\""); resp1.setHeader("Date", DateUtils.formatDate(tenSecondsAgo)); resp1.setHeader("Cache-Control","max-age=5"); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_NOT_MODIFIED, "Not Modified"); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp2 = HttpTestUtils.make304Response(); resp2.setHeader("ETag","\"etag\""); resp2.setHeader("Date", DateUtils.formatDate(elevenSecondsAgo)); backendExpectsAnyRequestAndReturn(resp2); - final Capture cap = new Capture<>(); - final HttpResponse resp3 = HttpTestUtils.make200Response(); + final Capture cap = new Capture<>(); + final ClassicHttpResponse resp3 = HttpTestUtils.make200Response(); resp3.setHeader("ETag","\"etag2\""); resp3.setHeader("Date", DateUtils.formatDate(now)); resp3.setHeader("Cache-Control","max-age=5"); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), EasyMock.capture(cap), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp3)); + EasyMock.isNull())).andReturn(resp3); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); verifyMocks(); - final HttpRequest captured = cap.getValue(); + final ClassicHttpRequest captured = cap.getValue(); boolean hasMaxAge0 = false; boolean hasNoCache = false; - for(final Header h : captured.getHeaders("Cache-Control")) { - for(final HeaderElement elt : h.getElements()) { - if ("max-age".equals(elt.getName())) { - try { - final int maxage = Integer.parseInt(elt.getValue()); - if (maxage == 0) { - hasMaxAge0 = true; - } - } catch (final NumberFormatException nfe) { - // nop + final Iterator it = MessageSupport.iterate(captured, HttpHeaders.CACHE_CONTROL); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + if ("max-age".equals(elt.getName())) { + try { + final int maxage = Integer.parseInt(elt.getValue()); + if (maxage == 0) { + hasMaxAge0 = true; } - } else if ("no-cache".equals(elt.getName())) { - hasNoCache = true; + } catch (final NumberFormatException nfe) { + // nop } + } else if ("no-cache".equals(elt.getName())) { + hasNoCache = true; } } assertTrue(hasMaxAge0 || hasNoCache); @@ -1144,47 +1130,45 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { @Test public void testSendsAllVariantEtagsInConditionalRequest() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET","/",HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET","/"), route); req1.setHeader("User-Agent","agent1"); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Cache-Control","max-age=3600"); resp1.setHeader("Vary","User-Agent"); resp1.setHeader("Etag","\"etag1\""); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET","/",HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET","/"), route); req2.setHeader("User-Agent","agent2"); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); resp2.setHeader("Cache-Control","max-age=3600"); resp2.setHeader("Vary","User-Agent"); resp2.setHeader("Etag","\"etag2\""); backendExpectsAnyRequestAndReturn(resp2); - final Capture cap = new Capture<>(); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET","/",HttpVersion.HTTP_1_1), host); + final Capture cap = new Capture<>(); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET","/"), route); req3.setHeader("User-Agent","agent3"); - final HttpResponse resp3 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp3 = HttpTestUtils.make200Response(); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), EasyMock.capture(cap), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp3)); + EasyMock.isNull())).andReturn(resp3); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); - impl.execute(route, req3, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); + impl.execute(req3, context, null); verifyMocks(); - final HttpRequest captured = cap.getValue(); + final ClassicHttpRequest captured = cap.getValue(); boolean foundEtag1 = false; boolean foundEtag2 = false; for(final Header h : captured.getHeaders("If-None-Match")) { @@ -1211,11 +1195,11 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { public void testResponseToExistingVariantsUpdatesEntry() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req1.setHeader("User-Agent", "agent1"); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Date", DateUtils.formatDate(tenSecondsAgo)); resp1.setHeader("Vary", "User-Agent"); resp1.setHeader("Cache-Control", "max-age=3600"); @@ -1224,11 +1208,11 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("User-Agent", "agent2"); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); resp2.setHeader("Date", DateUtils.formatDate(tenSecondsAgo)); resp2.setHeader("Vary", "User-Agent"); resp2.setHeader("Cache-Control", "max-age=3600"); @@ -1236,28 +1220,28 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp2); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req3.setHeader("User-Agent", "agent3"); - final HttpResponse resp3 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_MODIFIED, "Not Modified"); + final ClassicHttpResponse resp3 = new BasicClassicHttpResponse(HttpStatus.SC_NOT_MODIFIED, "Not Modified"); resp3.setHeader("Date", DateUtils.formatDate(now)); resp3.setHeader("ETag", "\"etag1\""); backendExpectsAnyRequestAndReturn(resp3); - final HttpRequestWrapper req4 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req4 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req4.setHeader("User-Agent", "agent1"); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); - final HttpResponse result1 = impl.execute(route, req3, context, null); - final HttpResponse result2 = impl.execute(route, req4, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); + final ClassicHttpResponse result1 = impl.execute(req3, context, null); + final ClassicHttpResponse result2 = impl.execute(req4, context, null); verifyMocks(); - assertEquals(HttpStatus.SC_OK, result1.getStatusLine().getStatusCode()); + assertEquals(HttpStatus.SC_OK, result1.getCode()); assertEquals("\"etag1\"", result1.getFirstHeader("ETag").getValue()); assertEquals(DateUtils.formatDate(now), result1.getFirstHeader("Date").getValue()); assertEquals(DateUtils.formatDate(now), result2.getFirstHeader("Date").getValue()); @@ -1267,11 +1251,11 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { public void testResponseToExistingVariantsIsCachedForFutureResponses() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req1.setHeader("User-Agent", "agent1"); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Date", DateUtils.formatDate(tenSecondsAgo)); resp1.setHeader("Vary", "User-Agent"); resp1.setHeader("Cache-Control", "max-age=3600"); @@ -1279,24 +1263,24 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("User-Agent", "agent2"); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_MODIFIED, "Not Modified"); + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_NOT_MODIFIED, "Not Modified"); resp2.setHeader("Date", DateUtils.formatDate(now)); resp2.setHeader("ETag", "\"etag1\""); backendExpectsAnyRequestAndReturn(resp2); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req3.setHeader("User-Agent", "agent2"); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); - impl.execute(route, req3, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); + impl.execute(req3, context, null); verifyMocks(); } @@ -1310,20 +1294,19 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { @Test public void variantNegotiationsDoNotIncludeEtagsForPartialResponses() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); req1.setHeader("User-Agent", "agent1"); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Cache-Control", "max-age=3600"); resp1.setHeader("Vary", "User-Agent"); resp1.setHeader("ETag", "\"etag1\""); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); req2.setHeader("User-Agent", "agent2"); req2.setHeader("Range", "bytes=0-49"); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); resp2.setEntity(HttpTestUtils.makeBody(50)); resp2.setHeader("Content-Length","50"); resp2.setHeader("Content-Range","bytes 0-49/100"); @@ -1334,34 +1317,32 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp2); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); req3.setHeader("User-Agent", "agent3"); - final HttpResponse resp3 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp3 = HttpTestUtils.make200Response(); resp1.setHeader("Cache-Control", "max-age=3600"); resp1.setHeader("Vary", "User-Agent"); resp1.setHeader("ETag", "\"etag3\""); - final Capture cap = new Capture<>(); + final Capture cap = new Capture<>(); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), EasyMock.capture(cap), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp3)); + EasyMock.isNull())).andReturn(resp3); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); - impl.execute(route, req3, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); + impl.execute(req3, context, null); verifyMocks(); - final HttpRequest captured = cap.getValue(); - for(final Header h : captured.getHeaders("If-None-Match")) { - for(final HeaderElement elt : h.getElements()) { - assertFalse("\"etag2\"".equals(elt.toString())); - } + final ClassicHttpRequest captured = cap.getValue(); + final Iterator it = MessageSupport.iterate(captured, HttpHeaders.IF_NONE_MATCH); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + assertFalse("\"etag2\"".equals(elt.toString())); } } @@ -1377,34 +1358,34 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { @Test public void cachedEntryShouldNotBeUsedIfMoreRecentMentionInContentLocation() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new HttpGet("http://foo.example.com/"), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new HttpGet("http://foo.example.com/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Cache-Control","max-age=3600"); resp1.setHeader("ETag", "\"old-etag\""); resp1.setHeader("Date", DateUtils.formatDate(tenSecondsAgo)); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new HttpPost("http://foo.example.com/bar"), host); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new HttpPost("http://foo.example.com/bar"), route); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); resp2.setHeader("ETag", "\"new-etag\""); resp2.setHeader("Date", DateUtils.formatDate(now)); resp2.setHeader("Content-Location", "http://foo.example.com/"); backendExpectsAnyRequestAndReturn(resp2); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap( - new HttpGet("http://foo.example.com"), host); - final HttpResponse resp3 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt( + new HttpGet("http://foo.example.com"), route); + final ClassicHttpResponse resp3 = HttpTestUtils.make200Response(); backendExpectsAnyRequestAndReturn(resp3); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); - impl.execute(route, req3, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); + impl.execute(req3, context, null); verifyMocks(); } @@ -1418,9 +1399,10 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { @Test public void responseToGetWithQueryFrom1_0OriginAndNoExpiresIsNotCached() throws Exception { - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new HttpGet("http://foo.example.com/bar?baz=quux"), host); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_0, HttpStatus.SC_OK, "OK"); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new HttpGet("http://foo.example.com/bar?baz=quux"), route); + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); + resp2.setVersion(HttpVersion.HTTP_1_0); resp2.setEntity(HttpTestUtils.makeBody(200)); resp2.setHeader("Content-Length","200"); resp2.setHeader("Date", DateUtils.formatDate(now)); @@ -1428,16 +1410,17 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req2, context, null); + impl.execute(req2, context, null); verifyMocks(); } @Test public void responseToGetWithQueryFrom1_0OriginVia1_1ProxyAndNoExpiresIsNotCached() throws Exception { - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new HttpGet("http://foo.example.com/bar?baz=quux"), host); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_0, HttpStatus.SC_OK, "OK"); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new HttpGet("http://foo.example.com/bar?baz=quux"), route); + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); + resp2.setVersion(HttpVersion.HTTP_1_0); resp2.setEntity(HttpTestUtils.makeBody(200)); resp2.setHeader("Content-Length","200"); resp2.setHeader("Date", DateUtils.formatDate(now)); @@ -1446,7 +1429,7 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req2, context, null); + impl.execute(req2, context, null); verifyMocks(); } @@ -1460,31 +1443,31 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { @Test public void shouldInvalidateNonvariantCacheEntryForUnknownMethod() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Cache-Control","max-age=3600"); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("FROB", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("FROB", "/"), route); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); resp2.setHeader("Cache-Control","max-age=3600"); backendExpectsAnyRequestAndReturn(resp2); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp3 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp3 = HttpTestUtils.make200Response(); resp3.setHeader("ETag", "\"etag\""); backendExpectsAnyRequestAndReturn(resp3); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); - final HttpResponse result = impl.execute(route, req3, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); + final ClassicHttpResponse result = impl.execute(req3, context, null); verifyMocks(); assertTrue(HttpTestUtils.semanticallyTransparent(resp3, result)); @@ -1493,54 +1476,54 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { @Test public void shouldInvalidateAllVariantsForUnknownMethod() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req1.setHeader("User-Agent", "agent1"); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Cache-Control","max-age=3600"); resp1.setHeader("Vary", "User-Agent"); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("User-Agent", "agent2"); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); resp2.setHeader("Cache-Control","max-age=3600"); resp2.setHeader("Vary", "User-Agent"); backendExpectsAnyRequestAndReturn(resp2); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap( - new BasicHttpRequest("FROB", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("FROB", "/"), route); req3.setHeader("User-Agent", "agent3"); - final HttpResponse resp3 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp3 = HttpTestUtils.make200Response(); resp3.setHeader("Cache-Control","max-age=3600"); backendExpectsAnyRequestAndReturn(resp3); - final HttpRequestWrapper req4 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req4 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req4.setHeader("User-Agent", "agent1"); - final HttpResponse resp4 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp4 = HttpTestUtils.make200Response(); resp4.setHeader("ETag", "\"etag1\""); backendExpectsAnyRequestAndReturn(resp4); - final HttpRequestWrapper req5 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req5 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req5.setHeader("User-Agent", "agent2"); - final HttpResponse resp5 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp5 = HttpTestUtils.make200Response(); resp5.setHeader("ETag", "\"etag2\""); backendExpectsAnyRequestAndReturn(resp5); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); - impl.execute(route, req3, context, null); - final HttpResponse result4 = impl.execute(route, req4, context, null); - final HttpResponse result5 = impl.execute(route, req5, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); + impl.execute(req3, context, null); + final ClassicHttpResponse result4 = impl.execute(req4, context, null); + final ClassicHttpResponse result5 = impl.execute(req5, context, null); verifyMocks(); assertTrue(HttpTestUtils.semanticallyTransparent(resp4, result4)); @@ -1557,29 +1540,29 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { @Test public void cacheShouldUpdateWithNewCacheableResponse() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Date", DateUtils.formatDate(tenSecondsAgo)); resp1.setHeader("Cache-Control", "max-age=3600"); resp1.setHeader("ETag", "\"etag1\""); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); req2.setHeader("Cache-Control", "max-age=0"); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); resp2.setHeader("Date", DateUtils.formatDate(now)); resp2.setHeader("Cache-Control", "max-age=3600"); resp2.setHeader("ETag", "\"etag2\""); backendExpectsAnyRequestAndReturn(resp2); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); - final HttpResponse result = impl.execute(route, req3, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); + final ClassicHttpResponse result = impl.execute(req3, context, null); verifyMocks(); assertTrue(HttpTestUtils.semanticallyTransparent(resp2, result)); @@ -1599,24 +1582,24 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { @Test public void expiresEqualToDateWithNoCacheControlIsNotCacheable() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Date", DateUtils.formatDate(now)); resp1.setHeader("Expires", DateUtils.formatDate(now)); resp1.removeHeaders("Cache-Control"); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); req2.setHeader("Cache-Control", "max-stale=1000"); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); resp2.setHeader("ETag", "\"etag2\""); backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); assertTrue(HttpTestUtils.semanticallyTransparent(resp2, result)); @@ -1625,24 +1608,24 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { @Test public void expiresPriorToDateWithNoCacheControlIsNotCacheable() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Date", DateUtils.formatDate(now)); resp1.setHeader("Expires", DateUtils.formatDate(tenSecondsAgo)); resp1.removeHeaders("Cache-Control"); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); req2.setHeader("Cache-Control", "max-stale=1000"); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); resp2.setHeader("ETag", "\"etag2\""); backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); assertTrue(HttpTestUtils.semanticallyTransparent(resp2, result)); @@ -1657,37 +1640,35 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { @Test public void otherFreshnessRequestDirectivesNotAllowedWithNoCache() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); req1.setHeader("Cache-Control", "min-fresh=10, no-cache"); req1.addHeader("Cache-Control", "max-stale=0, max-age=0"); - final Capture cap = new Capture<>(); + final Capture cap = new Capture<>(); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), EasyMock.capture(cap), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(HttpTestUtils.make200Response())); + EasyMock.isNull())).andReturn(HttpTestUtils.make200Response()); replayMocks(); - impl.execute(route, req1, context, null); + impl.execute(req1, context, null); verifyMocks(); - final HttpRequest captured = cap.getValue(); + final ClassicHttpRequest captured = cap.getValue(); boolean foundNoCache = false; boolean foundDisallowedDirective = false; final List disallowed = Arrays.asList("min-fresh", "max-stale", "max-age"); - for(final Header h : captured.getHeaders("Cache-Control")) { - for(final HeaderElement elt : h.getElements()) { - if (disallowed.contains(elt.getName())) { - foundDisallowedDirective = true; - } - if ("no-cache".equals(elt.getName())) { - foundNoCache = true; - } + final Iterator it = MessageSupport.iterate(captured, HttpHeaders.CACHE_CONTROL); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + if (disallowed.contains(elt.getName())) { + foundDisallowedDirective = true; + } + if ("no-cache".equals(elt.getName())) { + foundNoCache = true; } } assertTrue(foundNoCache); @@ -1706,32 +1687,32 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { @Test public void cacheMissResultsIn504WithOnlyIfCached() throws Exception { - final HttpRequestWrapper req = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); + final RoutedHttpRequest req = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); req.setHeader("Cache-Control", "only-if-cached"); replayMocks(); - final HttpResponse result = impl.execute(route, req, context, null); + final ClassicHttpResponse result = impl.execute(req, context, null); verifyMocks(); assertEquals(HttpStatus.SC_GATEWAY_TIMEOUT, - result.getStatusLine().getStatusCode()); + result.getCode()); } @Test public void cacheHitOkWithOnlyIfCached() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Cache-Control","max-age=3600"); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); req2.setHeader("Cache-Control", "only-if-cached"); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); assertTrue(HttpTestUtils.semanticallyTransparent(resp1, result)); @@ -1740,42 +1721,42 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { @Test public void returns504ForStaleEntryWithOnlyIfCached() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Date", DateUtils.formatDate(tenSecondsAgo)); resp1.setHeader("Cache-Control","max-age=5"); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); req2.setHeader("Cache-Control", "only-if-cached"); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); assertEquals(HttpStatus.SC_GATEWAY_TIMEOUT, - result.getStatusLine().getStatusCode()); + result.getCode()); } @Test public void returnsStaleCacheEntryWithOnlyIfCachedAndMaxStale() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Date", DateUtils.formatDate(tenSecondsAgo)); resp1.setHeader("Cache-Control","max-age=5"); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); req2.setHeader("Cache-Control", "max-stale=20, only-if-cached"); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); assertTrue(HttpTestUtils.semanticallyTransparent(resp1, result)); @@ -1783,23 +1764,23 @@ public class TestProtocolRecommendations extends AbstractProtocolTest { @Test public void issues304EvenWithWeakETag() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Date", DateUtils.formatDate(tenSecondsAgo)); resp1.setHeader("Cache-Control", "max-age=300"); resp1.setHeader("ETag","W/\"weak-sauce\""); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); req2.setHeader("If-None-Match","W/\"weak-sauce\""); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getStatusLine().getStatusCode()); + assertEquals(HttpStatus.SC_NOT_MODIFIED, 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 06feb1769..e7b1b5469 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 @@ -30,33 +30,34 @@ import java.io.IOException; import java.io.InputStream; import java.net.SocketTimeoutException; import java.util.Date; +import java.util.Iterator; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.hc.client5.http.HttpRoute; import org.apache.hc.client5.http.cache.HttpCacheEntry; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpExecutionAware; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.ClientProtocolException; 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.HeaderElement; import org.apache.hc.core5.http.HeaderElements; 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.HttpResponse; import org.apache.hc.core5.http.HttpStatus; import org.apache.hc.core5.http.HttpVersion; import org.apache.hc.core5.http.ProtocolVersion; -import org.apache.hc.core5.http.entity.BasicHttpEntity; -import org.apache.hc.core5.http.entity.ByteArrayEntity; +import org.apache.hc.core5.http.io.entity.BasicHttpEntity; +import org.apache.hc.core5.http.io.entity.ByteArrayEntity; +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.BasicHttpRequest; -import org.apache.hc.core5.http.message.BasicHttpResponse; +import org.apache.hc.core5.http.message.MessageSupport; import org.easymock.Capture; import org.easymock.EasyMock; import org.junit.Assert; @@ -78,13 +79,12 @@ public class TestProtocolRequirements extends AbstractProtocolTest { public void testCacheMissOnGETUsesOriginResponse() throws Exception { EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), eqRequest(request), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); Assert.assertTrue(HttpTestUtils.semanticallyTransparent(originResponse, result)); @@ -106,18 +106,17 @@ public class TestProtocolRequirements extends AbstractProtocolTest { // tunnel behavior: I don't muck with request or response in // any way - request = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/foo", new ProtocolVersion("HTTP", 2, 13)), host); + request = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("GET", "/foo"), route); + request.setVersion(new ProtocolVersion("HTTP", 2, 13)); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), eqRequest(request), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); Assert.assertSame(originResponse, result); @@ -126,21 +125,22 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testHigher1_XProtocolVersionsDowngradeTo1_1() throws Exception { - request = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/foo", new ProtocolVersion("HTTP", 1, 2)), host); + request = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/foo"), route); + request.setVersion(new ProtocolVersion("HTTP", 1, 2)); - final HttpRequestWrapper downgraded = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/foo", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest downgraded = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/foo"), route); + downgraded.setVersion(HttpVersion.HTTP_1_1); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), eqRequest(downgraded), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); Assert.assertTrue(HttpTestUtils.semanticallyTransparent(originResponse, result)); @@ -158,20 +158,21 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testRequestsWithLowerProtocolVersionsGetUpgradedTo1_1() throws Exception { - request = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/foo", new ProtocolVersion("HTTP", 1, 0)), host); - final HttpRequestWrapper upgraded = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/foo", HttpVersion.HTTP_1_1), host); + request = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/foo"), route); + request.setVersion(new ProtocolVersion("HTTP", 1, 0)); + final RoutedHttpRequest upgraded = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/foo"), route); + upgraded.setVersion(HttpVersion.HTTP_1_1); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), eqRequest(upgraded), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); Assert.assertTrue(HttpTestUtils.semanticallyTransparent(originResponse, result)); @@ -187,8 +188,8 @@ public class TestProtocolRequirements extends AbstractProtocolTest { */ @Test public void testLowerOriginResponsesUpgradedToOurVersion1_1() throws Exception { - originResponse = Proxies.enhanceResponse( - new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 2), HttpStatus.SC_OK, "OK")); + originResponse = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); + originResponse.setVersion(new ProtocolVersion("HTTP", 1, 2)); originResponse.setHeader("Date", DateUtils.formatDate(new Date())); originResponse.setHeader("Server", "MockOrigin/1.0"); originResponse.setEntity(body); @@ -197,35 +198,34 @@ public class TestProtocolRequirements extends AbstractProtocolTest { // to check the protocol version that comes out the other end EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); - Assert.assertEquals(HttpVersion.HTTP_1_1, result.getProtocolVersion()); + Assert.assertEquals(HttpVersion.HTTP_1_1, result.getVersion()); } @Test public void testResponseToA1_0RequestShouldUse1_1() throws Exception { - request = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/foo", new ProtocolVersion("HTTP", 1, 0)), host); + request = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/foo"), route); + request.setVersion(new ProtocolVersion("HTTP", 1, 0)); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); - Assert.assertEquals(HttpVersion.HTTP_1_1, result.getProtocolVersion()); + Assert.assertEquals(HttpVersion.HTTP_1_1, result.getVersion()); } /* @@ -234,25 +234,26 @@ public class TestProtocolRequirements extends AbstractProtocolTest { */ @Test public void testForwardsUnknownHeadersOnRequestsFromHigherProtocolVersions() throws Exception { - request = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/foo", new ProtocolVersion("HTTP", 1, 2)), host); + request = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/foo"), route); + request.setVersion(new ProtocolVersion("HTTP", 1, 2)); request.removeHeaders("Connection"); request.addHeader("X-Unknown-Header", "some-value"); - final HttpRequestWrapper downgraded = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/foo", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest downgraded = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/foo"), route); + downgraded.setVersion(HttpVersion.HTTP_1_1); downgraded.removeHeaders("Connection"); downgraded.addHeader("X-Unknown-Header", "some-value"); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), eqRequest(downgraded), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - impl.execute(route, request, context, null); + impl.execute(request, context, null); verifyMocks(); } @@ -266,18 +267,18 @@ public class TestProtocolRequirements extends AbstractProtocolTest { originResponse.setHeader("Transfer-Encoding", "identity"); - request = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/foo", new ProtocolVersion("HTTP", 1, 0)), host); + final ClassicHttpRequest originalRequest = new BasicClassicHttpRequest("GET", "/foo"); + originalRequest.setVersion(new ProtocolVersion("HTTP", 1, 0)); + request = RoutedHttpRequest.adapt(originalRequest, route); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); @@ -298,23 +299,22 @@ public class TestProtocolRequirements extends AbstractProtocolTest { * these field values when a message is forwarded." * http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 */ - private void testOrderOfMultipleHeadersIsPreservedOnRequests(final String h, final HttpRequestWrapper request) + private void testOrderOfMultipleHeadersIsPreservedOnRequests(final String h, final RoutedHttpRequest request) throws Exception { - final Capture reqCapture = new Capture<>(); + final Capture reqCapture = new Capture<>(); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), EasyMock.capture(reqCapture), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - impl.execute(route, request, context, null); + impl.execute(request, context, null); verifyMocks(); - final HttpRequest forwarded = reqCapture.getValue(); + final ClassicHttpRequest forwarded = reqCapture.getValue(); Assert.assertNotNull(forwarded); final String expected = HttpTestUtils.getCanonicalHeaderValue(request, h); final String actual = HttpTestUtils.getCanonicalHeaderValue(forwarded, h); @@ -354,13 +354,12 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testOrderOfMultipleAllowHeadersIsPreservedOnRequests() throws Exception { - final BasicHttpRequest put = new BasicHttpRequest("PUT", "/", - HttpVersion.HTTP_1_1); + final BasicClassicHttpRequest put = new BasicClassicHttpRequest("PUT", "/"); put.setEntity(body); put.addHeader("Allow", "GET, HEAD"); put.addHeader("Allow", "DELETE"); put.addHeader("Content-Length", "128"); - testOrderOfMultipleHeadersIsPreservedOnRequests("Allow", HttpRequestWrapper.wrap(put, host)); + testOrderOfMultipleHeadersIsPreservedOnRequests("Allow", RoutedHttpRequest.adapt(put, route)); } @Test @@ -372,35 +371,32 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testOrderOfMultipleContentEncodingHeadersIsPreservedOnRequests() throws Exception { - final BasicHttpRequest post = new BasicHttpRequest("POST", "/", - HttpVersion.HTTP_1_1); + final BasicClassicHttpRequest post = new BasicClassicHttpRequest("POST", "/"); post.setEntity(body); post.addHeader("Content-Encoding", "gzip"); post.addHeader("Content-Encoding", "compress"); post.addHeader("Content-Length", "128"); - testOrderOfMultipleHeadersIsPreservedOnRequests("Content-Encoding", HttpRequestWrapper.wrap(post, host)); + testOrderOfMultipleHeadersIsPreservedOnRequests("Content-Encoding", RoutedHttpRequest.adapt(post, route)); } @Test public void testOrderOfMultipleContentLanguageHeadersIsPreservedOnRequests() throws Exception { - final BasicHttpRequest post = new BasicHttpRequest("POST", "/", - HttpVersion.HTTP_1_1); + final BasicClassicHttpRequest post = new BasicClassicHttpRequest("POST", "/"); post.setEntity(body); post.addHeader("Content-Language", "mi"); post.addHeader("Content-Language", "en"); post.addHeader("Content-Length", "128"); - testOrderOfMultipleHeadersIsPreservedOnRequests("Content-Language", HttpRequestWrapper.wrap(post, host)); + testOrderOfMultipleHeadersIsPreservedOnRequests("Content-Language", RoutedHttpRequest.adapt(post, route)); } @Test public void testOrderOfMultipleExpectHeadersIsPreservedOnRequests() throws Exception { - final BasicHttpRequest post = new BasicHttpRequest("POST", "/", - HttpVersion.HTTP_1_1); + final BasicClassicHttpRequest post = new BasicClassicHttpRequest("POST", "/"); post.setEntity(body); post.addHeader("Expect", "100-continue"); post.addHeader("Expect", "x-expect=true"); post.addHeader("Content-Length", "128"); - testOrderOfMultipleHeadersIsPreservedOnRequests("Expect", HttpRequestWrapper.wrap(post, host)); + testOrderOfMultipleHeadersIsPreservedOnRequests("Expect", RoutedHttpRequest.adapt(post, route)); } @Test @@ -427,13 +423,12 @@ public class TestProtocolRequirements extends AbstractProtocolTest { private void testOrderOfMultipleHeadersIsPreservedOnResponses(final String h) throws Exception { EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); @@ -445,8 +440,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testOrderOfMultipleAllowHeadersIsPreservedOnResponses() throws Exception { - originResponse = Proxies.enhanceResponse( - new BasicHttpResponse(HttpVersion.HTTP_1_1, 405, "Method Not Allowed")); + originResponse = new BasicClassicHttpResponse(405, "Method Not Allowed"); originResponse.addHeader("Allow", "HEAD"); originResponse.addHeader("Allow", "DELETE"); testOrderOfMultipleHeadersIsPreservedOnResponses("Allow"); @@ -506,8 +500,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { emptyMockCacheExpectsNoPuts(); - originResponse = Proxies.enhanceResponse( - new BasicHttpResponse(HttpVersion.HTTP_1_1, code, "Moo")); + originResponse = new BasicClassicHttpResponse(code, "Moo"); originResponse.setHeader("Date", DateUtils.formatDate(new Date())); originResponse.setHeader("Server", "MockOrigin/1.0"); originResponse.setHeader("Cache-Control", "max-age=3600"); @@ -515,14 +508,13 @@ public class TestProtocolRequirements extends AbstractProtocolTest { EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - impl.execute(route, request, context, null); + impl.execute(request, context, null); // in particular, there were no storage calls on the cache verifyMocks(); @@ -556,20 +548,19 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testUnknownHeadersOnRequestsAreForwarded() throws Exception { request.addHeader("X-Unknown-Header", "blahblah"); - final Capture reqCap = new Capture<>(); + final Capture reqCap = new Capture<>(); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), EasyMock.capture(reqCap), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - impl.execute(route, request, context, null); + impl.execute(request, context, null); verifyMocks(); - final HttpRequest forwarded = reqCap.getValue(); + final ClassicHttpRequest forwarded = reqCap.getValue(); final Header[] hdrs = forwarded.getHeaders("X-Unknown-Header"); Assert.assertEquals(1, hdrs.length); Assert.assertEquals("blahblah", hdrs[0].getValue()); @@ -580,14 +571,13 @@ public class TestProtocolRequirements extends AbstractProtocolTest { originResponse.addHeader("X-Unknown-Header", "blahblah"); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); final Header[] hdrs = result.getHeaders("X-Unknown-Header"); @@ -604,35 +594,33 @@ public class TestProtocolRequirements extends AbstractProtocolTest { */ @Test public void testRequestsExpecting100ContinueBehaviorShouldSetExpectHeader() throws Exception { - final BasicHttpRequest post = new BasicHttpRequest( - "POST", "/", HttpVersion.HTTP_1_1); + final BasicClassicHttpRequest post = new BasicClassicHttpRequest("POST", "/"); post.setHeader(HttpHeaders.EXPECT, HeaderElements.CONTINUE); post.setHeader("Content-Length", "128"); post.setEntity(new BasicHttpEntity()); - final Capture reqCap = new Capture<>(); + final Capture reqCap = new Capture<>(); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), EasyMock.capture(reqCap), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - impl.execute(route, HttpRequestWrapper.wrap(post, host), context, null); + impl.execute(RoutedHttpRequest.adapt(post, route), context, null); verifyMocks(); - final HttpRequestWrapper forwarded = reqCap.getValue(); + final RoutedHttpRequest forwarded = reqCap.getValue(); boolean foundExpect = false; - for (final Header h : forwarded.getHeaders("Expect")) { - for (final HeaderElement elt : h.getElements()) { - if ("100-continue".equalsIgnoreCase(elt.getName())) { - foundExpect = true; - break; - } + final Iterator it = MessageSupport.iterate(forwarded, HttpHeaders.EXPECT); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + if ("100-continue".equalsIgnoreCase(elt.getName())) { + foundExpect = true; + break; } } Assert.assertTrue(foundExpect); @@ -648,34 +636,32 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testRequestsNotExpecting100ContinueBehaviorShouldNotSetExpectContinueHeader() throws Exception { - final BasicHttpRequest post = new BasicHttpRequest( - "POST", "/", HttpVersion.HTTP_1_1); + final BasicClassicHttpRequest post = new BasicClassicHttpRequest("POST", "/"); post.setHeader("Content-Length", "128"); post.setEntity(new BasicHttpEntity()); - final Capture reqCap = new Capture<>(); + final Capture reqCap = new Capture<>(); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), EasyMock.capture(reqCap), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - impl.execute(route, HttpRequestWrapper.wrap(post, host), context, null); + impl.execute(RoutedHttpRequest.adapt(post, route), context, null); verifyMocks(); - final HttpRequestWrapper forwarded = reqCap.getValue(); + final RoutedHttpRequest forwarded = reqCap.getValue(); boolean foundExpect = false; - for (final Header h : forwarded.getHeaders("Expect")) { - for (final HeaderElement elt : h.getElements()) { - if ("100-continue".equalsIgnoreCase(elt.getName())) { - foundExpect = true; - break; - } + final Iterator it = MessageSupport.iterate(forwarded, HttpHeaders.EXPECT); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + if ("100-continue".equalsIgnoreCase(elt.getName())) { + foundExpect = true; + break; } } Assert.assertFalse(foundExpect); @@ -691,26 +677,25 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testExpect100ContinueIsNotSentIfThereIsNoRequestBody() throws Exception { request.addHeader("Expect", "100-continue"); - final Capture reqCap = new Capture<>(); + final Capture reqCap = new Capture<>(); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), EasyMock.capture(reqCap), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - impl.execute(route, request, context, null); + impl.execute(request, context, null); verifyMocks(); - final HttpRequest forwarded = reqCap.getValue(); + final ClassicHttpRequest forwarded = reqCap.getValue(); boolean foundExpectContinue = false; - for (final Header h : forwarded.getHeaders("Expect")) { - for (final HeaderElement elt : h.getElements()) { - if ("100-continue".equalsIgnoreCase(elt.getName())) { - foundExpectContinue = true; - break; - } + final Iterator it = MessageSupport.iterate(forwarded, HttpHeaders.EXPECT); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + if ("100-continue".equalsIgnoreCase(elt.getName())) { + foundExpectContinue = true; + break; } } Assert.assertFalse(foundExpectContinue); @@ -749,17 +734,15 @@ public class TestProtocolRequirements extends AbstractProtocolTest { public void test100ContinueResponsesAreNotForwardedTo1_0ClientsWhoDidNotAskForThem() throws Exception { - final BasicHttpRequest post = new BasicHttpRequest("POST", "/", - new ProtocolVersion("HTTP", 1, 0)); + final BasicClassicHttpRequest post = new BasicClassicHttpRequest("POST", "/"); + post.setVersion(new ProtocolVersion("HTTP", 1, 0)); post.setEntity(body); post.setHeader("Content-Length", "128"); - originResponse = Proxies.enhanceResponse( - new BasicHttpResponse(HttpVersion.HTTP_1_1, 100, "Continue")); + originResponse = new BasicClassicHttpResponse(100, "Continue"); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); @@ -767,7 +750,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { try { // if a 100 response gets up to us from the HttpClient // backend, we can't really handle it at that point - impl.execute(route, HttpRequestWrapper.wrap(post, host), context, null); + impl.execute(RoutedHttpRequest.adapt(post, route), context, null); Assert.fail("should have thrown an exception"); } catch (final ClientProtocolException expected) { } @@ -783,19 +766,18 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testResponsesToOPTIONSAreNotCacheable() throws Exception { emptyMockCacheExpectsNoPuts(); - request = HttpRequestWrapper.wrap(new BasicHttpRequest("OPTIONS", "/", HttpVersion.HTTP_1_1), host); + request = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("OPTIONS", "/"), route); originResponse.addHeader("Cache-Control", "max-age=3600"); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - impl.execute(route, request, context, null); + impl.execute(request, context, null); verifyMocks(); } @@ -809,19 +791,18 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void test200ResponseToOPTIONSWithNoBodyShouldIncludeContentLengthZero() throws Exception { - request = HttpRequestWrapper.wrap(new BasicHttpRequest("OPTIONS", "/", HttpVersion.HTTP_1_1), host); + request = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("OPTIONS", "/"), route); originResponse.setEntity(null); originResponse.setHeader("Content-Length", "0"); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); final Header contentLength = result.getFirstHeader("Content-Length"); @@ -841,11 +822,11 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testDoesNotForwardOPTIONSWhenMaxForwardsIsZeroOnAbsoluteURIRequest() throws Exception { - request = HttpRequestWrapper.wrap(new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1), host); + request = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("OPTIONS", "*"), route); request.setHeader("Max-Forwards", "0"); replayMocks(); - impl.execute(route, request, context, null); + impl.execute(request, context, null); verifyMocks(); } @@ -858,23 +839,22 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testDecrementsMaxForwardsWhenForwardingOPTIONSRequest() throws Exception { - request = HttpRequestWrapper.wrap(new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1), host); + request = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("OPTIONS", "*"), route); request.setHeader("Max-Forwards", "7"); - final Capture cap = new Capture<>(); + final Capture cap = new Capture<>(); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), EasyMock.capture(cap), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - impl.execute(route, request, context, null); + impl.execute(request, context, null); verifyMocks(); - final HttpRequest captured = cap.getValue(); + final ClassicHttpRequest captured = cap.getValue(); Assert.assertEquals("6", captured.getFirstHeader("Max-Forwards").getValue()); } @@ -886,20 +866,19 @@ public class TestProtocolRequirements extends AbstractProtocolTest { */ @Test public void testDoesNotAddAMaxForwardsHeaderToForwardedOPTIONSRequests() throws Exception { - request = HttpRequestWrapper.wrap(new BasicHttpRequest("OPTIONS", "/", HttpVersion.HTTP_1_1), host); - final Capture reqCap = new Capture<>(); + request = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("OPTIONS", "/"), route); + final Capture reqCap = new Capture<>(); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), EasyMock.capture(reqCap), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - impl.execute(route, request, context, null); + impl.execute(request, context, null); verifyMocks(); - final HttpRequest forwarded = reqCap.getValue(); + final ClassicHttpRequest forwarded = reqCap.getValue(); Assert.assertNull(forwarded.getFirstHeader("Max-Forwards")); } @@ -911,17 +890,16 @@ public class TestProtocolRequirements extends AbstractProtocolTest { */ @Test public void testResponseToAHEADRequestMustNotHaveABody() throws Exception { - request = HttpRequestWrapper.wrap(new BasicHttpRequest("HEAD", "/", HttpVersion.HTTP_1_1), host); + request = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("HEAD", "/"), route); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); @@ -940,52 +918,48 @@ public class TestProtocolRequirements extends AbstractProtocolTest { final String oldVal, final String newVal) throws Exception { // put something cacheable in the cache - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.addHeader("Cache-Control", "max-age=3600"); resp1.setHeader(eHeader, oldVal); // get a head that penetrates the cache - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("HEAD", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("HEAD", "/"), route); req2.addHeader("Cache-Control", "no-cache"); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); resp2.setEntity(null); resp2.setHeader(eHeader, newVal); // next request doesn't tolerate stale entry - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req3.addHeader("Cache-Control", "max-stale=0"); - final HttpResponse resp3 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp3 = HttpTestUtils.make200Response(); resp3.setHeader(eHeader, newVal); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), eqRequest(req1), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), eqRequest(req2), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp3)); + EasyMock.isNull())).andReturn(resp3); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); - impl.execute(route, req3, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); + impl.execute(req3, context, null); verifyMocks(); } @@ -1028,8 +1002,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { public void testResponsesToPOSTWithoutCacheControlOrExpiresAreNotCached() throws Exception { emptyMockCacheExpectsNoPuts(); - final BasicHttpRequest post = new BasicHttpRequest("POST", "/", - HttpVersion.HTTP_1_1); + final BasicClassicHttpRequest post = new BasicClassicHttpRequest("POST", "/"); post.setHeader("Content-Length", "128"); post.setEntity(HttpTestUtils.makeBody(128)); @@ -1038,14 +1011,13 @@ public class TestProtocolRequirements extends AbstractProtocolTest { EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - impl.execute(route, HttpRequestWrapper.wrap(post, host), context, null); + impl.execute(RoutedHttpRequest.adapt(post, route), context, null); verifyMocks(); } @@ -1059,8 +1031,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { public void testResponsesToPUTsAreNotCached() throws Exception { emptyMockCacheExpectsNoPuts(); - final BasicHttpRequest put = new BasicHttpRequest("PUT", "/", - HttpVersion.HTTP_1_1); + final BasicClassicHttpRequest put = new BasicClassicHttpRequest("PUT", "/"); put.setEntity(HttpTestUtils.makeBody(128)); put.addHeader("Content-Length", "128"); @@ -1068,14 +1039,13 @@ public class TestProtocolRequirements extends AbstractProtocolTest { EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - impl.execute(route, HttpRequestWrapper.wrap(put, host), context, null); + impl.execute(RoutedHttpRequest.adapt(put, route), context, null); verifyMocks(); } @@ -1089,19 +1059,18 @@ public class TestProtocolRequirements extends AbstractProtocolTest { public void testResponsesToDELETEsAreNotCached() throws Exception { emptyMockCacheExpectsNoPuts(); - request = HttpRequestWrapper.wrap(new BasicHttpRequest("DELETE", "/", HttpVersion.HTTP_1_1), host); + request = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("DELETE", "/"), route); originResponse.setHeader("Cache-Control", "max-age=3600"); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - impl.execute(route, request, context, null); + impl.execute(request, context, null); verifyMocks(); } @@ -1113,25 +1082,23 @@ public class TestProtocolRequirements extends AbstractProtocolTest { */ @Test public void testForwardedTRACERequestsDoNotIncludeAnEntity() throws Exception { - final BasicHttpRequest trace = new BasicHttpRequest("TRACE", "/", - HttpVersion.HTTP_1_1); + final BasicClassicHttpRequest trace = new BasicClassicHttpRequest("TRACE", "/"); trace.setEntity(HttpTestUtils.makeBody(entityLength)); trace.setHeader("Content-Length", Integer.toString(entityLength)); - final Capture reqCap = new Capture<>(); + final Capture reqCap = new Capture<>(); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), EasyMock.capture(reqCap), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - impl.execute(route, HttpRequestWrapper.wrap(trace, host), context, null); + impl.execute(RoutedHttpRequest.adapt(trace, route), context, null); verifyMocks(); - final HttpRequest bodyReq = reqCap.getValue(); + final ClassicHttpRequest bodyReq = reqCap.getValue(); Assert.assertTrue(bodyReq.getEntity() == null || bodyReq.getEntity().getContentLength() == 0); } @@ -1144,19 +1111,18 @@ public class TestProtocolRequirements extends AbstractProtocolTest { public void testResponsesToTRACEsAreNotCached() throws Exception { emptyMockCacheExpectsNoPuts(); - request = HttpRequestWrapper.wrap(new BasicHttpRequest("TRACE", "/", HttpVersion.HTTP_1_1), host); + request = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("TRACE", "/"), route); originResponse.setHeader("Cache-Control", "max-age=3600"); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - impl.execute(route, request, context, null); + impl.execute(request, context, null); verifyMocks(); } @@ -1169,20 +1135,18 @@ public class TestProtocolRequirements extends AbstractProtocolTest { */ @Test public void test204ResponsesDoNotContainMessageBodies() throws Exception { - originResponse = Proxies.enhanceResponse( - new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NO_CONTENT, "No Content")); + originResponse = new BasicClassicHttpResponse(HttpStatus.SC_NO_CONTENT, "No Content"); originResponse.setEntity(HttpTestUtils.makeBody(entityLength)); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); @@ -1196,20 +1160,18 @@ public class TestProtocolRequirements extends AbstractProtocolTest { */ @Test public void test205ResponsesDoNotContainMessageBodies() throws Exception { - originResponse = Proxies.enhanceResponse( - new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_RESET_CONTENT, "Reset Content")); + originResponse = new BasicClassicHttpResponse(HttpStatus.SC_RESET_CONTENT, "Reset Content"); originResponse.setEntity(HttpTestUtils.makeBody(entityLength)); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); @@ -1239,26 +1201,26 @@ public class TestProtocolRequirements extends AbstractProtocolTest { public void test206ResponseGeneratedFromCacheMustHaveContentRangeOrMultipartByteRangesContentType() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("ETag", "\"etag\""); resp1.setHeader("Cache-Control", "max-age=3600"); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("Range", "bytes=0-50"); backendExpectsAnyRequestAndReturn(resp1).times(1, 2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - if (HttpStatus.SC_PARTIAL_CONTENT == result.getStatusLine().getStatusCode()) { + if (HttpStatus.SC_PARTIAL_CONTENT == result.getCode()) { if (result.getFirstHeader("Content-Range") == null) { - final HeaderElement elt = result.getFirstHeader("Content-Type").getElements()[0]; + final HeaderElement elt = MessageSupport.parse(result.getFirstHeader("Content-Type"))[0]; Assert.assertTrue("multipart/byteranges".equalsIgnoreCase(elt.getName())); Assert.assertNotNull(elt.getParameterByName("boundary")); Assert.assertNotNull(elt.getParameterByName("boundary").getValue()); @@ -1271,24 +1233,24 @@ public class TestProtocolRequirements extends AbstractProtocolTest { public void test206ResponseGeneratedFromCacheMustHaveABodyThatMatchesContentLengthHeaderIfPresent() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("ETag", "\"etag\""); resp1.setHeader("Cache-Control", "max-age=3600"); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("Range", "bytes=0-50"); backendExpectsAnyRequestAndReturn(resp1).times(1, 2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - if (HttpStatus.SC_PARTIAL_CONTENT == result.getStatusLine().getStatusCode()) { + if (HttpStatus.SC_PARTIAL_CONTENT == result.getCode()) { final Header h = result.getFirstHeader("Content-Length"); if (h != null) { final int contentLength = Integer.parseInt(h.getValue()); @@ -1305,24 +1267,24 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void test206ResponseGeneratedFromCacheMustHaveDateHeader() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("ETag", "\"etag\""); resp1.setHeader("Cache-Control", "max-age=3600"); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("Range", "bytes=0-50"); backendExpectsAnyRequestAndReturn(resp1).times(1, 2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - if (HttpStatus.SC_PARTIAL_CONTENT == result.getStatusLine().getStatusCode()) { + if (HttpStatus.SC_PARTIAL_CONTENT == result.getCode()) { Assert.assertNotNull(result.getFirstHeader("Date")); } } @@ -1330,8 +1292,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void test206ResponseReturnedToClientMustHaveDateHeader() throws Exception { request.addHeader("Range", "bytes=0-50"); - originResponse = Proxies.enhanceResponse( - new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_PARTIAL_CONTENT, "Partial Content")); + originResponse = new BasicClassicHttpResponse(HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); originResponse.setHeader("Date", DateUtils.formatDate(new Date())); originResponse.setHeader("Server", "MockOrigin/1.0"); originResponse.setEntity(HttpTestUtils.makeBody(500)); @@ -1340,15 +1301,14 @@ public class TestProtocolRequirements extends AbstractProtocolTest { EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); - Assert.assertTrue(result.getStatusLine().getStatusCode() != HttpStatus.SC_PARTIAL_CONTENT + final ClassicHttpResponse result = impl.execute(request, context, null); + Assert.assertTrue(result.getCode() != HttpStatus.SC_PARTIAL_CONTENT || result.getFirstHeader("Date") != null); verifyMocks(); @@ -1356,52 +1316,52 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void test206ContainsETagIfA200ResponseWouldHaveIncludedIt() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); originResponse.addHeader("Cache-Control", "max-age=3600"); originResponse.addHeader("ETag", "\"etag1\""); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.addHeader("Range", "bytes=0-50"); backendExpectsAnyRequest().andReturn(originResponse).times(1, 2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - if (result.getStatusLine().getStatusCode() == HttpStatus.SC_PARTIAL_CONTENT) { + if (result.getCode() == HttpStatus.SC_PARTIAL_CONTENT) { Assert.assertNotNull(result.getFirstHeader("ETag")); } } @Test public void test206ContainsContentLocationIfA200ResponseWouldHaveIncludedIt() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); originResponse.addHeader("Cache-Control", "max-age=3600"); originResponse.addHeader("Content-Location", "http://foo.example.com/other/url"); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.addHeader("Range", "bytes=0-50"); backendExpectsAnyRequest().andReturn(originResponse).times(1, 2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - if (result.getStatusLine().getStatusCode() == HttpStatus.SC_PARTIAL_CONTENT) { + if (result.getCode() == HttpStatus.SC_PARTIAL_CONTENT) { Assert.assertNotNull(result.getFirstHeader("Content-Location")); } } @@ -1409,8 +1369,8 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void test206ResponseIncludesVariantHeadersIfValueMightDiffer() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req1.addHeader("Accept-Encoding", "gzip"); final Date now = new Date(); @@ -1419,21 +1379,21 @@ public class TestProtocolRequirements extends AbstractProtocolTest { originResponse.addHeader("Expires", DateUtils.formatDate(inOneHour)); originResponse.addHeader("Vary", "Accept-Encoding"); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.addHeader("Cache-Control", "no-cache"); req2.addHeader("Accept-Encoding", "gzip"); final Date nextSecond = new Date(now.getTime() + 1000L); final Date inTwoHoursPlusASec = new Date(now.getTime() + 2 * 3600 * 1000L + 1000L); - final HttpResponse originResponse2 = HttpTestUtils.make200Response(); + final ClassicHttpResponse originResponse2 = HttpTestUtils.make200Response(); originResponse2.setHeader("Date", DateUtils.formatDate(nextSecond)); originResponse2.setHeader("Cache-Control", "max-age=7200"); originResponse2.setHeader("Expires", DateUtils.formatDate(inTwoHoursPlusASec)); originResponse2.setHeader("Vary", "Accept-Encoding"); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req3.addHeader("Range", "bytes=0-50"); req3.addHeader("Accept-Encoding", "gzip"); @@ -1442,13 +1402,13 @@ public class TestProtocolRequirements extends AbstractProtocolTest { replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); - final HttpResponse result = impl.execute(route, req3, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); + final ClassicHttpResponse result = impl.execute(req3, context, null); verifyMocks(); - if (result.getStatusLine().getStatusCode() == HttpStatus.SC_PARTIAL_CONTENT) { + if (result.getCode() == HttpStatus.SC_PARTIAL_CONTENT) { Assert.assertNotNull(result.getFirstHeader("Expires")); Assert.assertNotNull(result.getFirstHeader("Cache-Control")); Assert.assertNotNull(result.getFirstHeader("Vary")); @@ -1467,12 +1427,12 @@ public class TestProtocolRequirements extends AbstractProtocolTest { public void test206ResponseToConditionalRangeRequestDoesNotIncludeOtherEntityHeaders() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); final Date now = new Date(); final Date oneHourAgo = new Date(now.getTime() - 3600 * 1000L); - originResponse = Proxies.enhanceResponse(HttpTestUtils.make200Response()); + originResponse = HttpTestUtils.make200Response(); originResponse.addHeader("Allow", "GET,HEAD"); originResponse.addHeader("Cache-Control", "max-age=3600"); originResponse.addHeader("Content-Language", "en"); @@ -1483,8 +1443,8 @@ public class TestProtocolRequirements extends AbstractProtocolTest { originResponse.addHeader("Last-Modified", DateUtils.formatDate(oneHourAgo)); originResponse.addHeader("ETag", "W/\"weak-tag\""); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.addHeader("If-Range", "W/\"weak-tag\""); req2.addHeader("Range", "bytes=0-50"); @@ -1492,12 +1452,12 @@ public class TestProtocolRequirements extends AbstractProtocolTest { replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - if (result.getStatusLine().getStatusCode() == HttpStatus.SC_PARTIAL_CONTENT) { + if (result.getCode() == HttpStatus.SC_PARTIAL_CONTENT) { Assert.assertNull(result.getFirstHeader("Allow")); Assert.assertNull(result.getFirstHeader("Content-Encoding")); Assert.assertNull(result.getFirstHeader("Content-Language")); @@ -1517,8 +1477,8 @@ public class TestProtocolRequirements extends AbstractProtocolTest { public void test206ResponseToIfRangeWithStrongValidatorReturnsAllEntityHeaders() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); final Date now = new Date(); final Date oneHourAgo = new Date(now.getTime() - 3600 * 1000L); @@ -1532,8 +1492,8 @@ public class TestProtocolRequirements extends AbstractProtocolTest { originResponse.addHeader("Last-Modified", DateUtils.formatDate(oneHourAgo)); originResponse.addHeader("ETag", "\"strong-tag\""); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.addHeader("If-Range", "\"strong-tag\""); req2.addHeader("Range", "bytes=0-50"); @@ -1541,12 +1501,12 @@ public class TestProtocolRequirements extends AbstractProtocolTest { replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - if (result.getStatusLine().getStatusCode() == HttpStatus.SC_PARTIAL_CONTENT) { + if (result.getCode() == HttpStatus.SC_PARTIAL_CONTENT) { Assert.assertEquals("GET,HEAD", result.getFirstHeader("Allow").getValue()); Assert.assertEquals("max-age=3600", result.getFirstHeader("Cache-Control").getValue()); Assert.assertEquals("en", result.getFirstHeader("Content-Language").getValue()); @@ -1571,9 +1531,9 @@ public class TestProtocolRequirements extends AbstractProtocolTest { final Date now = new Date(); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Cache-Control", "max-age=3600"); resp1.setHeader("ETag", "\"etag1\""); final byte[] bytes1 = new byte[128]; @@ -1582,13 +1542,13 @@ public class TestProtocolRequirements extends AbstractProtocolTest { } resp1.setEntity(new ByteArrayEntity(bytes1)); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("Cache-Control", "no-cache"); req2.setHeader("Range", "bytes=0-50"); final Date inOneSecond = new Date(now.getTime() + 1000L); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_PARTIAL_CONTENT, + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); resp2.setHeader("Date", DateUtils.formatDate(inOneSecond)); resp2.setHeader("Server", resp1.getFirstHeader("Server").getValue()); @@ -1601,9 +1561,9 @@ public class TestProtocolRequirements extends AbstractProtocolTest { resp2.setEntity(new ByteArrayEntity(bytes2)); final Date inTwoSeconds = new Date(now.getTime() + 2000L); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp3 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp3 = HttpTestUtils.make200Response(); resp3.setHeader("Date", DateUtils.formatDate(inTwoSeconds)); resp3.setHeader("Cache-Control", "max-age=3600"); resp3.setHeader("ETag", "\"etag2\""); @@ -1615,30 +1575,24 @@ public class TestProtocolRequirements extends AbstractProtocolTest { EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp1)); + EasyMock.isNull())).andReturn(resp1); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp2)); + EasyMock.isNull())).andReturn(resp2); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp3)).times(0, 1); + EasyMock.isNull())).andReturn(resp3).times(0, 1); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); - final HttpResponse result = impl.execute(route, req3, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); + final ClassicHttpResponse result = impl.execute(req3, context, null); verifyMocks(); @@ -1664,9 +1618,9 @@ public class TestProtocolRequirements extends AbstractProtocolTest { final Date now = new Date(); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); final Date oneHourAgo = new Date(now.getTime() - 3600L); resp1.setHeader("Cache-Control", "max-age=3600"); resp1.setHeader("Last-Modified", DateUtils.formatDate(oneHourAgo)); @@ -1676,13 +1630,13 @@ public class TestProtocolRequirements extends AbstractProtocolTest { } resp1.setEntity(new ByteArrayEntity(bytes1)); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("Cache-Control", "no-cache"); req2.setHeader("Range", "bytes=0-50"); final Date inOneSecond = new Date(now.getTime() + 1000L); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_PARTIAL_CONTENT, + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); resp2.setHeader("Date", DateUtils.formatDate(inOneSecond)); resp2.setHeader("Server", resp1.getFirstHeader("Server").getValue()); @@ -1695,9 +1649,9 @@ public class TestProtocolRequirements extends AbstractProtocolTest { resp2.setEntity(new ByteArrayEntity(bytes2)); final Date inTwoSeconds = new Date(now.getTime() + 2000L); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp3 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp3 = HttpTestUtils.make200Response(); resp3.setHeader("Date", DateUtils.formatDate(inTwoSeconds)); resp3.setHeader("Cache-Control", "max-age=3600"); resp3.setHeader("ETag", "\"etag2\""); @@ -1709,30 +1663,24 @@ public class TestProtocolRequirements extends AbstractProtocolTest { EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp1)); + EasyMock.isNull())).andReturn(resp1); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp2)); + EasyMock.isNull())).andReturn(resp2); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp3)).times(0, 1); + EasyMock.isNull())).andReturn(resp3).times(0, 1); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); - final HttpResponse result = impl.execute(route, req3, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); + final ClassicHttpResponse result = impl.execute(req3, context, null); verifyMocks(); @@ -1765,13 +1713,11 @@ public class TestProtocolRequirements extends AbstractProtocolTest { if (!supportsRangeAndContentRangeHeaders(impl)) { emptyMockCacheExpectsNoPuts(); - request = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + request = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); request.addHeader("Range", "bytes=0-50"); - originResponse = Proxies.enhanceResponse( - new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_PARTIAL_CONTENT, - "Partial Content")); + originResponse = new BasicClassicHttpResponse(HttpStatus.SC_PARTIAL_CONTENT,"Partial Content"); originResponse.setHeader("Content-Range", "bytes 0-50/128"); originResponse.setHeader("Cache-Control", "max-age=3600"); final byte[] bytes = new byte[51]; @@ -1780,14 +1726,12 @@ public class TestProtocolRequirements extends AbstractProtocolTest { EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - originResponse); + EasyMock.isNull())).andReturn(originResponse); replayMocks(); - impl.execute(route, request, context, null); + impl.execute(request, context, null); verifyMocks(); } } @@ -1802,10 +1746,9 @@ public class TestProtocolRequirements extends AbstractProtocolTest { public void test303ResponsesAreNotCached() throws Exception { emptyMockCacheExpectsNoPuts(); - request = HttpRequestWrapper.wrap(new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + request = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("GET", "/"), route); - originResponse = Proxies.enhanceResponse( - new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_SEE_OTHER, "See Other")); + originResponse = new BasicClassicHttpResponse(HttpStatus.SC_SEE_OTHER, "See Other"); originResponse.setHeader("Date", DateUtils.formatDate(new Date())); originResponse.setHeader("Server", "MockServer/1.0"); originResponse.setHeader("Cache-Control", "max-age=3600"); @@ -1815,13 +1758,12 @@ public class TestProtocolRequirements extends AbstractProtocolTest { EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - impl.execute(route, request, context, null); + impl.execute(request, context, null); verifyMocks(); } @@ -1835,9 +1777,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { public void test304ResponseDoesNotContainABody() throws Exception { request.setHeader("If-None-Match", "\"etag\""); - originResponse = Proxies.enhanceResponse( - new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_MODIFIED, - "Not Modified")); + originResponse = new BasicClassicHttpResponse(HttpStatus.SC_NOT_MODIFIED,"Not Modified"); originResponse.setHeader("Date", DateUtils.formatDate(new Date())); originResponse.setHeader("Server", "MockServer/1.0"); originResponse.setHeader("Content-Length", "128"); @@ -1845,14 +1785,13 @@ public class TestProtocolRequirements extends AbstractProtocolTest { EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); @@ -1872,22 +1811,19 @@ public class TestProtocolRequirements extends AbstractProtocolTest { request.setHeader("If-None-Match", "\"etag\""); - originResponse = Proxies.enhanceResponse( - new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_MODIFIED, - "Not Modified")); + originResponse = new BasicClassicHttpResponse(HttpStatus.SC_NOT_MODIFIED,"Not Modified"); originResponse.setHeader("Date", DateUtils.formatDate(new Date())); originResponse.setHeader("Server", "MockServer/1.0"); originResponse.setHeader("ETag", "\"etag\""); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); Assert.assertNotNull(result.getFirstHeader("Date")); @@ -1896,28 +1832,27 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void test304ResponseGeneratedFromCacheIncludesDateHeader() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); originResponse.setHeader("Cache-Control", "max-age=3600"); originResponse.setHeader("ETag", "\"etag\""); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("If-None-Match", "\"etag\""); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse).times(1, 2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - if (result.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_MODIFIED) { + if (result.getCode() == HttpStatus.SC_NOT_MODIFIED) { Assert.assertNotNull(result.getFirstHeader("Date")); } } @@ -1931,28 +1866,27 @@ public class TestProtocolRequirements extends AbstractProtocolTest { */ @Test public void test304ResponseGeneratedFromCacheIncludesEtagIfOriginResponseDid() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); originResponse.setHeader("Cache-Control", "max-age=3600"); originResponse.setHeader("ETag", "\"etag\""); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("If-None-Match", "\"etag\""); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse).times(1, 2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - if (result.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_MODIFIED) { + if (result.getCode() == HttpStatus.SC_NOT_MODIFIED) { Assert.assertNotNull(result.getFirstHeader("ETag")); } } @@ -1960,29 +1894,28 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void test304ResponseGeneratedFromCacheIncludesContentLocationIfOriginResponseDid() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); originResponse.setHeader("Cache-Control", "max-age=3600"); originResponse.setHeader("Content-Location", "http://foo.example.com/other"); originResponse.setHeader("ETag", "\"etag\""); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("If-None-Match", "\"etag\""); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse).times(1, 2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - if (result.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_MODIFIED) { + if (result.getCode() == HttpStatus.SC_NOT_MODIFIED) { Assert.assertNotNull(result.getFirstHeader("Content-Location")); } } @@ -2001,57 +1934,53 @@ public class TestProtocolRequirements extends AbstractProtocolTest { final Date now = new Date(); final Date inTwoHours = new Date(now.getTime() + 2 * 3600 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req1.setHeader("Accept-Encoding", "gzip"); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("ETag", "\"v1\""); resp1.setHeader("Cache-Control", "max-age=7200"); resp1.setHeader("Expires", DateUtils.formatDate(inTwoHours)); resp1.setHeader("Vary", "Accept-Encoding"); resp1.setEntity(HttpTestUtils.makeBody(entityLength)); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req1.setHeader("Accept-Encoding", "gzip"); req1.setHeader("Cache-Control", "no-cache"); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); resp2.setHeader("ETag", "\"v2\""); resp2.setHeader("Cache-Control", "max-age=3600"); resp2.setHeader("Expires", DateUtils.formatDate(inTwoHours)); resp2.setHeader("Vary", "Accept-Encoding"); resp2.setEntity(HttpTestUtils.makeBody(entityLength)); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req3.setHeader("Accept-Encoding", "gzip"); req3.setHeader("If-None-Match", "\"v2\""); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp1)); + EasyMock.isNull())).andReturn(resp1); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp2)).times(1, 2); + EasyMock.isNull())).andReturn(resp2).times(1, 2); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); - final HttpResponse result = impl.execute(route, req3, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); + final ClassicHttpResponse result = impl.execute(req3, context, null); verifyMocks(); - if (result.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_MODIFIED) { + if (result.getCode() == HttpStatus.SC_NOT_MODIFIED) { Assert.assertNotNull(result.getFirstHeader("Expires")); Assert.assertNotNull(result.getFirstHeader("Cache-Control")); Assert.assertNotNull(result.getFirstHeader("Vary")); @@ -2072,10 +2001,10 @@ public class TestProtocolRequirements extends AbstractProtocolTest { final Date now = new Date(); final Date oneHourAgo = new Date(now.getTime() - 3600 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("ETag", "W/\"v1\""); resp1.setHeader("Allow", "GET,HEAD"); resp1.setHeader("Content-Encoding", "x-coding"); @@ -2086,25 +2015,23 @@ public class TestProtocolRequirements extends AbstractProtocolTest { resp1.setHeader("Last-Modified", DateUtils.formatDate(oneHourAgo)); resp1.setHeader("Cache-Control", "max-age=7200"); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("If-None-Match", "W/\"v1\""); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp1)).times(1, 2); + EasyMock.isNull())).andReturn(resp1).times(1, 2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - if (result.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_MODIFIED) { + if (result.getCode() == HttpStatus.SC_NOT_MODIFIED) { Assert.assertNull(result.getFirstHeader("Allow")); Assert.assertNull(result.getFirstHeader("Content-Encoding")); Assert.assertNull(result.getFirstHeader("Content-Length")); @@ -2128,64 +2055,58 @@ public class TestProtocolRequirements extends AbstractProtocolTest { final Date now = new Date(); // load cache with cacheable entry - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("ETag", "\"etag1\""); resp1.setHeader("Cache-Control", "max-age=3600"); // force a revalidation - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("Cache-Control", "max-age=0,max-stale=0"); // updated ETag provided to a conditional revalidation - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_MODIFIED, + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_NOT_MODIFIED, "Not Modified"); resp2.setHeader("Date", DateUtils.formatDate(now)); resp2.setHeader("Server", "MockServer/1.0"); resp2.setHeader("ETag", "\"etag2\""); // conditional validation uses If-None-Match - final HttpRequestWrapper conditionalValidation = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest conditionalValidation = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); conditionalValidation.setHeader("If-None-Match", "\"etag1\""); // unconditional validation doesn't use If-None-Match - final HttpRequestWrapper unconditionalValidation = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest unconditionalValidation = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); // new response to unconditional validation provides new body - final HttpResponse resp3 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp3 = HttpTestUtils.make200Response(); resp1.setHeader("ETag", "\"etag2\""); resp1.setHeader("Cache-Control", "max-age=3600"); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp1)); + EasyMock.isNull())).andReturn(resp1); // this next one will happen once if the cache tries to // conditionally validate, zero if it goes full revalidation EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), eqRequest(conditionalValidation), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp2)).times(0, 1); + EasyMock.isNull())).andReturn(resp2).times(0, 1); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), eqRequest(unconditionalValidation), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp3)); + EasyMock.isNull())).andReturn(resp3); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); verifyMocks(); } @@ -2203,66 +2124,59 @@ public class TestProtocolRequirements extends AbstractProtocolTest { final Date now = new Date(); final Date inFiveSeconds = new Date(now.getTime() + 5000L); - final HttpRequestWrapper initialRequest = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest initialRequest = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); - final HttpResponse cachedResponse = HttpTestUtils.make200Response(); + final ClassicHttpResponse cachedResponse = HttpTestUtils.make200Response(); cachedResponse.setHeader("Cache-Control", "max-age=3600"); cachedResponse.setHeader("ETag", "\"etag\""); - final HttpRequestWrapper secondRequest = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest secondRequest = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); secondRequest.setHeader("Cache-Control", "max-age=0,max-stale=0"); - final HttpRequestWrapper conditionalValidationRequest = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest conditionalValidationRequest = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); conditionalValidationRequest.setHeader("If-None-Match", "\"etag\""); - final HttpRequestWrapper unconditionalValidationRequest = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest unconditionalValidationRequest = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); // to be used if the cache generates a conditional validation - final HttpResponse conditionalResponse = new BasicHttpResponse( - HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_MODIFIED, "Not Modified"); + final ClassicHttpResponse conditionalResponse = HttpTestUtils.make304Response(); conditionalResponse.setHeader("Date", DateUtils.formatDate(inFiveSeconds)); conditionalResponse.setHeader("Server", "MockUtils/1.0"); conditionalResponse.setHeader("ETag", "\"etag\""); conditionalResponse.setHeader("X-Extra", "junk"); // to be used if the cache generates an unconditional validation - final HttpResponse unconditionalResponse = HttpTestUtils.make200Response(); + final ClassicHttpResponse unconditionalResponse = HttpTestUtils.make200Response(); unconditionalResponse.setHeader("Date", DateUtils.formatDate(inFiveSeconds)); unconditionalResponse.setHeader("ETag", "\"etag\""); - final Capture cap1 = new Capture<>(); - final Capture cap2 = new Capture<>(); + final Capture cap1 = new Capture<>(); + final Capture cap2 = new Capture<>(); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(cachedResponse)); + EasyMock.isNull())).andReturn(cachedResponse); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), EasyMock.and(eqRequest(conditionalValidationRequest), EasyMock.capture(cap1)), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(conditionalResponse)).times(0, 1); + EasyMock.isNull())).andReturn(conditionalResponse).times(0, 1); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), EasyMock.and(eqRequest(unconditionalValidationRequest), EasyMock.capture(cap2)), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(unconditionalResponse)).times(0, 1); + EasyMock.isNull())).andReturn(unconditionalResponse).times(0, 1); replayMocks(); - impl.execute(route, initialRequest, context, null); - final HttpResponse result = impl.execute(route, secondRequest, context, null); + impl.execute(initialRequest, context, null); + final ClassicHttpResponse result = impl.execute(secondRequest, context, null); verifyMocks(); @@ -2285,20 +2199,18 @@ public class TestProtocolRequirements extends AbstractProtocolTest { */ @Test public void testMustIncludeWWWAuthenticateHeaderOnAnOrigin401Response() throws Exception { - originResponse = Proxies.enhanceResponse( - new BasicHttpResponse(HttpVersion.HTTP_1_1, 401, "Unauthorized")); + originResponse = new BasicClassicHttpResponse(401, "Unauthorized"); originResponse.setHeader("WWW-Authenticate", "x-scheme x-param"); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); - if (result.getStatusLine().getStatusCode() == 401) { + final ClassicHttpResponse result = impl.execute(request, context, null); + if (result.getCode() == 401) { Assert.assertNotNull(result.getFirstHeader("WWW-Authenticate")); } @@ -2313,16 +2225,15 @@ public class TestProtocolRequirements extends AbstractProtocolTest { */ @Test public void testMustIncludeAllowHeaderFromAnOrigin405Response() throws Exception { - originResponse = Proxies.enhanceResponse( - new BasicHttpResponse(HttpVersion.HTTP_1_1, 405, "Method Not Allowed")); + originResponse = new BasicClassicHttpResponse(405, "Method Not Allowed"); originResponse.setHeader("Allow", "GET, HEAD"); backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); - if (result.getStatusLine().getStatusCode() == 405) { + final ClassicHttpResponse result = impl.execute(request, context, null); + if (result.getCode() == 405) { Assert.assertNotNull(result.getFirstHeader("Allow")); } @@ -2338,20 +2249,18 @@ public class TestProtocolRequirements extends AbstractProtocolTest { */ @Test public void testMustIncludeProxyAuthenticateHeaderFromAnOrigin407Response() throws Exception { - originResponse = Proxies.enhanceResponse( - new BasicHttpResponse(HttpVersion.HTTP_1_1, 407, "Proxy Authentication Required")); + originResponse = new BasicClassicHttpResponse(407, "Proxy Authentication Required"); originResponse.setHeader("Proxy-Authenticate", "x-scheme x-param"); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); - if (result.getStatusLine().getStatusCode() == 407) { + final ClassicHttpResponse result = impl.execute(request, context, null); + if (result.getCode() == 407) { Assert.assertNotNull(result.getFirstHeader("Proxy-Authenticate")); } @@ -2366,25 +2275,23 @@ public class TestProtocolRequirements extends AbstractProtocolTest { */ @Test public void testMustNotAddMultipartByteRangeContentTypeTo416Response() throws Exception { - originResponse = Proxies.enhanceResponse( - new BasicHttpResponse(HttpVersion.HTTP_1_1, 416, "Requested Range Not Satisfiable")); + originResponse = new BasicClassicHttpResponse(416, "Requested Range Not Satisfiable"); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); - if (result.getStatusLine().getStatusCode() == 416) { - for (final Header h : result.getHeaders("Content-Type")) { - for (final HeaderElement elt : h.getElements()) { - Assert.assertFalse("multipart/byteranges".equalsIgnoreCase(elt.getName())); - } + if (result.getCode() == 416) { + final Iterator it = MessageSupport.iterate(result, HttpHeaders.CONTENT_TYPE); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + Assert.assertFalse("multipart/byteranges".equalsIgnoreCase(elt.getName())); } } } @@ -2397,40 +2304,37 @@ public class TestProtocolRequirements extends AbstractProtocolTest { originResponse.setHeader("Content-Length", "128"); originResponse.setHeader("Cache-Control", "max-age=3600"); - final HttpRequestWrapper rangeReq = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest rangeReq = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); rangeReq.setHeader("Range", "bytes=1000-1200"); - final HttpResponse orig416 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 416, + final ClassicHttpResponse orig416 = new BasicClassicHttpResponse(416, "Requested Range Not Satisfiable"); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); // cache may 416 me right away if it understands byte ranges, // ok to delegate to origin though EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(orig416)).times(0, 1); + EasyMock.isNull())).andReturn(orig416).times(0, 1); replayMocks(); - impl.execute(route, request, context, null); - final HttpResponse result = impl.execute(route, rangeReq, context, null); + impl.execute(request, context, null); + final ClassicHttpResponse result = impl.execute(rangeReq, context, null); verifyMocks(); // might have gotten a 416 from the origin or the cache - if (result.getStatusLine().getStatusCode() == 416) { - for (final Header h : result.getHeaders("Content-Type")) { - for (final HeaderElement elt : h.getElements()) { - Assert.assertFalse("multipart/byteranges".equalsIgnoreCase(elt.getName())); - } + if (result.getCode() == 416) { + final Iterator it = MessageSupport.iterate(result, HttpHeaders.CONTENT_TYPE); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + Assert.assertFalse("multipart/byteranges".equalsIgnoreCase(elt.getName())); } } } @@ -2485,15 +2389,14 @@ public class TestProtocolRequirements extends AbstractProtocolTest { impl = new CachingExec(mockBackend, mockCache, config); - request = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/thing", HttpVersion.HTTP_1_1), host); + request = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/thing"), route); - final HttpRequestWrapper validate = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/thing", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest validate = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/thing"), route); validate.setHeader("If-None-Match", "\"etag\""); - final CloseableHttpResponse notModified = Proxies.enhanceResponse( - new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_MODIFIED, "Not Modified")); + final ClassicHttpResponse notModified = new BasicClassicHttpResponse(HttpStatus.SC_NOT_MODIFIED, "Not Modified"); notModified.setHeader("Date", DateUtils.formatDate(now)); notModified.setHeader("ETag", "\"etag\""); @@ -2504,7 +2407,6 @@ public class TestProtocolRequirements extends AbstractProtocolTest { .andReturn(entry); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), eqRequest(validate), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(notModified); @@ -2518,7 +2420,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { .andReturn(HttpTestUtils.makeCacheEntry()); replayMocks(); - impl.execute(route, request, context, null); + impl.execute(request, context, null); verifyMocks(); } @@ -2542,16 +2444,16 @@ public class TestProtocolRequirements extends AbstractProtocolTest { final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(tenSecondsAgo, eightSecondsAgo, hdrs, bytes); impl = new CachingExec(mockBackend, mockCache, config); - request = HttpRequestWrapper.wrap(new BasicHttpRequest("GET", "/thing", HttpVersion.HTTP_1_1), host); + request = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("GET", "/thing"), route); mockCache.flushInvalidatedCacheEntriesFor(EasyMock.eq(host), eqRequest(request)); EasyMock.expect(mockCache.getCacheEntry(EasyMock.eq(host), eqRequest(request))).andReturn(entry); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); - Assert.assertEquals(200, result.getStatusLine().getStatusCode()); + Assert.assertEquals(200, result.getCode()); } /* @@ -2590,25 +2492,24 @@ public class TestProtocolRequirements extends AbstractProtocolTest { final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(tenSecondsAgo, eightSecondsAgo, hdrs, bytes); impl = new CachingExec(mockBackend, mockCache, config); - request = HttpRequestWrapper.wrap(new BasicHttpRequest("GET", "/thing", HttpVersion.HTTP_1_1), host); + request = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("GET", "/thing"), route); mockCache.flushInvalidatedCacheEntriesFor(EasyMock.eq(host), eqRequest(request)); EasyMock.expect(mockCache.getCacheEntry(EasyMock.eq(host), eqRequest(request))).andReturn(entry); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andThrow( new IOException("can't talk to origin!")).anyTimes(); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); - final int status = result.getStatusLine().getStatusCode(); + final int status = result.getCode(); if (status == 200) { boolean foundWarning = false; for (final Header h : result.getHeaders("Warning")) { @@ -2645,21 +2546,21 @@ public class TestProtocolRequirements extends AbstractProtocolTest { final Date now = new Date(); final Date tenSecondsAgo = new Date(now.getTime() - 25 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Date", DateUtils.formatDate(tenSecondsAgo)); resp1.setHeader("ETag", "\"etag\""); resp1.setHeader("Cache-Control", "max-age=5"); resp1.setHeader("Warning", "110 squid \"stale stuff\""); resp1.setHeader("Via", "1.1 fred"); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("GET", "/"), route); - final HttpRequestWrapper validate = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest validate = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); validate.setHeader("If-None-Match", "\"etag\""); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_MODIFIED, + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_NOT_MODIFIED, "Not Modified"); resp2.setHeader("Date", DateUtils.formatDate(now)); resp2.setHeader("Server", "MockServer/1.0"); @@ -2669,37 +2570,35 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp1); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), eqRequest(validate), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp2)); + EasyMock.isNull())).andReturn(resp2); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap(new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("GET", "/"), route); replayMocks(); - final HttpResponse stale = impl.execute(route, req1, context, null); + final ClassicHttpResponse stale = impl.execute(req1, context, null); Assert.assertNotNull(stale.getFirstHeader("Warning")); - final HttpResponse result1 = impl.execute(route, req2, context, null); - final HttpResponse result2 = impl.execute(route, req3, context, null); + final ClassicHttpResponse result1 = impl.execute(req2, context, null); + final ClassicHttpResponse result2 = impl.execute(req3, context, null); verifyMocks(); boolean found1xxWarning = false; - for (final Header h : result1.getHeaders("Warning")) { - for (final HeaderElement elt : h.getElements()) { - if (elt.getName().startsWith("1")) { - found1xxWarning = true; - } + final Iterator it = MessageSupport.iterate(result1, HttpHeaders.WARNING); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + if (elt.getName().startsWith("1")) { + found1xxWarning = true; } } - for (final Header h : result2.getHeaders("Warning")) { - for (final HeaderElement elt : h.getElements()) { - if (elt.getName().startsWith("1")) { - found1xxWarning = true; - } + final Iterator it2 = MessageSupport.iterate(result2, HttpHeaders.WARNING); + while (it2.hasNext()) { + final HeaderElement elt = it2.next(); + if (elt.getName().startsWith("1")) { + found1xxWarning = true; } } Assert.assertFalse(found1xxWarning); @@ -2716,67 +2615,65 @@ public class TestProtocolRequirements extends AbstractProtocolTest { public void test2xxWarningsAreNotDeletedAfterSuccessfulRevalidation() throws Exception { final Date now = new Date(); final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Date", DateUtils.formatDate(tenSecondsAgo)); resp1.setHeader("ETag", "\"etag\""); resp1.setHeader("Cache-Control", "max-age=5"); resp1.setHeader("Via", "1.1 xproxy"); resp1.setHeader("Warning", "214 xproxy \"transformed stuff\""); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("GET", "/"), route); - final HttpRequestWrapper validate = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest validate = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); validate.setHeader("If-None-Match", "\"etag\""); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_MODIFIED, + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_NOT_MODIFIED, "Not Modified"); resp2.setHeader("Date", DateUtils.formatDate(now)); resp2.setHeader("Server", "MockServer/1.0"); resp2.setHeader("ETag", "\"etag\""); resp1.setHeader("Via", "1.1 xproxy"); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap(new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("GET", "/"), route); backendExpectsAnyRequestAndReturn(resp1); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), eqRequest(validate), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp2)); + EasyMock.isNull())).andReturn(resp2); replayMocks(); - final HttpResponse stale = impl.execute(route, req1, context, null); + final ClassicHttpResponse stale = impl.execute(req1, context, null); Assert.assertNotNull(stale.getFirstHeader("Warning")); - final HttpResponse result1 = impl.execute(route, req2, context, null); - final HttpResponse result2 = impl.execute(route, req3, context, null); + final ClassicHttpResponse result1 = impl.execute(req2, context, null); + final ClassicHttpResponse result2 = impl.execute(req3, context, null); verifyMocks(); boolean found214Warning = false; - for (final Header h : result1.getHeaders("Warning")) { - for (final HeaderElement elt : h.getElements()) { - final String[] parts = elt.getName().split(" "); - if ("214".equals(parts[0])) { - found214Warning = true; - } + final Iterator 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; } } Assert.assertTrue(found214Warning); found214Warning = false; - for (final Header h : result2.getHeaders("Warning")) { - for (final HeaderElement elt : h.getElements()) { - final String[] parts = elt.getName().split(" "); - if ("214".equals(parts[0])) { - found214Warning = true; - } + final Iterator 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; } } Assert.assertTrue(found214Warning); @@ -2809,16 +2706,16 @@ public class TestProtocolRequirements extends AbstractProtocolTest { final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(tenSecondsAgo, eightSecondsAgo, hdrs, bytes); impl = new CachingExec(mockBackend, mockCache, config); - request = HttpRequestWrapper.wrap(new BasicHttpRequest("GET", "/thing", HttpVersion.HTTP_1_1), host); + request = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("GET", "/thing"), route); mockCache.flushInvalidatedCacheEntriesFor(EasyMock.eq(host), eqRequest(request)); EasyMock.expect(mockCache.getCacheEntry(EasyMock.eq(host), eqRequest(request))).andReturn(entry); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); - Assert.assertEquals(200, result.getStatusLine().getStatusCode()); + Assert.assertEquals(200, result.getCode()); Assert.assertEquals("11", result.getFirstHeader("Age").getValue()); } @@ -2861,56 +2758,55 @@ public class TestProtocolRequirements extends AbstractProtocolTest { impl = new CachingExec(mockBackend, mockCache, config); - request = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/thing", HttpVersion.HTTP_1_1), host); + request = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/thing"), route); - final CloseableHttpResponse validated = Proxies.enhanceResponse(HttpTestUtils.make200Response()); + final ClassicHttpResponse validated = HttpTestUtils.make200Response(); validated.setHeader("Cache-Control", "public"); validated.setHeader("Last-Modified", DateUtils.formatDate(oneYearAgo)); validated.setHeader("Content-Length", "128"); validated.setEntity(new ByteArrayEntity(bytes)); - final CloseableHttpResponse reconstructed = Proxies.enhanceResponse(HttpTestUtils.make200Response()); + final ClassicHttpResponse reconstructed = HttpTestUtils.make200Response(); - final Capture cap = new Capture<>(); + final Capture cap = new Capture<>(); mockCache.flushInvalidatedCacheEntriesFor(EasyMock.eq(host), eqRequest(request)); mockCache.flushInvalidatedCacheEntriesFor( EasyMock.isA(HttpHost.class), - EasyMock.isA(HttpRequestWrapper.class), - EasyMock.isA(HttpResponse.class)); + EasyMock.isA(RoutedHttpRequest.class), + EasyMock.isA(ClassicHttpResponse.class)); EasyMock.expect(mockCache.getCacheEntry(EasyMock.eq(host), eqRequest(request))).andReturn(entry); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), EasyMock.capture(cap), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(validated).times(0, 1); EasyMock.expect(mockCache.getCacheEntry( EasyMock.isA(HttpHost.class), - EasyMock.isA(HttpRequestWrapper.class))).andReturn(entry).times(0, 1); + EasyMock.isA(RoutedHttpRequest.class))).andReturn(entry).times(0, 1); EasyMock.expect(mockCache.cacheAndReturnResponse( EasyMock.isA(HttpHost.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), eqCloseableResponse(validated), EasyMock.isA(Date.class), EasyMock.isA(Date.class))).andReturn(reconstructed).times(0, 1); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); - Assert.assertEquals(200, result.getStatusLine().getStatusCode()); + Assert.assertEquals(200, result.getCode()); if (!cap.hasCaptured()) { // heuristic cache hit boolean found113Warning = false; - for (final Header h : result.getHeaders("Warning")) { - for (final HeaderElement elt : h.getElements()) { - final String[] parts = elt.getName().split(" "); - if ("113".equals(parts[0])) { - found113Warning = true; - break; - } + final Iterator 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; } } Assert.assertTrue(found113Warning); @@ -2931,43 +2827,41 @@ public class TestProtocolRequirements extends AbstractProtocolTest { final Date inFiveSecond = new Date(now.getTime() + 5 * 1000L); // put an entry in the cache - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Date", DateUtils.formatDate(inFiveSecond)); resp1.setHeader("ETag", "\"etag1\""); resp1.setHeader("Cache-Control", "max-age=3600"); resp1.setHeader("Content-Length", "128"); // force another origin hit - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("Cache-Control", "no-cache"); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); resp2.setHeader("Date", DateUtils.formatDate(now)); // older resp2.setHeader("ETag", "\"etag2\""); resp2.setHeader("Cache-Control", "max-age=3600"); resp2.setHeader("Content-Length", "128"); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), eqRequest(req1), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp1)); + EasyMock.isNull())).andReturn(resp1); backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); - final HttpResponse result = impl.execute(route, req3, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); + final ClassicHttpResponse result = impl.execute(req3, context, null); verifyMocks(); Assert.assertEquals("\"etag1\"", result.getFirstHeader("ETag").getValue()); } @@ -2986,23 +2880,22 @@ public class TestProtocolRequirements extends AbstractProtocolTest { * for validation, but we can't tell if we receive a conditional request * from upstream. */ - private HttpResponse testRequestWithWeakETagValidatorIsNotAllowed(final String header) + private ClassicHttpResponse testRequestWithWeakETagValidatorIsNotAllowed(final String header) throws Exception { - final Capture cap = new Capture<>(); + final Capture cap = new Capture<>(); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), EasyMock.capture(cap), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse).times(0, 1); replayMocks(); - final HttpResponse response = impl.execute(route, request, context, null); + final ClassicHttpResponse response = impl.execute(request, context, null); verifyMocks(); // it's probably ok to return a 400 (Bad Request) to this client if (cap.hasCaptured()) { - final HttpRequest forwarded = cap.getValue(); + final ClassicHttpRequest forwarded = cap.getValue(); final Header h = forwarded.getFirstHeader(header); if (h != null) { Assert.assertFalse(h.getValue().startsWith("W/")); @@ -3014,40 +2907,40 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testSubrangeGETWithWeakETagIsNotAllowed() throws Exception { - request = HttpRequestWrapper.wrap(new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + request = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("GET", "/"), route); request.setHeader("Range", "bytes=0-500"); request.setHeader("If-Range", "W/\"etag\""); - final HttpResponse response = testRequestWithWeakETagValidatorIsNotAllowed("If-Range"); - Assert.assertTrue(response.getStatusLine().getStatusCode() == HttpStatus.SC_BAD_REQUEST); + final ClassicHttpResponse response = testRequestWithWeakETagValidatorIsNotAllowed("If-Range"); + Assert.assertTrue(response.getCode() == HttpStatus.SC_BAD_REQUEST); } @Test public void testPUTWithIfMatchWeakETagIsNotAllowed() throws Exception { - final HttpRequest put = new BasicHttpRequest("PUT", "/", HttpVersion.HTTP_1_1); + final ClassicHttpRequest put = new BasicClassicHttpRequest("PUT", "/"); put.setEntity(HttpTestUtils.makeBody(128)); put.setHeader("Content-Length", "128"); put.setHeader("If-Match", "W/\"etag\""); - request = HttpRequestWrapper.wrap(put, host); + request = RoutedHttpRequest.adapt(put, route); testRequestWithWeakETagValidatorIsNotAllowed("If-Match"); } @Test public void testPUTWithIfNoneMatchWeakETagIsNotAllowed() throws Exception { - final HttpRequest put = new BasicHttpRequest("PUT", "/", HttpVersion.HTTP_1_1); + final ClassicHttpRequest put = new BasicClassicHttpRequest("PUT", "/"); put.setEntity(HttpTestUtils.makeBody(128)); put.setHeader("Content-Length", "128"); put.setHeader("If-None-Match", "W/\"etag\""); - request = HttpRequestWrapper.wrap(put, host); + request = RoutedHttpRequest.adapt(put, route); testRequestWithWeakETagValidatorIsNotAllowed("If-None-Match"); } @Test public void testDELETEWithIfMatchWeakETagIsNotAllowed() throws Exception { - request = HttpRequestWrapper.wrap( - new BasicHttpRequest("DELETE", "/", HttpVersion.HTTP_1_1), host); + request = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("DELETE", "/"), route); request.setHeader("If-Match", "W/\"etag\""); testRequestWithWeakETagValidatorIsNotAllowed("If-Match"); @@ -3055,8 +2948,8 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testDELETEWithIfNoneMatchWeakETagIsNotAllowed() throws Exception { - request = HttpRequestWrapper.wrap( - new BasicHttpRequest("DELETE", "/", HttpVersion.HTTP_1_1), host); + request = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("DELETE", "/"), route); request.setHeader("If-None-Match", "W/\"etag\""); testRequestWithWeakETagValidatorIsNotAllowed("If-None-Match"); @@ -3072,9 +2965,9 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testSubrangeGETMustUseStrongComparisonForCachedResponse() throws Exception { final Date now = new Date(); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Date", DateUtils.formatDate(now)); resp1.setHeader("Cache-Control", "max-age=3600"); resp1.setHeader("ETag", "\"etag\""); @@ -3084,25 +2977,23 @@ public class TestProtocolRequirements extends AbstractProtocolTest { // 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 HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("Range", "bytes=0-50"); req2.setHeader("If-Range", "W/\"etag\""); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp1)).times(1, 2); + EasyMock.isNull())).andReturn(resp1).times(1, 2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - Assert.assertFalse(HttpStatus.SC_PARTIAL_CONTENT == result.getStatusLine().getStatusCode()); + Assert.assertFalse(HttpStatus.SC_PARTIAL_CONTENT == result.getCode()); } /* @@ -3118,41 +3009,37 @@ public class TestProtocolRequirements extends AbstractProtocolTest { final Date now = new Date(); final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Date", DateUtils.formatDate(now)); resp1.setHeader("Cache-Control", "max-age=3600"); resp1.setHeader("Last-Modified", DateUtils.formatDate(tenSecondsAgo)); resp1.setHeader("ETag", "W/\"etag\""); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("Cache-Control", "max-age=0,max-stale=0"); - final Capture cap = new Capture<>(); + final Capture cap = new Capture<>(); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp1)); + EasyMock.isNull())).andReturn(resp1); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), EasyMock.capture(cap), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp1)); + EasyMock.isNull())).andReturn(resp1); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); verifyMocks(); - final HttpRequest validation = cap.getValue(); + final ClassicHttpRequest validation = cap.getValue(); boolean isConditional = false; final String[] conditionalHeaders = { "If-Range", "If-Modified-Since", "If-Unmodified-Since", "If-Match", "If-None-Match" }; @@ -3166,18 +3053,18 @@ public class TestProtocolRequirements extends AbstractProtocolTest { if (isConditional) { boolean foundETag = false; - for (final Header h : validation.getHeaders("If-Match")) { - for (final HeaderElement elt : h.getElements()) { - if ("W/\"etag\"".equals(elt.getName())) { - foundETag = true; - } + final Iterator it = MessageSupport.iterate(validation, HttpHeaders.IF_MATCH); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + if ("W/\"etag\"".equals(elt.getName())) { + foundETag = true; } } - for (final Header h : validation.getHeaders("If-None-Match")) { - for (final HeaderElement elt : h.getElements()) { - if ("W/\"etag\"".equals(elt.getName())) { - foundETag = true; - } + final Iterator it2 = MessageSupport.iterate(validation, HttpHeaders.IF_NONE_MATCH); + while (it2.hasNext()) { + final HeaderElement elt = it2.next(); + if ("W/\"etag\"".equals(elt.getName())) { + foundETag = true; } } Assert.assertTrue(foundETag); @@ -3200,34 +3087,32 @@ public class TestProtocolRequirements extends AbstractProtocolTest { final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); final Date twentySecondsAgo = new Date(now.getTime() - 20 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Date", DateUtils.formatDate(now)); resp1.setHeader("Cache-Control", "max-age=3600"); resp1.setHeader("Last-Modified", DateUtils.formatDate(tenSecondsAgo)); resp1.setHeader("ETag", "W/\"etag\""); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("If-None-Match", "W/\"etag\""); req2.setHeader("If-Modified-Since", DateUtils.formatDate(twentySecondsAgo)); // must hit the origin again for the second request EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp1)).times(2); + EasyMock.isNull())).andReturn(resp1).times(2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - Assert.assertFalse(HttpStatus.SC_NOT_MODIFIED == result.getStatusLine().getStatusCode()); + Assert.assertFalse(HttpStatus.SC_NOT_MODIFIED == result.getCode()); } @Test @@ -3236,31 +3121,29 @@ public class TestProtocolRequirements extends AbstractProtocolTest { final Date now = new Date(); final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Date", DateUtils.formatDate(now)); resp1.setHeader("Cache-Control", "max-age=3600"); resp1.setHeader("Last-Modified", DateUtils.formatDate(tenSecondsAgo)); resp1.setHeader("ETag", "W/\"etag\""); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("If-None-Match", "W/\"etag\""); req2.setHeader("If-Modified-Since", DateUtils.formatDate(tenSecondsAgo)); // may hit the origin again for the second request EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp1)).times(1,2); + EasyMock.isNull())).andReturn(resp1).times(1,2); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); verifyMocks(); } @@ -3278,23 +3161,22 @@ public class TestProtocolRequirements extends AbstractProtocolTest { if (!supportsRangeAndContentRangeHeaders(impl)) { emptyMockCacheExpectsNoPuts(); - final HttpRequestWrapper req = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req.setHeader("Range", "bytes=0-50"); - final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, 206, "Partial Content"); + final ClassicHttpResponse resp = new BasicClassicHttpResponse(206, "Partial Content"); resp.setHeader("Content-Range", "bytes 0-50/128"); resp.setHeader("ETag", "\"etag\""); resp.setHeader("Cache-Control", "max-age=3600"); EasyMock.expect(mockBackend.execute( - EasyMock.isA(HttpRoute.class), - EasyMock.isA(HttpRequestWrapper.class), + EasyMock.isA(RoutedHttpRequest.class), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn(Proxies.enhanceResponse(resp)); + EasyMock.isNull())).andReturn(resp); replayMocks(); - impl.execute(route, req, context, null); + impl.execute(req, context, null); verifyMocks(); } } @@ -3312,8 +3194,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { */ @Test public void test302ResponseWithoutExplicitCacheabilityIsNotReturnedFromCache() throws Exception { - originResponse = Proxies.enhanceResponse( - new BasicHttpResponse(HttpVersion.HTTP_1_1, 302, "Temporary Redirect")); + originResponse = new BasicClassicHttpResponse(302, "Temporary Redirect"); originResponse.setHeader("Location", "http://foo.example.com/other"); originResponse.removeHeaders("Expires"); originResponse.removeHeaders("Cache-Control"); @@ -3321,8 +3202,8 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequest().andReturn(originResponse).times(2); replayMocks(); - impl.execute(route, request, context, null); - impl.execute(route, request, context, null); + impl.execute(request, context, null); + impl.execute(request, context, null); verifyMocks(); } @@ -3332,13 +3213,13 @@ public class TestProtocolRequirements extends AbstractProtocolTest { * already present: - Content-Location - Content-MD5 - ETag - Last-Modified */ private void testDoesNotModifyHeaderFromOrigin(final String header, final String value) throws Exception { - originResponse = Proxies.enhanceResponse(HttpTestUtils.make200Response()); + originResponse = HttpTestUtils.make200Response(); originResponse.setHeader(header, value); backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); Assert.assertEquals(value, result.getFirstHeader(header).getValue()); @@ -3373,7 +3254,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); Assert.assertNull(result.getFirstHeader(header)); @@ -3402,20 +3283,20 @@ public class TestProtocolRequirements extends AbstractProtocolTest { private void testDoesNotModifyHeaderFromOriginOnCacheHit(final String header, final String value) throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); - originResponse = Proxies.enhanceResponse(HttpTestUtils.make200Response()); + originResponse = HttpTestUtils.make200Response(); originResponse.setHeader("Cache-Control", "max-age=3600"); originResponse.setHeader(header, value); backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); Assert.assertEquals(value, result.getFirstHeader(header).getValue()); @@ -3445,10 +3326,10 @@ public class TestProtocolRequirements extends AbstractProtocolTest { private void testDoesNotAddHeaderOnCacheHit(final String header) throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); originResponse.addHeader("Cache-Control", "max-age=3600"); originResponse.removeHeaders(header); @@ -3456,8 +3337,8 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); Assert.assertNull(result.getFirstHeader(header)); @@ -3484,26 +3365,24 @@ public class TestProtocolRequirements extends AbstractProtocolTest { } private void testDoesNotModifyHeaderOnRequest(final String header, final String value) throws Exception { - final BasicHttpRequest req = - new BasicHttpRequest("POST","/",HttpVersion.HTTP_1_1); + final BasicClassicHttpRequest req = new BasicClassicHttpRequest("POST","/"); req.setEntity(HttpTestUtils.makeBody(128)); req.setHeader("Content-Length","128"); req.setHeader(header,value); - final Capture cap = new Capture<>(); + final Capture cap = new Capture<>(); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), EasyMock.capture(cap), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - impl.execute(route, HttpRequestWrapper.wrap(req, host), context, null); + impl.execute(RoutedHttpRequest.adapt(req, route), context, null); verifyMocks(); - final HttpRequest captured = cap.getValue(); + final ClassicHttpRequest captured = cap.getValue(); Assert.assertEquals(value, captured.getFirstHeader(header).getValue()); } @@ -3531,26 +3410,24 @@ public class TestProtocolRequirements extends AbstractProtocolTest { } private void testDoesNotAddHeaderToRequestIfNotPresent(final String header) throws Exception { - final BasicHttpRequest req = - new BasicHttpRequest("POST","/",HttpVersion.HTTP_1_1); + final BasicClassicHttpRequest req = new BasicClassicHttpRequest("POST","/"); req.setEntity(HttpTestUtils.makeBody(128)); req.setHeader("Content-Length","128"); req.removeHeaders(header); - final Capture cap = new Capture<>(); + final Capture cap = new Capture<>(); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), EasyMock.capture(cap), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - impl.execute(route, HttpRequestWrapper.wrap(req, host), context, null); + impl.execute(RoutedHttpRequest.adapt(req, route), context, null); verifyMocks(); - final HttpRequest captured = cap.getValue(); + final ClassicHttpRequest captured = cap.getValue(); Assert.assertNull(captured.getFirstHeader(header)); } @@ -3601,7 +3478,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); final Header expHdr = result.getFirstHeader("Expires"); @@ -3613,10 +3490,10 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testExpiresHeaderMatchesDateIfAddedToCacheHit() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); originResponse.setHeader("Cache-Control","max-age=3600"); originResponse.removeHeaders("Expires"); @@ -3624,8 +3501,8 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); final Header expHdr = result.getFirstHeader("Expires"); @@ -3648,7 +3525,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); Assert.assertEquals(value, result.getFirstHeader(header).getValue()); @@ -3664,8 +3541,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { request.setHeader("If-Range","\"etag\""); request.setHeader("Range","bytes=0-49"); - originResponse = Proxies.enhanceResponse( - new BasicHttpResponse(HttpVersion.HTTP_1_1, 206, "Partial Content")); + originResponse = new BasicClassicHttpResponse(206, "Partial Content"); originResponse.setEntity(HttpTestUtils.makeBody(50)); testDoesNotModifyHeaderFromOriginResponseWithNoTransform("Content-Range","bytes 0-49/128"); } @@ -3676,10 +3552,10 @@ public class TestProtocolRequirements extends AbstractProtocolTest { } private void testDoesNotModifyHeaderOnCachedResponseWithNoTransform(final String header, final String value) throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); originResponse.addHeader("Cache-Control","max-age=3600, no-transform"); originResponse.setHeader(header, value); @@ -3687,8 +3563,8 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); Assert.assertEquals(value, result.getFirstHeader(header).getValue()); @@ -3706,12 +3582,12 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testDoesNotModifyContentRangeHeaderOnCachedResponseWithNoTransform() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req1.setHeader("If-Range","\"etag\""); req1.setHeader("Range","bytes=0-49"); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("If-Range","\"etag\""); req2.setHeader("Range","bytes=0-49"); @@ -3721,8 +3597,8 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequest().andReturn(originResponse).times(1,2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); Assert.assertEquals("bytes 0-49/128", @@ -3809,23 +3685,23 @@ public class TestProtocolRequirements extends AbstractProtocolTest { * http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.5.3 */ public void testCachedEntityBodyIsUsedForResponseAfter304Validation() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Cache-Control","max-age=3600"); resp1.setHeader("ETag","\"etag\""); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("Cache-Control","max-age=0, max-stale=0"); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_MODIFIED, "Not Modified"); + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_NOT_MODIFIED, "Not Modified"); backendExpectsAnyRequestAndReturn(resp1); backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); final InputStream i1 = resp1.getEntity().getContent(); @@ -3852,7 +3728,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { * with corresponding headers received in the incoming response, * except for Warning headers as described immediately above." */ - private void decorateWithEndToEndHeaders(final HttpResponse r) { + private void decorateWithEndToEndHeaders(final ClassicHttpResponse r) { r.setHeader("Allow","GET"); r.setHeader("Content-Encoding","gzip"); r.setHeader("Content-Language","en"); @@ -3869,17 +3745,17 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testResponseIncludesCacheEntryEndToEndHeadersForResponseAfter304Validation() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Cache-Control","max-age=3600"); resp1.setHeader("ETag","\"etag\""); decorateWithEndToEndHeaders(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("Cache-Control", "max-age=0, max-stale=0"); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_MODIFIED, "Not Modified"); + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_NOT_MODIFIED, "Not Modified"); resp2.setHeader("Date", DateUtils.formatDate(new Date())); resp2.setHeader("Server", "MockServer/1.0"); @@ -3887,8 +3763,8 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); final String[] endToEndHeaders = { @@ -3906,17 +3782,17 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testUpdatedEndToEndHeadersFrom304ArePassedOnResponseAndUpdatedInCacheEntry() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Cache-Control","max-age=3600"); resp1.setHeader("ETag","\"etag\""); decorateWithEndToEndHeaders(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("Cache-Control", "max-age=0, max-stale=0"); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_MODIFIED, "Not Modified"); + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_NOT_MODIFIED, "Not Modified"); resp2.setHeader("Cache-Control", "max-age=1800"); resp2.setHeader("Date", DateUtils.formatDate(new Date())); resp2.setHeader("Server", "MockServer/1.0"); @@ -3932,13 +3808,13 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp1); backendExpectsAnyRequestAndReturn(resp2); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result1 = impl.execute(route, req2, context, null); - final HttpResponse result2 = impl.execute(route, req3, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result1 = impl.execute(req2, context, null); + final ClassicHttpResponse result2 = impl.execute(req3, context, null); verifyMocks(); final String[] endToEndHeaders = { @@ -3960,29 +3836,29 @@ public class TestProtocolRequirements extends AbstractProtocolTest { */ @Test public void testMultiHeadersAreSuccessfullyReplacedOn304Validation() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.addHeader("Cache-Control","max-age=3600"); resp1.addHeader("Cache-Control","public"); resp1.setHeader("ETag","\"etag\""); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("Cache-Control", "max-age=0, max-stale=0"); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_MODIFIED, "Not Modified"); + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_NOT_MODIFIED, "Not Modified"); resp2.setHeader("Cache-Control", "max-age=1800"); backendExpectsAnyRequestAndReturn(resp1); backendExpectsAnyRequestAndReturn(resp2); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result1 = impl.execute(route, req2, context, null); - final HttpResponse result2 = impl.execute(route, req3, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result1 = impl.execute(req2, context, null); + final ClassicHttpResponse result2 = impl.execute(req3, context, null); verifyMocks(); final String h = "Cache-Control"; @@ -4015,15 +3891,15 @@ public class TestProtocolRequirements extends AbstractProtocolTest { public void testCannotCombinePartialResponseIfIncomingResponseDoesNotHaveACacheValidator() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req1.setHeader("Range","bytes=0-49"); final Date now = new Date(); final Date oneSecondAgo = new Date(now.getTime() - 1 * 1000L); final Date twoSecondsAgo = new Date(now.getTime() - 2 * 1000L); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); resp1.setEntity(HttpTestUtils.makeBody(50)); resp1.setHeader("Server","MockServer/1.0"); resp1.setHeader("Date", DateUtils.formatDate(twoSecondsAgo)); @@ -4033,11 +3909,11 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("Range","bytes=50-127"); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); resp2.setEntity(HttpTestUtils.makeBody(78)); resp2.setHeader("Cache-Control","max-age=3600"); resp2.setHeader("Content-Range","bytes 50-127/128"); @@ -4046,10 +3922,10 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp2); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); - final HttpResponse resp3 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); + final ClassicHttpResponse resp3 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp3.setEntity(HttpTestUtils.makeBody(128)); resp3.setHeader("Server","MockServer/1.0"); resp3.setHeader("Date", DateUtils.formatDate(now)); @@ -4057,9 +3933,9 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp3); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); - impl.execute(route, req3, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); + impl.execute(req3, context, null); verifyMocks(); } @@ -4071,11 +3947,11 @@ public class TestProtocolRequirements extends AbstractProtocolTest { final Date oneSecondAgo = new Date(now.getTime() - 1 * 1000L); final Date twoSecondsAgo = new Date(now.getTime() - 2 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req1.setHeader("Range","bytes=0-49"); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); resp1.setEntity(HttpTestUtils.makeBody(50)); resp1.setHeader("Cache-Control","max-age=3600"); resp1.setHeader("Content-Range","bytes 0-49/128"); @@ -4084,11 +3960,11 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("Range","bytes=50-127"); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); resp2.setEntity(HttpTestUtils.makeBody(78)); resp2.setHeader("Cache-Control","max-age=3600"); resp2.setHeader("Content-Range","bytes 50-127/128"); @@ -4098,10 +3974,10 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp2); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); - final HttpResponse resp3 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); + final ClassicHttpResponse resp3 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp3.setEntity(HttpTestUtils.makeBody(128)); resp3.setHeader("Server","MockServer/1.0"); resp3.setHeader("Date", DateUtils.formatDate(now)); @@ -4109,9 +3985,9 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp3); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); - impl.execute(route, req3, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); + impl.execute(req3, context, null); verifyMocks(); } @@ -4123,11 +3999,11 @@ public class TestProtocolRequirements extends AbstractProtocolTest { final Date oneSecondAgo = new Date(now.getTime() - 1 * 1000L); final Date twoSecondsAgo = new Date(now.getTime() - 2 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req1.setHeader("Range","bytes=0-49"); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); resp1.setEntity(HttpTestUtils.makeBody(50)); resp1.setHeader("Cache-Control","max-age=3600"); resp1.setHeader("Content-Range","bytes 0-49/128"); @@ -4137,11 +4013,11 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("Range","bytes=50-127"); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); resp2.setEntity(HttpTestUtils.makeBody(78)); resp2.setHeader("Cache-Control","max-age=3600"); resp2.setHeader("Content-Range","bytes 50-127/128"); @@ -4151,10 +4027,10 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp2); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); - final HttpResponse resp3 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); + final ClassicHttpResponse resp3 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp3.setEntity(HttpTestUtils.makeBody(128)); resp3.setHeader("Server","MockServer/1.0"); resp3.setHeader("Date", DateUtils.formatDate(now)); @@ -4162,9 +4038,9 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp3); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); - impl.execute(route, req3, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); + impl.execute(req3, context, null); verifyMocks(); } @@ -4176,11 +4052,11 @@ public class TestProtocolRequirements extends AbstractProtocolTest { final Date oneSecondAgo = new Date(now.getTime() - 1 * 1000L); final Date twoSecondsAgo = new Date(now.getTime() - 2 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req1.setHeader("Range","bytes=0-49"); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); resp1.setEntity(HttpTestUtils.makeBody(50)); resp1.setHeader("Cache-Control","max-age=3600"); resp1.setHeader("Content-Range","bytes 0-49/128"); @@ -4190,11 +4066,11 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("Range","bytes=50-127"); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); resp2.setEntity(HttpTestUtils.makeBody(78)); resp2.setHeader("Cache-Control","max-age=3600"); resp2.setHeader("Content-Range","bytes 50-127/128"); @@ -4203,11 +4079,11 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp2); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req3.setHeader("Range","bytes=0-49"); - final HttpResponse resp3 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); + final ClassicHttpResponse resp3 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp3.setEntity(HttpTestUtils.makeBody(128)); resp3.setHeader("Server","MockServer/1.0"); resp3.setHeader("Date", DateUtils.formatDate(now)); @@ -4216,9 +4092,9 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp3); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); - impl.execute(route, req3, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); + impl.execute(req3, context, null); verifyMocks(); } @@ -4230,11 +4106,11 @@ public class TestProtocolRequirements extends AbstractProtocolTest { final Date oneSecondAgo = new Date(now.getTime() - 1 * 1000L); final Date twoSecondsAgo = new Date(now.getTime() - 2 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req1.setHeader("Range","bytes=0-49"); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); resp1.setEntity(HttpTestUtils.makeBody(50)); resp1.setHeader("Cache-Control","max-age=3600"); resp1.setHeader("Content-Range","bytes 0-49/128"); @@ -4243,11 +4119,11 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("Range","bytes=50-127"); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); resp2.setEntity(HttpTestUtils.makeBody(78)); resp2.setHeader("Cache-Control","max-age=3600"); resp2.setHeader("Content-Range","bytes 50-127/128"); @@ -4257,11 +4133,11 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp2); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req3.setHeader("Range","bytes=0-49"); - final HttpResponse resp3 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); + final ClassicHttpResponse resp3 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp3.setEntity(HttpTestUtils.makeBody(128)); resp3.setHeader("Server","MockServer/1.0"); resp3.setHeader("Date", DateUtils.formatDate(now)); @@ -4270,9 +4146,9 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp3); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); - impl.execute(route, req3, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); + impl.execute(req3, context, null); verifyMocks(); } @@ -4284,11 +4160,11 @@ public class TestProtocolRequirements extends AbstractProtocolTest { final Date oneSecondAgo = new Date(now.getTime() - 1 * 1000L); final Date twoSecondsAgo = new Date(now.getTime() - 2 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req1.setHeader("Range","bytes=0-49"); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); resp1.setEntity(HttpTestUtils.makeBody(50)); resp1.setHeader("Cache-Control","max-age=3600"); resp1.setHeader("Content-Range","bytes 0-49/128"); @@ -4298,11 +4174,11 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("Range","bytes=50-127"); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); resp2.setEntity(HttpTestUtils.makeBody(78)); resp2.setHeader("Cache-Control","max-age=3600"); resp2.setHeader("Content-Range","bytes 50-127/128"); @@ -4312,11 +4188,11 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp2); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req3.setHeader("Range","bytes=0-49"); - final HttpResponse resp3 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); + final ClassicHttpResponse resp3 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp3.setEntity(HttpTestUtils.makeBody(128)); resp3.setHeader("Server","MockServer/1.0"); resp3.setHeader("Date", DateUtils.formatDate(now)); @@ -4325,9 +4201,9 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp3); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); - impl.execute(route, req3, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); + impl.execute(req3, context, null); verifyMocks(); } @@ -4339,11 +4215,11 @@ public class TestProtocolRequirements extends AbstractProtocolTest { final Date oneSecondAgo = new Date(now.getTime() - 1 * 1000L); final Date twoSecondsAgo = new Date(now.getTime() - 2 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req1.setHeader("Range","bytes=0-49"); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); resp1.setEntity(HttpTestUtils.makeBody(50)); resp1.setHeader("Cache-Control","max-age=3600"); resp1.setHeader("Content-Range","bytes 0-49/128"); @@ -4353,11 +4229,11 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("Range","bytes=50-127"); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); resp2.setEntity(HttpTestUtils.makeBody(78)); resp2.setHeader("Cache-Control","max-age=3600"); resp2.setHeader("Content-Range","bytes 50-127/128"); @@ -4367,11 +4243,11 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp2); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req3.setHeader("Range","bytes=50-127"); - final HttpResponse resp3 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); + final ClassicHttpResponse resp3 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp3.setEntity(HttpTestUtils.makeBody(128)); resp3.setHeader("Server","MockServer/1.0"); resp3.setHeader("Date", DateUtils.formatDate(now)); @@ -4380,9 +4256,9 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp3); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); - impl.execute(route, req3, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); + impl.execute(req3, context, null); verifyMocks(); } @@ -4393,11 +4269,11 @@ public class TestProtocolRequirements extends AbstractProtocolTest { final Date now = new Date(); final Date oneSecondAgo = new Date(now.getTime() - 1 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req1.setHeader("Range","bytes=0-49"); - final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); + final ClassicHttpResponse resp1 = new BasicClassicHttpResponse(HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); resp1.setEntity(HttpTestUtils.makeBody(50)); resp1.setHeader("Cache-Control","max-age=3600"); resp1.setHeader("Content-Range","bytes 0-49/128"); @@ -4407,11 +4283,11 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("Range","bytes=50-127"); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); resp2.setEntity(HttpTestUtils.makeBody(78)); resp2.setHeader("Cache-Control","max-age=3600"); resp2.setHeader("Content-Range","bytes 50-127/128"); @@ -4421,11 +4297,11 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp2); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req3.setHeader("Range","bytes=0-49"); - final HttpResponse resp3 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); + final ClassicHttpResponse resp3 = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); resp3.setEntity(HttpTestUtils.makeBody(128)); resp3.setHeader("Server","MockServer/1.0"); resp3.setHeader("Date", DateUtils.formatDate(now)); @@ -4434,9 +4310,9 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp3); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); - impl.execute(route, req3, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); + impl.execute(req3, context, null); verifyMocks(); } @@ -4453,22 +4329,22 @@ public class TestProtocolRequirements extends AbstractProtocolTest { public void testCannotUseVariantCacheEntryIfNotAllSelectingRequestHeadersMatch() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req1.setHeader("Accept-Encoding","gzip"); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("ETag","\"etag1\""); resp1.setHeader("Cache-Control","max-age=3600"); resp1.setHeader("Vary","Accept-Encoding"); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.removeHeaders("Accept-Encoding"); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); resp2.setHeader("ETag","\"etag1\""); resp2.setHeader("Cache-Control","max-age=3600"); @@ -4476,8 +4352,8 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); verifyMocks(); } @@ -4489,20 +4365,20 @@ public class TestProtocolRequirements extends AbstractProtocolTest { */ @Test public void testCannotServeFromCacheForVaryStar() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("ETag","\"etag1\""); resp1.setHeader("Cache-Control","max-age=3600"); resp1.setHeader("Vary","*"); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); resp2.setHeader("ETag","\"etag1\""); resp2.setHeader("Cache-Control","max-age=3600"); @@ -4510,8 +4386,8 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); verifyMocks(); } @@ -4541,11 +4417,11 @@ public class TestProtocolRequirements extends AbstractProtocolTest { public void testNonmatchingVariantCannotBeServedFromCacheUnlessConditionallyValidated() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req1.setHeader("User-Agent","MyBrowser/1.0"); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("ETag","\"etag1\""); resp1.setHeader("Cache-Control","max-age=3600"); resp1.setHeader("Vary","User-Agent"); @@ -4553,47 +4429,43 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("User-Agent","MyBrowser/1.5"); - final HttpRequestWrapper conditional = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest conditional = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); conditional.setHeader("User-Agent","MyBrowser/1.5"); conditional.setHeader("If-None-Match","\"etag1\""); - final HttpResponse resp200 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp200 = HttpTestUtils.make200Response(); resp200.setHeader("ETag","\"etag1\""); resp200.setHeader("Vary","User-Agent"); - final HttpResponse resp304 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_MODIFIED, "Not Modified"); + final ClassicHttpResponse resp304 = new BasicClassicHttpResponse(HttpStatus.SC_NOT_MODIFIED, "Not Modified"); resp304.setHeader("ETag","\"etag1\""); resp304.setHeader("Vary","User-Agent"); - final Capture condCap = new Capture<>(); - final Capture uncondCap = new Capture<>(); + final Capture condCap = new Capture<>(); + final Capture uncondCap = new Capture<>(); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), EasyMock.and(eqRequest(conditional), EasyMock.capture(condCap)), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp304)).times(0,1); + EasyMock.isNull())).andReturn(resp304).times(0,1); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), EasyMock.and(eqRequest(req2), EasyMock.capture(uncondCap)), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp200)).times(0,1); + EasyMock.isNull())).andReturn(resp200).times(0,1); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - if (HttpStatus.SC_OK == result.getStatusLine().getStatusCode()) { + if (HttpStatus.SC_OK == result.getCode()) { Assert.assertTrue(condCap.hasCaptured() || uncondCap.hasCaptured()); if (uncondCap.hasCaptured()) { @@ -4622,10 +4494,10 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); - final int status = result.getStatusLine().getStatusCode(); + final int status = result.getCode(); Assert.assertFalse(HttpStatus.SC_OK == status); if (status > 200 && status <= 299 && HttpTestUtils.equivalent(originResponse.getEntity(), @@ -4645,148 +4517,148 @@ public class TestProtocolRequirements extends AbstractProtocolTest { * http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.9 */ protected void testUnsafeOperationInvalidatesCacheForThatUri( - final HttpRequestWrapper unsafeReq) throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest unsafeReq) throws Exception { + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Cache-Control","public, max-age=3600"); backendExpectsAnyRequestAndReturn(resp1); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NO_CONTENT, "No Content"); + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_NO_CONTENT, "No Content"); backendExpectsAnyRequestAndReturn(resp2); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp3 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp3 = HttpTestUtils.make200Response(); resp3.setHeader("Cache-Control","public, max-age=3600"); // this origin request MUST happen due to invalidation backendExpectsAnyRequestAndReturn(resp3); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, unsafeReq, context, null); - impl.execute(route, req3, context, null); + impl.execute(req1, context, null); + impl.execute(unsafeReq, context, null); + impl.execute(req3, context, null); verifyMocks(); } @Test public void testPutToUriInvalidatesCacheForThatUri() throws Exception { - final HttpRequest req = makeRequestWithBody("PUT","/"); - testUnsafeOperationInvalidatesCacheForThatUri(HttpRequestWrapper.wrap(req, host)); + final ClassicHttpRequest req = makeRequestWithBody("PUT","/"); + testUnsafeOperationInvalidatesCacheForThatUri(RoutedHttpRequest.adapt(req, route)); } @Test public void testDeleteToUriInvalidatesCacheForThatUri() throws Exception { - final HttpRequestWrapper req = HttpRequestWrapper.wrap(new BasicHttpRequest("DELETE","/"), host); + final RoutedHttpRequest req = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("DELETE","/"), route); testUnsafeOperationInvalidatesCacheForThatUri(req); } @Test public void testPostToUriInvalidatesCacheForThatUri() throws Exception { - final HttpRequestWrapper req = makeRequestWithBody("POST","/"); + final RoutedHttpRequest req = makeRequestWithBody("POST","/"); testUnsafeOperationInvalidatesCacheForThatUri(req); } protected void testUnsafeMethodInvalidatesCacheForHeaderUri( - final HttpRequestWrapper unsafeReq) throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/content", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest unsafeReq) throws Exception { + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/content"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Cache-Control","public, max-age=3600"); backendExpectsAnyRequestAndReturn(resp1); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NO_CONTENT, "No Content"); + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_NO_CONTENT, "No Content"); backendExpectsAnyRequestAndReturn(resp2); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/content", HttpVersion.HTTP_1_1), host); - final HttpResponse resp3 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/content"), route); + final ClassicHttpResponse resp3 = HttpTestUtils.make200Response(); resp3.setHeader("Cache-Control","public, max-age=3600"); // this origin request MUST happen due to invalidation backendExpectsAnyRequestAndReturn(resp3); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, unsafeReq, context, null); - impl.execute(route, req3, context, null); + impl.execute(req1, context, null); + impl.execute(unsafeReq, context, null); + impl.execute(req3, context, null); verifyMocks(); } protected void testUnsafeMethodInvalidatesCacheForUriInContentLocationHeader( - final HttpRequestWrapper unsafeReq) throws Exception { + final RoutedHttpRequest unsafeReq) throws Exception { unsafeReq.setHeader("Content-Location","http://foo.example.com/content"); testUnsafeMethodInvalidatesCacheForHeaderUri(unsafeReq); } protected void testUnsafeMethodInvalidatesCacheForRelativeUriInContentLocationHeader( - final HttpRequestWrapper unsafeReq) throws Exception { + final RoutedHttpRequest unsafeReq) throws Exception { unsafeReq.setHeader("Content-Location","/content"); testUnsafeMethodInvalidatesCacheForHeaderUri(unsafeReq); } protected void testUnsafeMethodInvalidatesCacheForUriInLocationHeader( - final HttpRequestWrapper unsafeReq) throws Exception { + final RoutedHttpRequest unsafeReq) throws Exception { unsafeReq.setHeader("Location","http://foo.example.com/content"); testUnsafeMethodInvalidatesCacheForHeaderUri(unsafeReq); } @Test public void testPutInvalidatesCacheForThatUriInContentLocationHeader() throws Exception { - final HttpRequestWrapper req2 = makeRequestWithBody("PUT","/"); + final RoutedHttpRequest req2 = makeRequestWithBody("PUT","/"); testUnsafeMethodInvalidatesCacheForUriInContentLocationHeader(req2); } @Test public void testPutInvalidatesCacheForThatUriInLocationHeader() throws Exception { - final HttpRequestWrapper req = makeRequestWithBody("PUT","/"); + final RoutedHttpRequest req = makeRequestWithBody("PUT","/"); testUnsafeMethodInvalidatesCacheForUriInLocationHeader(req); } @Test public void testPutInvalidatesCacheForThatUriInRelativeContentLocationHeader() throws Exception { - final HttpRequestWrapper req = makeRequestWithBody("PUT","/"); + final RoutedHttpRequest req = makeRequestWithBody("PUT","/"); testUnsafeMethodInvalidatesCacheForRelativeUriInContentLocationHeader(req); } @Test public void testDeleteInvalidatesCacheForThatUriInContentLocationHeader() throws Exception { - final HttpRequestWrapper req = HttpRequestWrapper.wrap(new BasicHttpRequest("DELETE", "/"), host); + final RoutedHttpRequest req = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("DELETE", "/"), route); testUnsafeMethodInvalidatesCacheForUriInContentLocationHeader(req); } @Test public void testDeleteInvalidatesCacheForThatUriInRelativeContentLocationHeader() throws Exception { - final HttpRequestWrapper req = HttpRequestWrapper.wrap(new BasicHttpRequest("DELETE", "/"), host); + final RoutedHttpRequest req = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("DELETE", "/"), route); testUnsafeMethodInvalidatesCacheForRelativeUriInContentLocationHeader(req); } @Test public void testDeleteInvalidatesCacheForThatUriInLocationHeader() throws Exception { - final HttpRequestWrapper req = HttpRequestWrapper.wrap(new BasicHttpRequest("DELETE", "/"), host); + final RoutedHttpRequest req = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("DELETE", "/"), route); testUnsafeMethodInvalidatesCacheForUriInLocationHeader(req); } @Test public void testPostInvalidatesCacheForThatUriInContentLocationHeader() throws Exception { - final HttpRequestWrapper req = makeRequestWithBody("POST","/"); + final RoutedHttpRequest req = makeRequestWithBody("POST","/"); testUnsafeMethodInvalidatesCacheForUriInContentLocationHeader(req); } @Test public void testPostInvalidatesCacheForThatUriInLocationHeader() throws Exception { - final HttpRequestWrapper req = makeRequestWithBody("POST","/"); + final RoutedHttpRequest req = makeRequestWithBody("POST","/"); testUnsafeMethodInvalidatesCacheForUriInLocationHeader(req); } @Test public void testPostInvalidatesCacheForRelativeUriInContentLocationHeader() throws Exception { - final HttpRequestWrapper req = makeRequestWithBody("POST","/"); + final RoutedHttpRequest req = makeRequestWithBody("POST","/"); testUnsafeMethodInvalidatesCacheForRelativeUriInContentLocationHeader(req); } @@ -4797,87 +4669,87 @@ public class TestProtocolRequirements extends AbstractProtocolTest { * http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.10 */ protected void testUnsafeMethodDoesNotInvalidateCacheForHeaderUri( - final HttpRequestWrapper unsafeReq) throws Exception { + final RoutedHttpRequest unsafeReq) throws Exception { final HttpHost otherHost = new HttpHost("bar.example.com", 80); final HttpRoute otherRoute = new HttpRoute(otherHost); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/content", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/content"), otherRoute); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Cache-Control","public, max-age=3600"); backendExpectsAnyRequestAndReturn(resp1); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NO_CONTENT, "No Content"); + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_NO_CONTENT, "No Content"); backendExpectsAnyRequestAndReturn(resp2); - final HttpRequestWrapper req3 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/content", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req3 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/content"), otherRoute); replayMocks(); - impl.execute(otherRoute, req1, context, null); - impl.execute(route, unsafeReq, context, null); - impl.execute(otherRoute, req3, context, null); + impl.execute(req1, context, null); + impl.execute(unsafeReq, context, null); + impl.execute(req3, context, null); verifyMocks(); } protected void testUnsafeMethodDoesNotInvalidateCacheForUriInContentLocationHeadersFromOtherHosts( - final HttpRequestWrapper unsafeReq) throws Exception { + final RoutedHttpRequest unsafeReq) throws Exception { unsafeReq.setHeader("Content-Location","http://bar.example.com/content"); testUnsafeMethodDoesNotInvalidateCacheForHeaderUri(unsafeReq); } protected void testUnsafeMethodDoesNotInvalidateCacheForUriInLocationHeadersFromOtherHosts( - final HttpRequestWrapper unsafeReq) throws Exception { + final RoutedHttpRequest unsafeReq) throws Exception { unsafeReq.setHeader("Location","http://bar.example.com/content"); testUnsafeMethodDoesNotInvalidateCacheForHeaderUri(unsafeReq); } - protected HttpRequestWrapper makeRequestWithBody(final String method, final String requestUri) { - final HttpRequest req = - new BasicHttpRequest(method, requestUri, HttpVersion.HTTP_1_1); + protected RoutedHttpRequest makeRequestWithBody(final String method, final String requestUri) { + final ClassicHttpRequest req = + new BasicClassicHttpRequest(method, requestUri); final int nbytes = 128; req.setEntity(HttpTestUtils.makeBody(nbytes)); req.setHeader("Content-Length",""+nbytes); - return HttpRequestWrapper.wrap(req, host); + return RoutedHttpRequest.adapt(req, route); } @Test public void testPutDoesNotInvalidateCacheForUriInContentLocationHeadersFromOtherHosts() throws Exception { - final HttpRequestWrapper req = makeRequestWithBody("PUT","/"); + final RoutedHttpRequest req = makeRequestWithBody("PUT","/"); testUnsafeMethodDoesNotInvalidateCacheForUriInContentLocationHeadersFromOtherHosts(req); } @Test public void testPutDoesNotInvalidateCacheForUriInLocationHeadersFromOtherHosts() throws Exception { - final HttpRequestWrapper req = makeRequestWithBody("PUT","/"); + final RoutedHttpRequest req = makeRequestWithBody("PUT","/"); testUnsafeMethodDoesNotInvalidateCacheForUriInLocationHeadersFromOtherHosts(req); } @Test public void testPostDoesNotInvalidateCacheForUriInContentLocationHeadersFromOtherHosts() throws Exception { - final HttpRequestWrapper req = makeRequestWithBody("POST","/"); + final RoutedHttpRequest req = makeRequestWithBody("POST","/"); testUnsafeMethodDoesNotInvalidateCacheForUriInContentLocationHeadersFromOtherHosts(req); } @Test public void testPostDoesNotInvalidateCacheForUriInLocationHeadersFromOtherHosts() throws Exception { - final HttpRequestWrapper req = makeRequestWithBody("POST","/"); + final RoutedHttpRequest req = makeRequestWithBody("POST","/"); testUnsafeMethodDoesNotInvalidateCacheForUriInLocationHeadersFromOtherHosts(req); } @Test public void testDeleteDoesNotInvalidateCacheForUriInContentLocationHeadersFromOtherHosts() throws Exception { - final HttpRequestWrapper req = HttpRequestWrapper.wrap( - new BasicHttpRequest("DELETE", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("DELETE", "/"), route); testUnsafeMethodDoesNotInvalidateCacheForUriInContentLocationHeadersFromOtherHosts(req); } @Test public void testDeleteDoesNotInvalidateCacheForUriInLocationHeadersFromOtherHosts() throws Exception { - final HttpRequestWrapper req = HttpRequestWrapper.wrap( - new BasicHttpRequest("DELETE", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("DELETE", "/"), route); testUnsafeMethodDoesNotInvalidateCacheForUriInLocationHeadersFromOtherHosts(req); } @@ -4890,35 +4762,33 @@ public class TestProtocolRequirements extends AbstractProtocolTest { * * http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.11 */ - private void testRequestIsWrittenThroughToOrigin(final HttpRequest req) + private void testRequestIsWrittenThroughToOrigin(final ClassicHttpRequest req) throws Exception { - final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NO_CONTENT, "No Content"); - final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(req, host); + final ClassicHttpResponse resp = new BasicClassicHttpResponse(HttpStatus.SC_NO_CONTENT, "No Content"); + final RoutedHttpRequest wrapper = RoutedHttpRequest.adapt(req, route); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), eqRequest(wrapper), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp)); + EasyMock.isNull())).andReturn(resp); replayMocks(); - impl.execute(route, wrapper, context, null); + impl.execute(wrapper, context, null); verifyMocks(); } @Test @Ignore public void testOPTIONSRequestsAreWrittenThroughToOrigin() throws Exception { - final HttpRequest req = HttpRequestWrapper.wrap( - new BasicHttpRequest("OPTIONS","*",HttpVersion.HTTP_1_1), host); + final ClassicHttpRequest req = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("OPTIONS","*"), route); testRequestIsWrittenThroughToOrigin(req); } @Test public void testPOSTRequestsAreWrittenThroughToOrigin() throws Exception { - final HttpRequest req = new BasicHttpRequest("POST","/",HttpVersion.HTTP_1_1); + final ClassicHttpRequest req = new BasicClassicHttpRequest("POST","/"); req.setEntity(HttpTestUtils.makeBody(128)); req.setHeader("Content-Length","128"); testRequestIsWrittenThroughToOrigin(req); @@ -4927,7 +4797,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testPUTRequestsAreWrittenThroughToOrigin() throws Exception { - final HttpRequest req = new BasicHttpRequest("PUT","/",HttpVersion.HTTP_1_1); + final ClassicHttpRequest req = new BasicClassicHttpRequest("PUT","/"); req.setEntity(HttpTestUtils.makeBody(128)); req.setHeader("Content-Length","128"); testRequestIsWrittenThroughToOrigin(req); @@ -4936,32 +4806,32 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testDELETERequestsAreWrittenThroughToOrigin() throws Exception { - final HttpRequest req = HttpRequestWrapper.wrap( - new BasicHttpRequest("DELETE", "/", HttpVersion.HTTP_1_1), host); + final ClassicHttpRequest req = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("DELETE", "/"), route); testRequestIsWrittenThroughToOrigin(req); } @Test public void testTRACERequestsAreWrittenThroughToOrigin() throws Exception { - final HttpRequest req = HttpRequestWrapper.wrap( - new BasicHttpRequest("TRACE","/",HttpVersion.HTTP_1_1), host); + final ClassicHttpRequest req = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("TRACE","/"), route); testRequestIsWrittenThroughToOrigin(req); } @Test public void testCONNECTRequestsAreWrittenThroughToOrigin() throws Exception { - final HttpRequest req = HttpRequestWrapper.wrap( - new BasicHttpRequest("CONNECT","/",HttpVersion.HTTP_1_1), host); + final ClassicHttpRequest req = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("CONNECT","/"), route); testRequestIsWrittenThroughToOrigin(req); } @Test public void testUnknownMethodRequestsAreWrittenThroughToOrigin() throws Exception { - final HttpRequest req = HttpRequestWrapper.wrap( - new BasicHttpRequest("UNKNOWN","/",HttpVersion.HTTP_1_1), host); + final ClassicHttpRequest req = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("UNKNOWN","/"), route); testRequestIsWrittenThroughToOrigin(req); } @@ -4981,7 +4851,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); Assert.assertEquals("2147483648", @@ -5001,7 +4871,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { originResponse.setHeader("Allow",allowHeaderValue); backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); Assert.assertEquals(HttpTestUtils.getCanonicalHeaderValue(originResponse,"Allow"), HttpTestUtils.getCanonicalHeaderValue(result, "Allow")); @@ -5033,29 +4903,28 @@ public class TestProtocolRequirements extends AbstractProtocolTest { * it MAY be returned in reply to any subsequent request. */ protected void testSharedCacheRevalidatesAuthorizedResponse( - final HttpResponse authorizedResponse, final int minTimes, final int maxTimes) throws Exception { + final ClassicHttpResponse authorizedResponse, final int minTimes, final int maxTimes) throws Exception { if (config.isSharedCache()) { final String authorization = "Basic dXNlcjpwYXNzd2Q="; - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req1.setHeader("Authorization",authorization); backendExpectsAnyRequestAndReturn(authorizedResponse); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); resp2.setHeader("Cache-Control","max-age=3600"); if (maxTimes > 0) { // this request MUST happen - backendExpectsAnyRequest().andReturn( - Proxies.enhanceResponse(resp2)).times(minTimes,maxTimes); + backendExpectsAnyRequest().andReturn(resp2).times(minTimes,maxTimes); } replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); verifyMocks(); } } @@ -5063,7 +4932,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testSharedCacheMustNotNormallyCacheAuthorizedResponses() throws Exception { - final HttpResponse resp = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp = HttpTestUtils.make200Response(); resp.setHeader("Cache-Control","max-age=3600"); resp.setHeader("ETag","\"etag\""); testSharedCacheRevalidatesAuthorizedResponse(resp, 1, 1); @@ -5072,7 +4941,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testSharedCacheMayCacheAuthorizedResponsesWithSMaxAgeHeader() throws Exception { - final HttpResponse resp = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp = HttpTestUtils.make200Response(); resp.setHeader("Cache-Control","s-maxage=3600"); resp.setHeader("ETag","\"etag\""); testSharedCacheRevalidatesAuthorizedResponse(resp, 0, 1); @@ -5081,7 +4950,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testSharedCacheMustRevalidateAuthorizedResponsesWhenSMaxAgeIsZero() throws Exception { - final HttpResponse resp = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp = HttpTestUtils.make200Response(); resp.setHeader("Cache-Control","s-maxage=0"); resp.setHeader("ETag","\"etag\""); testSharedCacheRevalidatesAuthorizedResponse(resp, 1, 1); @@ -5090,7 +4959,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testSharedCacheMayCacheAuthorizedResponsesWithMustRevalidate() throws Exception { - final HttpResponse resp = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp = HttpTestUtils.make200Response(); resp.setHeader("Cache-Control","must-revalidate"); resp.setHeader("ETag","\"etag\""); testSharedCacheRevalidatesAuthorizedResponse(resp, 0, 1); @@ -5099,44 +4968,42 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testSharedCacheMayCacheAuthorizedResponsesWithCacheControlPublic() throws Exception { - final HttpResponse resp = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp = HttpTestUtils.make200Response(); resp.setHeader("Cache-Control","public"); testSharedCacheRevalidatesAuthorizedResponse(resp, 0, 1); } protected void testSharedCacheMustUseNewRequestHeadersWhenRevalidatingAuthorizedResponse( - final HttpResponse authorizedResponse) throws Exception { + final ClassicHttpResponse authorizedResponse) throws Exception { if (config.isSharedCache()) { final String authorization1 = "Basic dXNlcjpwYXNzd2Q="; final String authorization2 = "Basic dXNlcjpwYXNzd2Qy"; - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req1.setHeader("Authorization",authorization1); backendExpectsAnyRequestAndReturn(authorizedResponse); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("Authorization",authorization2); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); - final Capture cap = new Capture<>(); + final Capture cap = new Capture<>(); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), EasyMock.capture(cap), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp2)); + EasyMock.isNull())).andReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); verifyMocks(); - final HttpRequest captured = cap.getValue(); + final ClassicHttpRequest captured = cap.getValue(); Assert.assertEquals(HttpTestUtils.getCanonicalHeaderValue(req2, "Authorization"), HttpTestUtils.getCanonicalHeaderValue(captured, "Authorization")); } @@ -5147,7 +5014,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { throws Exception { final Date now = new Date(); final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Date",DateUtils.formatDate(tenSecondsAgo)); resp1.setHeader("ETag","\"etag\""); resp1.setHeader("Cache-Control","s-maxage=5"); @@ -5160,7 +5027,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { throws Exception { final Date now = new Date(); final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Date",DateUtils.formatDate(tenSecondsAgo)); resp1.setHeader("ETag","\"etag\""); resp1.setHeader("Cache-Control","maxage=5, must-revalidate"); @@ -5186,43 +5053,41 @@ public class TestProtocolRequirements extends AbstractProtocolTest { throws Exception { final Date now = new Date(); final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Date", DateUtils.formatDate(tenSecondsAgo)); resp1.setHeader("Cache-Control","max-age=5"); resp1.setHeader("Etag","\"etag\""); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("Cache-Control","max-stale=60"); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); - final Capture cap = new Capture<>(); + final Capture cap = new Capture<>(); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), EasyMock.capture(cap), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp2)).times(0,1); + EasyMock.isNull())).andReturn(resp2).times(0,1); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); if (!cap.hasCaptured()) { boolean found110Warning = false; - for(final Header h : result.getHeaders("Warning")) { - for(final HeaderElement elt : h.getElements()) { - final String[] parts = elt.getName().split("\\s"); - if ("110".equals(parts[0])) { - found110Warning = true; - break; - } + final Iterator 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; } } Assert.assertTrue(found110Warning); @@ -5238,27 +5103,26 @@ public class TestProtocolRequirements extends AbstractProtocolTest { public void testDoesNotTransmitNoCacheDirectivesWithFieldsDownstream() throws Exception { request.setHeader("Cache-Control","no-cache=\"X-Field\""); - final Capture cap = new Capture<>(); + final Capture cap = new Capture<>(); EasyMock.expect(mockBackend.execute( - EasyMock.eq(route), EasyMock.capture(cap), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse).times(0,1); replayMocks(); try { - impl.execute(route, request, context, null); + impl.execute(request, context, null); } catch (final ClientProtocolException acceptable) { } verifyMocks(); if (cap.hasCaptured()) { - final HttpRequest captured = cap.getValue(); - for(final Header h : captured.getHeaders("Cache-Control")) { - for(final HeaderElement elt : h.getElements()) { - if ("no-cache".equals(elt.getName())) { - Assert.assertNull(elt.getValue()); - } + final ClassicHttpRequest captured = cap.getValue(); + final Iterator it = MessageSupport.iterate(captured, HttpHeaders.CACHE_CONTROL); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + if ("no-cache".equals(elt.getName())) { + Assert.assertNull(elt.getValue()); } } } @@ -5270,43 +5134,41 @@ public class TestProtocolRequirements extends AbstractProtocolTest { * * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.4 */ - protected void testCacheIsNotUsedWhenRespondingToRequest(final HttpRequestWrapper req) + protected void testCacheIsNotUsedWhenRespondingToRequest(final RoutedHttpRequest req) throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Etag","\"etag\""); resp1.setHeader("Cache-Control","max-age=3600"); backendExpectsAnyRequestAndReturn(resp1); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); resp2.setHeader("Etag","\"etag2\""); resp2.setHeader("Cache-Control","max-age=1200"); - final Capture cap = new Capture<>(); + final Capture cap = new Capture<>(); EasyMock.expect(mockBackend.execute( - EasyMock.eq(route), EasyMock.capture(cap), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp2)); + EasyMock.isNull())).andReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req, context, null); verifyMocks(); Assert.assertTrue(HttpTestUtils.semanticallyTransparent(resp2, result)); - final HttpRequest captured = cap.getValue(); + final ClassicHttpRequest captured = cap.getValue(); Assert.assertTrue(HttpTestUtils.equivalent(req, captured)); } @Test public void testCacheIsNotUsedWhenRespondingToRequestWithCacheControlNoCache() throws Exception { - final HttpRequestWrapper req = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req.setHeader("Cache-Control","no-cache"); testCacheIsNotUsedWhenRespondingToRequest(req); } @@ -5314,8 +5176,8 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testCacheIsNotUsedWhenRespondingToRequestWithPragmaNoCache() throws Exception { - final HttpRequestWrapper req = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req.setHeader("Pragma","no-cache"); testCacheIsNotUsedWhenRespondingToRequest(req); } @@ -5330,42 +5192,40 @@ public class TestProtocolRequirements extends AbstractProtocolTest { * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.4 */ protected void testStaleCacheResponseMustBeRevalidatedWithOrigin( - final HttpResponse staleResponse) throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final ClassicHttpResponse staleResponse) throws Exception { + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); backendExpectsAnyRequestAndReturn(staleResponse); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("Cache-Control","max-stale=3600"); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); resp2.setHeader("ETag","\"etag2\""); resp2.setHeader("Cache-Control","max-age=5, must-revalidate"); - final Capture cap = new Capture<>(); + final Capture cap = new Capture<>(); // this request MUST happen EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), EasyMock.capture(cap), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp2)); + EasyMock.isNull())).andReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); verifyMocks(); - final HttpRequest reval = cap.getValue(); + final ClassicHttpRequest reval = cap.getValue(); boolean foundMaxAge0 = false; - for(final Header h : reval.getHeaders("Cache-Control")) { - for(final HeaderElement elt : h.getElements()) { - if ("max-age".equalsIgnoreCase(elt.getName()) + final Iterator it = MessageSupport.iterate(reval, HttpHeaders.CACHE_CONTROL); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + if ("max-age".equalsIgnoreCase(elt.getName()) && "0".equals(elt.getValue())) { - foundMaxAge0 = true; - } + foundMaxAge0 = true; } } Assert.assertTrue(foundMaxAge0); @@ -5374,7 +5234,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testStaleEntryWithMustRevalidateIsNotUsedWithoutRevalidatingWithOrigin() throws Exception { - final HttpResponse response = HttpTestUtils.make200Response(); + final ClassicHttpResponse response = HttpTestUtils.make200Response(); final Date now = new Date(); final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); response.setHeader("Date",DateUtils.formatDate(tenSecondsAgo)); @@ -5390,30 +5250,30 @@ public class TestProtocolRequirements extends AbstractProtocolTest { * for any reason, it MUST generate a 504 (Gateway Timeout) response." */ protected void testGenerates504IfCannotRevalidateStaleResponse( - final HttpResponse staleResponse) throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final ClassicHttpResponse staleResponse) throws Exception { + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); backendExpectsAnyRequestAndReturn(staleResponse); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); backendExpectsAnyRequest().andThrow(new SocketTimeoutException()); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); Assert.assertEquals(HttpStatus.SC_GATEWAY_TIMEOUT, - result.getStatusLine().getStatusCode()); + result.getCode()); } @Test public void testGenerates504IfCannotRevalidateAMustRevalidateEntry() throws Exception { - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); final Date now = new Date(); final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); resp1.setHeader("ETag","\"etag\""); @@ -5433,7 +5293,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { public void testStaleEntryWithProxyRevalidateOnSharedCacheIsNotUsedWithoutRevalidatingWithOrigin() throws Exception { if (config.isSharedCache()) { - final HttpResponse response = HttpTestUtils.make200Response(); + final ClassicHttpResponse response = HttpTestUtils.make200Response(); final Date now = new Date(); final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); response.setHeader("Date",DateUtils.formatDate(tenSecondsAgo)); @@ -5448,7 +5308,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { public void testGenerates504IfSharedCacheCannotRevalidateAProxyRevalidateEntry() throws Exception { if (config.isSharedCache()) { - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); final Date now = new Date(); final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); resp1.setHeader("ETag","\"etag\""); @@ -5469,22 +5329,22 @@ public class TestProtocolRequirements extends AbstractProtocolTest { public void testCacheControlPrivateIsNotCacheableBySharedCache() throws Exception { if (config.isSharedCache()) { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Cache-Control","private,max-age=3600"); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); // this backend request MUST happen backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); verifyMocks(); } } @@ -5493,24 +5353,24 @@ public class TestProtocolRequirements extends AbstractProtocolTest { public void testCacheControlPrivateOnFieldIsNotReturnedBySharedCache() throws Exception { if (config.isSharedCache()) { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("X-Personal","stuff"); resp1.setHeader("Cache-Control","private=\"X-Personal\",s-maxage=3600"); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); // this backend request MAY happen backendExpectsAnyRequestAndReturn(resp2).times(0,1); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); Assert.assertNull(result.getFirstHeader("X-Personal")); } @@ -5527,49 +5387,49 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testNoCacheCannotSatisfyASubsequentRequestWithoutRevalidation() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("ETag","\"etag\""); resp1.setHeader("Cache-Control","no-cache"); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); // this MUST happen backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); verifyMocks(); } @Test public void testNoCacheCannotSatisfyASubsequentRequestWithoutRevalidationEvenWithContraryIndications() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("ETag","\"etag\""); resp1.setHeader("Cache-Control","no-cache,s-maxage=3600"); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("Cache-Control","max-stale=7200"); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); // this MUST happen backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); verifyMocks(); } @@ -5582,34 +5442,32 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testNoCacheOnFieldIsNotReturnedWithoutRevalidation() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("ETag","\"etag\""); resp1.setHeader("X-Stuff","things"); resp1.setHeader("Cache-Control","no-cache=\"X-Stuff\", max-age=3600"); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); resp2.setHeader("ETag","\"etag\""); resp2.setHeader("X-Stuff","things"); resp2.setHeader("Cache-Control","no-cache=\"X-Stuff\",max-age=3600"); - final Capture cap = new Capture<>(); + final Capture cap = new Capture<>(); EasyMock.expect( mockBackend.execute( - EasyMock.eq(route), EasyMock.capture(cap), EasyMock.isA(HttpClientContext.class), - EasyMock.isNull())).andReturn( - Proxies.enhanceResponse(resp2)).times(0,1); + EasyMock.isNull())).andReturn(resp2).times(0,1); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); if (!cap.hasCaptured()) { @@ -5640,7 +5498,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - impl.execute(route, request, context, null); + impl.execute(request, context, null); verifyMocks(); } @@ -5653,7 +5511,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - impl.execute(route, request, context, null); + impl.execute(request, context, null); verifyMocks(); } @@ -5665,7 +5523,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - impl.execute(route, request, context, null); + impl.execute(request, context, null); verifyMocks(); } @@ -5677,7 +5535,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - impl.execute(route, request, context, null); + impl.execute(request, context, null); verifyMocks(); } @@ -5694,12 +5552,13 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); int total_encodings = 0; - for(final Header hdr : result.getHeaders("Content-Encoding")) { - for(final HeaderElement elt : hdr.getElements()) { - switch(total_encodings) { + final Iterator it = MessageSupport.iterate(result, HttpHeaders.CONTENT_ENCODING); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + switch(total_encodings) { case 0: Assert.assertEquals("gzip", elt.getName()); break; @@ -5708,9 +5567,8 @@ public class TestProtocolRequirements extends AbstractProtocolTest { break; default: Assert.fail("too many encodings"); - } - total_encodings++; } + total_encodings++; } Assert.assertEquals(2, total_encodings); } @@ -5722,12 +5580,13 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); int total_encodings = 0; - for(final Header hdr : result.getHeaders("Content-Encoding")) { - for(final HeaderElement elt : hdr.getElements()) { - switch(total_encodings) { + final Iterator it = MessageSupport.iterate(result, HttpHeaders.CONTENT_ENCODING); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + switch(total_encodings) { case 0: Assert.assertEquals("gzip", elt.getName()); break; @@ -5736,9 +5595,8 @@ public class TestProtocolRequirements extends AbstractProtocolTest { break; default: Assert.fail("too many encodings"); - } - total_encodings++; } + total_encodings++; } Assert.assertEquals(2, total_encodings); } @@ -5752,16 +5610,16 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testCacheDoesNotAssumeContentLocationHeaderIndicatesAnotherCacheableResource() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/foo", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/foo"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Cache-Control","public,max-age=3600"); resp1.setHeader("Etag","\"etag\""); resp1.setHeader("Content-Location","http://foo.example.com/bar"); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/bar", HttpVersion.HTTP_1_1), host); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/bar"), route); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); resp2.setHeader("Cache-Control","public,max-age=3600"); resp2.setHeader("Etag","\"etag\""); @@ -5769,8 +5627,8 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); verifyMocks(); } @@ -5790,7 +5648,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); Assert.assertNotNull(result.getFirstHeader("Date")); } @@ -5804,24 +5662,24 @@ public class TestProtocolRequirements extends AbstractProtocolTest { */ private void testInvalidExpiresHeaderIsTreatedAsStale( final String expiresHeader) throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Cache-Control","public"); resp1.setHeader("ETag","\"etag\""); resp1.setHeader("Expires", expiresHeader); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); backendExpectsAnyRequestAndReturn(resp1); // second request to origin MUST happen backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); verifyMocks(); } @@ -5845,24 +5703,24 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testExpiresHeaderEqualToDateHeaderIsTreatedAsStale() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Cache-Control","public"); resp1.setHeader("ETag","\"etag\""); resp1.setHeader("Expires", resp1.getFirstHeader("Date").getValue()); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp2 = HttpTestUtils.make200Response(); backendExpectsAnyRequestAndReturn(resp1); // second request to origin MUST happen backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); verifyMocks(); } @@ -5880,7 +5738,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); Assert.assertEquals(server, result.getFirstHeader("Server").getValue()); } @@ -5899,12 +5757,13 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); int transfer_encodings = 0; - for(final Header h : result.getHeaders("Transfer-Encoding")) { - for(final HeaderElement elt : h.getElements()) { - switch(transfer_encodings) { + final Iterator it = MessageSupport.iterate(result, HttpHeaders.TRANSFER_ENCODING); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + switch(transfer_encodings) { case 0: Assert.assertEquals("chunked",elt.getName()); break; @@ -5913,9 +5772,8 @@ public class TestProtocolRequirements extends AbstractProtocolTest { break; default: Assert.fail("too many transfer encodings"); - } - transfer_encodings++; } + transfer_encodings++; } Assert.assertEquals(2, transfer_encodings); } @@ -5928,12 +5786,13 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); int transfer_encodings = 0; - for(final Header h : result.getHeaders("Transfer-Encoding")) { - for(final HeaderElement elt : h.getElements()) { - switch(transfer_encodings) { + final Iterator it = MessageSupport.iterate(result, HttpHeaders.TRANSFER_ENCODING); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + switch(transfer_encodings) { case 0: Assert.assertEquals("chunked",elt.getName()); break; @@ -5942,9 +5801,8 @@ public class TestProtocolRequirements extends AbstractProtocolTest { break; default: Assert.fail("too many transfer encodings"); - } - transfer_encodings++; } + transfer_encodings++; } Assert.assertEquals(2, transfer_encodings); } @@ -5968,12 +5826,12 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); - for(final Header h : result.getHeaders("Vary")) { - for(final HeaderElement elt : h.getElements()) { - Assert.assertFalse("*".equals(elt.getName())); - } + final Iterator it = MessageSupport.iterate(result, HttpHeaders.VARY); + while (it.hasNext()) { + final HeaderElement elt = it.next(); + Assert.assertFalse("*".equals(elt.getName())); } } @@ -5986,20 +5844,19 @@ public class TestProtocolRequirements extends AbstractProtocolTest { */ @Test public void testProperlyFormattedViaHeaderIsAddedToRequests() throws Exception { - final Capture cap = new Capture<>(); + final Capture cap = new Capture<>(); request.removeHeaders("Via"); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), EasyMock.capture(cap), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - impl.execute(route, request, context, null); + impl.execute(request, context, null); verifyMocks(); - final HttpRequest captured = cap.getValue(); + final ClassicHttpRequest captured = cap.getValue(); final String via = captured.getFirstHeader("Via").getValue(); assertValidViaHeader(via); } @@ -6009,7 +5866,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { originResponse.removeHeaders("Via"); backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); assertValidViaHeader(result.getFirstHeader("Via").getValue()); } @@ -6086,21 +5943,22 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testViaHeaderOnRequestProperlyRecordsClientProtocol() throws Exception { - request = HttpRequestWrapper.wrap(new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_0), host); + final ClassicHttpRequest originalRequest = new BasicClassicHttpRequest("GET", "/"); + originalRequest.setVersion(HttpVersion.HTTP_1_0); + request = RoutedHttpRequest.adapt(originalRequest, route); request.removeHeaders("Via"); - final Capture cap = new Capture<>(); + final Capture cap = new Capture<>(); EasyMock.expect( mockBackend.execute( - EasyMock.isA(HttpRoute.class), EasyMock.capture(cap), EasyMock.isA(HttpClientContext.class), EasyMock.isNull())).andReturn(originResponse); replayMocks(); - impl.execute(route, request, context, null); + impl.execute(request, context, null); verifyMocks(); - final HttpRequest captured = cap.getValue(); + final ClassicHttpRequest captured = cap.getValue(); final String via = captured.getFirstHeader("Via").getValue(); final String protocol = via.split("\\s+")[0]; final String[] protoParts = protocol.split("/"); @@ -6114,13 +5972,13 @@ public class TestProtocolRequirements extends AbstractProtocolTest { public void testViaHeaderOnResponseProperlyRecordsOriginProtocol() throws Exception { - originResponse = Proxies.enhanceResponse( - new BasicHttpResponse(HttpVersion.HTTP_1_0, HttpStatus.SC_NO_CONTENT, "No Content")); + originResponse = new BasicClassicHttpResponse(HttpStatus.SC_NO_CONTENT, "No Content"); + originResponse.setVersion(HttpVersion.HTTP_1_0); backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); final String via = result.getFirstHeader("Via").getValue(); @@ -6148,7 +6006,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); Assert.assertEquals(warning, result.getFirstHeader("Warning").getValue()); @@ -6164,14 +6022,14 @@ public class TestProtocolRequirements extends AbstractProtocolTest { @Test public void testUpdatesWarningHeadersOnValidation() throws Exception { - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); final Date now = new Date(); final Date twentySecondsAgo = new Date(now.getTime() - 20 * 1000L); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Date", DateUtils.formatDate(twentySecondsAgo)); resp1.setHeader("Cache-Control","public,max-age=5"); resp1.setHeader("ETag", "\"etag1\""); @@ -6179,7 +6037,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { resp1.setHeader("Warning", oldWarning); final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); - final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_MODIFIED, "Not Modified"); + final ClassicHttpResponse resp2 = new BasicClassicHttpResponse(HttpStatus.SC_NOT_MODIFIED, "Not Modified"); resp2.setHeader("Date", DateUtils.formatDate(tenSecondsAgo)); resp2.setHeader("ETag", "\"etag1\""); final String newWarning = "113 betty \"stale too\""; @@ -6189,8 +6047,8 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); boolean oldWarningFound = false; @@ -6220,18 +6078,19 @@ public class TestProtocolRequirements extends AbstractProtocolTest { throws Exception { final String dateHdr = DateUtils.formatDate(new Date()); final String origWarning = "110 fred \"stale\""; - originResponse.setStatusLine(HttpVersion.HTTP_1_0, HttpStatus.SC_OK); + originResponse.setCode(HttpStatus.SC_OK); + originResponse.setVersion(HttpVersion.HTTP_1_0); originResponse.addHeader("Warning", origWarning); originResponse.setHeader("Date", dateHdr); backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); // 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.getProtocolVersion())) { + if (HttpVersion.HTTP_1_0.greaterEquals(result.getVersion())) { Assert.assertEquals(dateHdr, result.getFirstHeader("Date").getValue()); boolean warningFound = false; final String targetWarning = origWarning + " \"" + dateHdr + "\""; @@ -6269,7 +6128,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); for(final Header h : result.getHeaders("Warning")) { @@ -6289,7 +6148,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); for(final Header h : result.getHeaders("Warning")) { @@ -6308,7 +6167,7 @@ public class TestProtocolRequirements extends AbstractProtocolTest { backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); - final HttpResponse result = impl.execute(route, request, context, null); + final ClassicHttpResponse result = impl.execute(request, context, null); verifyMocks(); final Header[] warningHeaders = result.getHeaders("Warning"); 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 f4c36b796..8f71ff26c 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 @@ -33,15 +33,14 @@ import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.util.Date; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.utils.DateUtils; +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.HttpResponse; import org.apache.hc.core5.http.HttpStatus; -import org.apache.hc.core5.http.HttpVersion; -import org.apache.hc.core5.http.entity.InputStreamEntity; -import org.apache.hc.core5.http.message.BasicHttpRequest; +import org.apache.hc.core5.http.io.entity.InputStreamEntity; +import org.apache.hc.core5.http.message.BasicClassicHttpRequest; import org.junit.Test; /** @@ -70,20 +69,20 @@ public class TestRFC5861Compliance extends AbstractProtocolTest { public void testStaleIfErrorInResponseIsTrueReturnsStaleEntryWithWarning() throws Exception{ final Date tenSecondsAgo = new Date(new Date().getTime() - 10 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(tenSecondsAgo, + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(tenSecondsAgo, "public, max-age=5, stale-if-error=60"); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); - final HttpResponse resp2 = HttpTestUtils.make500Response(); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); + final ClassicHttpResponse resp2 = HttpTestUtils.make500Response(); backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); HttpTestUtils.assert110WarningFound(result); @@ -93,14 +92,14 @@ public class TestRFC5861Compliance extends AbstractProtocolTest { public void testConsumesErrorResponseWhenServingStale() throws Exception{ final Date tenSecondsAgo = new Date(new Date().getTime() - 10 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(tenSecondsAgo, + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(tenSecondsAgo, "public, max-age=5, stale-if-error=60"); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); - final HttpResponse resp2 = HttpTestUtils.make500Response(); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); + final ClassicHttpResponse resp2 = HttpTestUtils.make500Response(); final byte[] body101 = HttpTestUtils.getRandomBytes(101); final ByteArrayInputStream buf = new ByteArrayInputStream(body101); final ConsumableInputStream cis = new ConsumableInputStream(buf); @@ -110,8 +109,8 @@ public class TestRFC5861Compliance extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + impl.execute(req2, context, null); verifyMocks(); assertTrue(cis.wasClosed()); @@ -121,23 +120,23 @@ public class TestRFC5861Compliance extends AbstractProtocolTest { public void testStaleIfErrorInResponseYieldsToMustRevalidate() throws Exception{ final Date tenSecondsAgo = new Date(new Date().getTime() - 10 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(tenSecondsAgo, + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(tenSecondsAgo, "public, max-age=5, stale-if-error=60, must-revalidate"); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); - final HttpResponse resp2 = HttpTestUtils.make500Response(); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); + final ClassicHttpResponse resp2 = HttpTestUtils.make500Response(); backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - assertTrue(HttpStatus.SC_OK != result.getStatusLine().getStatusCode()); + assertTrue(HttpStatus.SC_OK != result.getCode()); } @Test @@ -145,23 +144,23 @@ public class TestRFC5861Compliance extends AbstractProtocolTest { throws Exception{ assertTrue(config.isSharedCache()); final Date tenSecondsAgo = new Date(new Date().getTime() - 10 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(tenSecondsAgo, + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(tenSecondsAgo, "public, max-age=5, stale-if-error=60, proxy-revalidate"); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); - final HttpResponse resp2 = HttpTestUtils.make500Response(); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); + final ClassicHttpResponse resp2 = HttpTestUtils.make500Response(); backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - assertTrue(HttpStatus.SC_OK != result.getStatusLine().getStatusCode()); + assertTrue(HttpStatus.SC_OK != result.getCode()); } @Test @@ -172,20 +171,20 @@ public class TestRFC5861Compliance extends AbstractProtocolTest { impl = new CachingExec(mockBackend, new BasicHttpCache(configUnshared), configUnshared); final Date tenSecondsAgo = new Date(new Date().getTime() - 10 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(tenSecondsAgo, + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(tenSecondsAgo, "public, max-age=5, stale-if-error=60, proxy-revalidate"); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); - final HttpResponse resp2 = HttpTestUtils.make500Response(); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); + final ClassicHttpResponse resp2 = HttpTestUtils.make500Response(); backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); HttpTestUtils.assert110WarningFound(result); @@ -195,45 +194,45 @@ public class TestRFC5861Compliance extends AbstractProtocolTest { public void testStaleIfErrorInResponseYieldsToExplicitFreshnessRequest() throws Exception{ final Date tenSecondsAgo = new Date(new Date().getTime() - 10 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(tenSecondsAgo, + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(tenSecondsAgo, "public, max-age=5, stale-if-error=60"); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); req2.setHeader("Cache-Control","min-fresh=2"); - final HttpResponse resp2 = HttpTestUtils.make500Response(); + final ClassicHttpResponse resp2 = HttpTestUtils.make500Response(); backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - assertTrue(HttpStatus.SC_OK != result.getStatusLine().getStatusCode()); + assertTrue(HttpStatus.SC_OK != result.getCode()); } @Test public void testStaleIfErrorInRequestIsTrueReturnsStaleEntryWithWarning() throws Exception{ final Date tenSecondsAgo = new Date(new Date().getTime() - 10 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(tenSecondsAgo, + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(tenSecondsAgo, "public, max-age=5"); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); req2.setHeader("Cache-Control","public, stale-if-error=60"); - final HttpResponse resp2 = HttpTestUtils.make500Response(); + final ClassicHttpResponse resp2 = HttpTestUtils.make500Response(); backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); HttpTestUtils.assert110WarningFound(result); @@ -243,22 +242,22 @@ public class TestRFC5861Compliance extends AbstractProtocolTest { public void testStaleIfErrorInRequestIsTrueReturnsStaleNonRevalidatableEntryWithWarning() throws Exception { final Date tenSecondsAgo = new Date(new Date().getTime() - 10 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Date", DateUtils.formatDate(tenSecondsAgo)); resp1.setHeader("Cache-Control", "public, max-age=5"); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); req2.setHeader("Cache-Control", "public, stale-if-error=60"); - final HttpResponse resp2 = HttpTestUtils.make500Response(); + final ClassicHttpResponse resp2 = HttpTestUtils.make500Response(); backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); HttpTestUtils.assert110WarningFound(result); @@ -269,24 +268,24 @@ public class TestRFC5861Compliance extends AbstractProtocolTest { throws Exception{ final Date now = new Date(); final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(tenSecondsAgo, + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(tenSecondsAgo, "public, max-age=5, stale-if-error=2"); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); - final HttpResponse resp2 = HttpTestUtils.make500Response(); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); + final ClassicHttpResponse resp2 = HttpTestUtils.make500Response(); backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, - result.getStatusLine().getStatusCode()); + result.getCode()); } @Test @@ -294,25 +293,25 @@ public class TestRFC5861Compliance extends AbstractProtocolTest { throws Exception{ final Date now = new Date(); final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(tenSecondsAgo, + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(tenSecondsAgo, "public, max-age=5"); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest(), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(HttpTestUtils.makeDefaultRequest(), route); req2.setHeader("Cache-Control","stale-if-error=2"); - final HttpResponse resp2 = HttpTestUtils.make500Response(); + final ClassicHttpResponse resp2 = HttpTestUtils.make500Response(); backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, - result.getStatusLine().getStatusCode()); + result.getCode()); } /* @@ -334,9 +333,9 @@ public class TestRFC5861Compliance extends AbstractProtocolTest { impl = new CachingExec(mockBackend, cache, config, new AsynchronousValidator(config)); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); final Date now = new Date(); final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); resp1.setHeader("Cache-Control", "public, max-age=5, stale-while-revalidate=15"); @@ -345,15 +344,15 @@ public class TestRFC5861Compliance extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp1).times(1,2); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - assertEquals(HttpStatus.SC_OK, result.getStatusLine().getStatusCode()); + assertEquals(HttpStatus.SC_OK, result.getCode()); boolean warning110Found = false; for(final Header h : result.getHeaders("Warning")) { for(final WarningValue wv : WarningValue.getWarningValues(h)) { @@ -379,9 +378,8 @@ public class TestRFC5861Compliance extends AbstractProtocolTest { impl = new CachingExec(mockBackend, cache, config, new AsynchronousValidator(config)); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new BasicHttpRequest("GET", "/", - HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); final Date now = new Date(); final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); resp1.setHeader("Cache-Control", "public, max-age=5, stale-while-revalidate=15"); @@ -389,15 +387,14 @@ public class TestRFC5861Compliance extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp1).times(1, 2); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new BasicHttpRequest("GET", "/", - HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt(new BasicClassicHttpRequest("GET", "/"), route); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - assertEquals(HttpStatus.SC_OK, result.getStatusLine().getStatusCode()); + assertEquals(HttpStatus.SC_OK, result.getCode()); boolean warning110Found = false; for (final Header h : result.getHeaders("Warning")) { for (final WarningValue wv : WarningValue.getWarningValues(h)) { @@ -422,9 +419,9 @@ public class TestRFC5861Compliance extends AbstractProtocolTest { .build(); impl = new CachingExec(mockBackend, cache, config, new AsynchronousValidator(config)); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(); final Date now = new Date(); final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); resp1.setHeader("Cache-Control", "private, stale-while-revalidate=15"); @@ -433,16 +430,16 @@ public class TestRFC5861Compliance extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp1).times(1,2); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("If-None-Match","\"etag\""); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getStatusLine().getStatusCode()); + assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getCode()); boolean warning110Found = false; for(final Header h : result.getHeaders("Warning")) { for(final WarningValue wv : WarningValue.getWarningValues(h)) { @@ -470,18 +467,18 @@ public class TestRFC5861Compliance extends AbstractProtocolTest { .build(); impl = new CachingExec(mockBackend, cache, config); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + 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.formatDate(tenSecondsAgo)); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + 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.formatDate(now)); @@ -489,11 +486,11 @@ public class TestRFC5861Compliance extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - assertEquals(HttpStatus.SC_OK, result.getStatusLine().getStatusCode()); + assertEquals(HttpStatus.SC_OK, result.getCode()); boolean warning110Found = false; for(final Header h : result.getHeaders("Warning")) { for(final WarningValue wv : WarningValue.getWarningValues(h)) { @@ -521,18 +518,18 @@ public class TestRFC5861Compliance extends AbstractProtocolTest { .build(); impl = new CachingExec(mockBackend, cache, config); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + 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.formatDate(tenSecondsAgo)); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + 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.formatDate(now)); @@ -540,11 +537,11 @@ public class TestRFC5861Compliance extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - assertEquals(HttpStatus.SC_OK, result.getStatusLine().getStatusCode()); + assertEquals(HttpStatus.SC_OK, result.getCode()); boolean warning110Found = false; for(final Header h : result.getHeaders("Warning")) { for(final WarningValue wv : WarningValue.getWarningValues(h)) { @@ -572,19 +569,19 @@ public class TestRFC5861Compliance extends AbstractProtocolTest { .build(); impl = new CachingExec(mockBackend, cache, config); - final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); - final HttpResponse resp1 = HttpTestUtils.make200Response(); + final RoutedHttpRequest req1 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); + 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.formatDate(tenSecondsAgo)); backendExpectsAnyRequestAndReturn(resp1); - final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1), host); + final RoutedHttpRequest req2 = RoutedHttpRequest.adapt( + new BasicClassicHttpRequest("GET", "/"), route); req2.setHeader("Cache-Control","min-fresh=2"); - final HttpResponse resp2 = HttpTestUtils.make200Response(); + 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.formatDate(now)); @@ -592,11 +589,11 @@ public class TestRFC5861Compliance extends AbstractProtocolTest { backendExpectsAnyRequestAndReturn(resp2); replayMocks(); - impl.execute(route, req1, context, null); - final HttpResponse result = impl.execute(route, req2, context, null); + impl.execute(req1, context, null); + final ClassicHttpResponse result = impl.execute(req2, context, null); verifyMocks(); - assertEquals(HttpStatus.SC_OK, result.getStatusLine().getStatusCode()); + assertEquals(HttpStatus.SC_OK, result.getCode()); boolean warning110Found = false; for(final Header h : result.getHeaders("Warning")) { for(final WarningValue wv : WarningValue.getWarningValues(h)) { 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 index 997241cb4..a6b21fa7f 100644 --- 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 @@ -32,25 +32,26 @@ import static org.junit.Assert.assertTrue; import java.util.Arrays; +import org.apache.hc.client5.http.HttpRoute; import org.apache.hc.client5.http.methods.HttpPut; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; +import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.HttpHost; -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.message.BasicClassicHttpRequest; import org.junit.Before; import org.junit.Test; public class TestRequestProtocolCompliance { - private HttpHost host; + private HttpRoute route; private RequestProtocolCompliance impl; - private HttpRequest req; + private ClassicHttpRequest req; @Before public void setUp() { - host = new HttpHost("foo.example.com", 80); + route = new HttpRoute(new HttpHost("foo.example.com", 80)); req = HttpTestUtils.makeDefaultRequest(); impl = new RequestProtocolCompliance(false); } @@ -85,43 +86,44 @@ public class TestRequestProtocolCompliance { @Test public void doesNotModifyACompliantRequest() throws Exception { - final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(req, host); + final RoutedHttpRequest wrapper = RoutedHttpRequest.adapt(req, route); impl.makeRequestCompliant(wrapper); assertTrue(HttpTestUtils.equivalent(req, wrapper)); } @Test public void removesEntityFromTRACERequest() throws Exception { - final HttpRequest request = - new BasicHttpRequest("TRACE", "/", HttpVersion.HTTP_1_1); + final ClassicHttpRequest request = new BasicClassicHttpRequest("TRACE", "/"); + request.setVersion(HttpVersion.HTTP_1_1); request.setEntity(HttpTestUtils.makeBody(50)); - final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(request, host); + final RoutedHttpRequest wrapper = RoutedHttpRequest.adapt(request, route); impl.makeRequestCompliant(wrapper); assertNull(wrapper.getEntity()); } @Test public void upgrades1_0RequestTo1_1() throws Exception { - req = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_0); - final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(req, host); + req = new BasicClassicHttpRequest("GET", "/"); + req.setVersion(HttpVersion.HTTP_1_0); + final RoutedHttpRequest wrapper = RoutedHttpRequest.adapt(req, route); impl.makeRequestCompliant(wrapper); - assertEquals(HttpVersion.HTTP_1_1, wrapper.getProtocolVersion()); + assertEquals(HttpVersion.HTTP_1_1, wrapper.getVersion()); } @Test public void downgrades1_2RequestTo1_1() throws Exception { - final ProtocolVersion HTTP_1_2 = new ProtocolVersion("HTTP", 1, 2); - req = new BasicHttpRequest("GET", "/", HTTP_1_2); - final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(req, host); + req = new BasicClassicHttpRequest("GET", "/"); + req.setVersion(new ProtocolVersion("HTTP", 1, 2)); + final RoutedHttpRequest wrapper = RoutedHttpRequest.adapt(req, route); impl.makeRequestCompliant(wrapper); - assertEquals(HttpVersion.HTTP_1_1, wrapper.getProtocolVersion()); + assertEquals(HttpVersion.HTTP_1_1, wrapper.getVersion()); } @Test public void stripsMinFreshFromRequestIfNoCachePresent() throws Exception { req.setHeader("Cache-Control", "no-cache, min-fresh=10"); - final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(req, host); + final RoutedHttpRequest wrapper = RoutedHttpRequest.adapt(req, route); impl.makeRequestCompliant(wrapper); assertEquals("no-cache", wrapper.getFirstHeader("Cache-Control").getValue()); @@ -131,7 +133,7 @@ public class TestRequestProtocolCompliance { public void stripsMaxFreshFromRequestIfNoCachePresent() throws Exception { req.setHeader("Cache-Control", "no-cache, max-stale=10"); - final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(req, host); + final RoutedHttpRequest wrapper = RoutedHttpRequest.adapt(req, route); impl.makeRequestCompliant(wrapper); assertEquals("no-cache", wrapper.getFirstHeader("Cache-Control").getValue()); @@ -141,7 +143,7 @@ public class TestRequestProtocolCompliance { public void stripsMaxAgeFromRequestIfNoCachePresent() throws Exception { req.setHeader("Cache-Control", "no-cache, max-age=10"); - final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(req, host); + final RoutedHttpRequest wrapper = RoutedHttpRequest.adapt(req, route); impl.makeRequestCompliant(wrapper); assertEquals("no-cache", wrapper.getFirstHeader("Cache-Control").getValue()); @@ -151,7 +153,7 @@ public class TestRequestProtocolCompliance { public void doesNotStripMinFreshFromRequestWithoutNoCache() throws Exception { req.setHeader("Cache-Control", "min-fresh=10"); - final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(req, host); + final RoutedHttpRequest wrapper = RoutedHttpRequest.adapt(req, route); impl.makeRequestCompliant(wrapper); assertEquals("min-fresh=10", wrapper.getFirstHeader("Cache-Control").getValue()); @@ -161,7 +163,7 @@ public class TestRequestProtocolCompliance { public void correctlyStripsMinFreshFromMiddleIfNoCache() throws Exception { req.setHeader("Cache-Control", "no-cache,min-fresh=10,no-store"); - final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(req, host); + final RoutedHttpRequest wrapper = RoutedHttpRequest.adapt(req, route); impl.makeRequestCompliant(wrapper); assertEquals("no-cache,no-store", wrapper.getFirstHeader("Cache-Control").getValue()); 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 6d77401d1..096e8eb99 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 @@ -38,7 +38,6 @@ 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.message.BasicHttpResponse; -import org.apache.hc.core5.http.message.BasicStatusLine; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -63,9 +62,8 @@ public class TestResponseCachingPolicy { tenSecondsFromNow = new Date(now.getTime() + 10 * 1000L); policy = new ResponseCachingPolicy(0, true, false, false); - request = new BasicHttpRequest("GET","/",HTTP_1_1); - response = new BasicHttpResponse( - new BasicStatusLine(HTTP_1_1, HttpStatus.SC_OK, "")); + request = new BasicHttpRequest("GET","/"); + response = new BasicHttpResponse(HttpStatus.SC_OK, ""); response.setHeader("Date", DateUtils.formatDate(new Date())); response.setHeader("Content-Length", "0"); } @@ -83,7 +81,7 @@ public class TestResponseCachingPolicy { @Test public void testResponsesToRequestsWithAuthorizationHeadersAreNotCacheableBySharedCache() { - request = new BasicHttpRequest("GET","/",HTTP_1_1); + request = new BasicHttpRequest("GET","/"); request.setHeader("Authorization","Basic dXNlcjpwYXNzd2Q="); Assert.assertFalse(policy.isResponseCacheable(request,response)); } @@ -91,14 +89,14 @@ public class TestResponseCachingPolicy { @Test public void testResponsesToRequestsWithAuthorizationHeadersAreCacheableByNonSharedCache() { policy = new ResponseCachingPolicy(0, false, false, false); - request = new BasicHttpRequest("GET","/",HTTP_1_1); + request = new BasicHttpRequest("GET","/"); request.setHeader("Authorization","Basic dXNlcjpwYXNzd2Q="); Assert.assertTrue(policy.isResponseCacheable(request,response)); } @Test public void testAuthorizedResponsesWithSMaxAgeAreCacheable() { - request = new BasicHttpRequest("GET","/",HTTP_1_1); + request = new BasicHttpRequest("GET","/"); request.setHeader("Authorization","Basic dXNlcjpwYXNzd2Q="); response.setHeader("Cache-Control","s-maxage=3600"); Assert.assertTrue(policy.isResponseCacheable(request,response)); @@ -106,7 +104,7 @@ public class TestResponseCachingPolicy { @Test public void testAuthorizedResponsesWithMustRevalidateAreCacheable() { - request = new BasicHttpRequest("GET","/",HTTP_1_1); + request = new BasicHttpRequest("GET","/"); request.setHeader("Authorization","Basic dXNlcjpwYXNzd2Q="); response.setHeader("Cache-Control","must-revalidate"); Assert.assertTrue(policy.isResponseCacheable(request,response)); @@ -114,7 +112,7 @@ public class TestResponseCachingPolicy { @Test public void testAuthorizedResponsesWithCacheControlPublicAreCacheable() { - request = new BasicHttpRequest("GET","/",HTTP_1_1); + request = new BasicHttpRequest("GET","/"); request.setHeader("Authorization","Basic dXNlcjpwYXNzd2Q="); response.setHeader("Cache-Control","public"); Assert.assertTrue(policy.isResponseCacheable(request,response)); @@ -122,7 +120,7 @@ public class TestResponseCachingPolicy { @Test public void testAuthorizedResponsesWithCacheControlMaxAgeAreNotCacheable() { - request = new BasicHttpRequest("GET","/",HTTP_1_1); + request = new BasicHttpRequest("GET","/"); request.setHeader("Authorization","Basic dXNlcjpwYXNzd2Q="); response.setHeader("Cache-Control","max-age=3600"); Assert.assertFalse(policy.isResponseCacheable(request,response)); @@ -130,13 +128,13 @@ public class TestResponseCachingPolicy { @Test public void test203ResponseCodeIsCacheable() { - response.setStatusCode(HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION); + response.setCode(HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION); Assert.assertTrue(policy.isResponseCacheable("GET", response)); } @Test public void test206ResponseCodeIsNotCacheable() { - response.setStatusCode(HttpStatus.SC_PARTIAL_CONTENT); + response.setCode(HttpStatus.SC_PARTIAL_CONTENT); Assert.assertFalse(policy.isResponseCacheable("GET", response)); } @@ -145,32 +143,32 @@ public class TestResponseCachingPolicy { policy = new ResponseCachingPolicy(0, true, false, false); request.setHeader("Authorization", "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); - response.setStatusCode(HttpStatus.SC_PARTIAL_CONTENT); + response.setCode(HttpStatus.SC_PARTIAL_CONTENT); response.setHeader("Cache-Control", "public"); Assert.assertFalse(policy.isResponseCacheable(request, response)); } @Test public void test300ResponseCodeIsCacheable() { - response.setStatusCode(HttpStatus.SC_MULTIPLE_CHOICES); + response.setCode(HttpStatus.SC_MULTIPLE_CHOICES); Assert.assertTrue(policy.isResponseCacheable("GET", response)); } @Test public void test301ResponseCodeIsCacheable() { - response.setStatusCode(HttpStatus.SC_MOVED_PERMANENTLY); + response.setCode(HttpStatus.SC_MOVED_PERMANENTLY); Assert.assertTrue(policy.isResponseCacheable("GET", response)); } @Test public void test410ResponseCodeIsCacheable() { - response.setStatusCode(HttpStatus.SC_GONE); + response.setCode(HttpStatus.SC_GONE); Assert.assertTrue(policy.isResponseCacheable("GET", response)); } @Test public void testPlain302ResponseCodeIsNotCacheable() { - response.setStatusCode(HttpStatus.SC_MOVED_TEMPORARILY); + response.setCode(HttpStatus.SC_MOVED_TEMPORARILY); response.removeHeaders("Expires"); response.removeHeaders("Cache-Control"); Assert.assertFalse(policy.isResponseCacheable("GET", response)); @@ -178,7 +176,7 @@ public class TestResponseCachingPolicy { @Test public void testPlain303ResponseCodeIsNotCacheableUnderDefaultBehavior() { - response.setStatusCode(HttpStatus.SC_SEE_OTHER); + response.setCode(HttpStatus.SC_SEE_OTHER); response.removeHeaders("Expires"); response.removeHeaders("Cache-Control"); Assert.assertFalse(policy.isResponseCacheable("GET", response)); @@ -187,7 +185,7 @@ public class TestResponseCachingPolicy { @Test public void testPlain303ResponseCodeIsNotCacheableEvenIf303CachingEnabled() { policy = new ResponseCachingPolicy(0, true, false, true); - response.setStatusCode(HttpStatus.SC_SEE_OTHER); + response.setCode(HttpStatus.SC_SEE_OTHER); response.removeHeaders("Expires"); response.removeHeaders("Cache-Control"); Assert.assertFalse(policy.isResponseCacheable("GET", response)); @@ -196,7 +194,7 @@ public class TestResponseCachingPolicy { @Test public void testPlain307ResponseCodeIsNotCacheable() { - response.setStatusCode(HttpStatus.SC_TEMPORARY_REDIRECT); + response.setCode(HttpStatus.SC_TEMPORARY_REDIRECT); response.removeHeaders("Expires"); response.removeHeaders("Cache-Control"); Assert.assertFalse(policy.isResponseCacheable("GET", response)); @@ -205,7 +203,7 @@ public class TestResponseCachingPolicy { @Test public void testNon206WithExplicitExpiresIsCacheable() { final int status = getRandomStatus(); - response.setStatusCode(status); + response.setCode(status); response.setHeader("Expires", DateUtils.formatDate(new Date())); Assert.assertTrue(policy.isResponseCacheable("GET", response)); } @@ -213,7 +211,7 @@ public class TestResponseCachingPolicy { @Test public void testNon206WithMaxAgeIsCacheable() { final int status = getRandomStatus(); - response.setStatusCode(status); + response.setCode(status); response.setHeader("Cache-Control", "max-age=0"); Assert.assertTrue(policy.isResponseCacheable("GET", response)); } @@ -221,7 +219,7 @@ public class TestResponseCachingPolicy { @Test public void testNon206WithSMaxAgeIsCacheable() { final int status = getRandomStatus(); - response.setStatusCode(status); + response.setCode(status); response.setHeader("Cache-Control", "s-maxage=0"); Assert.assertTrue(policy.isResponseCacheable("GET", response)); } @@ -229,7 +227,7 @@ public class TestResponseCachingPolicy { @Test public void testNon206WithMustRevalidateIsCacheable() { final int status = getRandomStatus(); - response.setStatusCode(status); + response.setCode(status); response.setHeader("Cache-Control", "must-revalidate"); Assert.assertTrue(policy.isResponseCacheable("GET", response)); } @@ -237,7 +235,7 @@ public class TestResponseCachingPolicy { @Test public void testNon206WithProxyRevalidateIsCacheable() { final int status = getRandomStatus(); - response.setStatusCode(status); + response.setCode(status); response.setHeader("Cache-Control", "proxy-revalidate"); Assert.assertTrue(policy.isResponseCacheable("GET", response)); } @@ -245,7 +243,7 @@ public class TestResponseCachingPolicy { @Test public void testNon206WithPublicCacheControlIsCacheable() { final int status = getRandomStatus(); - response.setStatusCode(status); + response.setCode(status); response.setHeader("Cache-Control", "public"); Assert.assertTrue(policy.isResponseCacheable("GET", response)); } @@ -253,7 +251,7 @@ public class TestResponseCachingPolicy { @Test public void testNon206WithPrivateCacheControlIsNotCacheableBySharedCache() { final int status = getRandomStatus(); - response.setStatusCode(status); + response.setCode(status); response.setHeader("Cache-Control", "private"); Assert.assertFalse(policy.isResponseCacheable("GET", response)); } @@ -261,7 +259,7 @@ public class TestResponseCachingPolicy { @Test public void test200ResponseWithPrivateCacheControlIsCacheableByNonSharedCache() { policy = new ResponseCachingPolicy(0, false, false, false); - response.setStatusCode(HttpStatus.SC_OK); + response.setCode(HttpStatus.SC_OK); response.setHeader("Cache-Control", "private"); Assert.assertTrue(policy.isResponseCacheable("GET", response)); } @@ -360,8 +358,7 @@ public class TestResponseCachingPolicy { Assert.assertTrue(policy.isResponseCacheable("GET", response)); - response = new BasicHttpResponse( - new BasicStatusLine(HTTP_1_1, HttpStatus.SC_OK, "")); + response = new BasicHttpResponse(HttpStatus.SC_OK, ""); response.setHeader("Date", DateUtils.formatDate(new Date())); response.addHeader("Cache-Control", "no-transform"); response.setHeader("Content-Length", "0"); @@ -376,8 +373,7 @@ public class TestResponseCachingPolicy { Assert.assertTrue(policy.isResponseCacheable("HEAD", response)); - response = new BasicHttpResponse( - new BasicStatusLine(HTTP_1_1, HttpStatus.SC_OK, "")); + response = new BasicHttpResponse(HttpStatus.SC_OK, ""); response.setHeader("Date", DateUtils.formatDate(new Date())); response.addHeader("Cache-Control", "no-transform"); response.setHeader("Content-Length", "0"); @@ -387,26 +383,22 @@ public class TestResponseCachingPolicy { @Test public void testIsGetWithout200Cacheable() { - HttpResponse response404 = new BasicHttpResponse(new BasicStatusLine(HTTP_1_1, - HttpStatus.SC_NOT_FOUND, "")); + HttpResponse response404 = new BasicHttpResponse(HttpStatus.SC_NOT_FOUND, ""); Assert.assertFalse(policy.isResponseCacheable("GET", response404)); - response404 = new BasicHttpResponse(new BasicStatusLine(HTTP_1_1, - HttpStatus.SC_GATEWAY_TIMEOUT, "")); + response404 = new BasicHttpResponse(HttpStatus.SC_GATEWAY_TIMEOUT, ""); Assert.assertFalse(policy.isResponseCacheable("GET", response404)); } @Test public void testIsHeadWithout200Cacheable() { - HttpResponse response404 = new BasicHttpResponse(new BasicStatusLine(HTTP_1_1, - HttpStatus.SC_NOT_FOUND, "")); + HttpResponse response404 = new BasicHttpResponse(HttpStatus.SC_NOT_FOUND, ""); Assert.assertFalse(policy.isResponseCacheable("HEAD", response404)); - response404 = new BasicHttpResponse(new BasicStatusLine(HTTP_1_1, - HttpStatus.SC_GATEWAY_TIMEOUT, "")); + response404 = new BasicHttpResponse(HttpStatus.SC_GATEWAY_TIMEOUT, ""); Assert.assertFalse(policy.isResponseCacheable("HEAD", response404)); } @@ -454,7 +446,7 @@ public class TestResponseCachingPolicy { request = new HttpOptions("http://foo.example.com/"); request.setHeader("Authorization", "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); - response.setStatusCode(HttpStatus.SC_NO_CONTENT); + response.setCode(HttpStatus.SC_NO_CONTENT); response.setHeader("Cache-Control", "public"); Assert.assertFalse(policy.isResponseCacheable(request, response)); @@ -629,14 +621,16 @@ public class TestResponseCachingPolicy { @Test public void getsWithQueryParametersDirectlyFrom1_0OriginsAreNotCacheable() { request = new BasicHttpRequest("GET", "/foo?s=bar"); - response = new BasicHttpResponse(HttpVersion.HTTP_1_0, HttpStatus.SC_OK, "OK"); + response = new BasicHttpResponse(HttpStatus.SC_OK, "OK"); + response.setVersion(HttpVersion.HTTP_1_0); Assert.assertFalse(policy.isResponseCacheable(request, response)); } @Test public void headsWithQueryParametersDirectlyFrom1_0OriginsAreNotCacheable() { request = new BasicHttpRequest("HEAD", "/foo?s=bar"); - response = new BasicHttpResponse(HttpVersion.HTTP_1_0, HttpStatus.SC_OK, "OK"); + response = new BasicHttpResponse(HttpStatus.SC_OK, "OK"); + response.setVersion(HttpVersion.HTTP_1_0); Assert.assertFalse(policy.isResponseCacheable(request, response)); } @@ -644,7 +638,8 @@ public class TestResponseCachingPolicy { public void getsWithQueryParametersDirectlyFrom1_0OriginsAreNotCacheableEvenWithSetting() { policy = new ResponseCachingPolicy(0, true, true, false); request = new BasicHttpRequest("GET", "/foo?s=bar"); - response = new BasicHttpResponse(HttpVersion.HTTP_1_0, HttpStatus.SC_OK, "OK"); + response = new BasicHttpResponse(HttpStatus.SC_OK, "OK"); + response.setVersion(HttpVersion.HTTP_1_0); Assert.assertFalse(policy.isResponseCacheable(request, response)); } @@ -652,14 +647,16 @@ public class TestResponseCachingPolicy { public void headsWithQueryParametersDirectlyFrom1_0OriginsAreNotCacheableEvenWithSetting() { policy = new ResponseCachingPolicy(0, true, true, false); request = new BasicHttpRequest("HEAD", "/foo?s=bar"); - response = new BasicHttpResponse(HttpVersion.HTTP_1_0, HttpStatus.SC_OK, "OK"); + response = new BasicHttpResponse(HttpStatus.SC_OK, "OK"); + response.setVersion(HttpVersion.HTTP_1_0); Assert.assertFalse(policy.isResponseCacheable(request, response)); } @Test public void getsWithQueryParametersDirectlyFrom1_0OriginsAreCacheableWithExpires() { request = new BasicHttpRequest("GET", "/foo?s=bar"); - response = new BasicHttpResponse(HttpVersion.HTTP_1_0, HttpStatus.SC_OK, "OK"); + response = new BasicHttpResponse(HttpStatus.SC_OK, "OK"); + response.setVersion(HttpVersion.HTTP_1_0); response.setHeader("Date", DateUtils.formatDate(now)); response.setHeader("Expires", DateUtils.formatDate(tenSecondsFromNow)); Assert.assertTrue(policy.isResponseCacheable(request, response)); @@ -669,7 +666,8 @@ public class TestResponseCachingPolicy { public void headsWithQueryParametersDirectlyFrom1_0OriginsAreCacheableWithExpires() { policy = new ResponseCachingPolicy(0, true, false, false); request = new BasicHttpRequest("HEAD", "/foo?s=bar"); - response = new BasicHttpResponse(HttpVersion.HTTP_1_0, HttpStatus.SC_OK, "OK"); + response = new BasicHttpResponse(HttpStatus.SC_OK, "OK"); + response.setVersion(HttpVersion.HTTP_1_0); response.setHeader("Date", DateUtils.formatDate(now)); response.setHeader("Expires", DateUtils.formatDate(tenSecondsFromNow)); Assert.assertTrue(policy.isResponseCacheable(request, response)); @@ -679,7 +677,8 @@ public class TestResponseCachingPolicy { public void getsWithQueryParametersDirectlyFrom1_0OriginsCanBeNotCacheableEvenWithExpires() { policy = new ResponseCachingPolicy(0, true, true, false); request = new BasicHttpRequest("GET", "/foo?s=bar"); - response = new BasicHttpResponse(HttpVersion.HTTP_1_0, HttpStatus.SC_OK, "OK"); + response = new BasicHttpResponse(HttpStatus.SC_OK, "OK"); + response.setVersion(HttpVersion.HTTP_1_0); response.setHeader("Date", DateUtils.formatDate(now)); response.setHeader("Expires", DateUtils.formatDate(tenSecondsFromNow)); Assert.assertFalse(policy.isResponseCacheable(request, response)); @@ -689,7 +688,8 @@ public class TestResponseCachingPolicy { public void headsWithQueryParametersDirectlyFrom1_0OriginsCanBeNotCacheableEvenWithExpires() { policy = new ResponseCachingPolicy(0, true, true, false); request = new BasicHttpRequest("HEAD", "/foo?s=bar"); - response = new BasicHttpResponse(HttpVersion.HTTP_1_0, HttpStatus.SC_OK, "OK"); + response = new BasicHttpResponse(HttpStatus.SC_OK, "OK"); + response.setVersion(HttpVersion.HTTP_1_0); response.setHeader("Date", DateUtils.formatDate(now)); response.setHeader("Expires", DateUtils.formatDate(tenSecondsFromNow)); Assert.assertFalse(policy.isResponseCacheable(request, response)); @@ -790,7 +790,8 @@ public class TestResponseCachingPolicy { @Test public void getsWithQueryParametersFrom1_1OriginsVia1_0ProxiesAreCacheableWithExpires() { request = new BasicHttpRequest("GET", "/foo?s=bar"); - response = new BasicHttpResponse(HttpVersion.HTTP_1_0, HttpStatus.SC_OK, "OK"); + response = new BasicHttpResponse(HttpStatus.SC_OK, "OK"); + response.setVersion(HttpVersion.HTTP_1_0); response.setHeader("Date", DateUtils.formatDate(now)); response.setHeader("Expires", DateUtils.formatDate(tenSecondsFromNow)); response.setHeader("Via", "1.1 someproxy"); @@ -801,7 +802,8 @@ public class TestResponseCachingPolicy { public void headsWithQueryParametersFrom1_1OriginsVia1_0ProxiesAreCacheableWithExpires() { policy = new ResponseCachingPolicy(0, true, false, false); request = new BasicHttpRequest("HEAD", "/foo?s=bar"); - response = new BasicHttpResponse(HttpVersion.HTTP_1_0, HttpStatus.SC_OK, "OK"); + response = new BasicHttpResponse(HttpStatus.SC_OK, "OK"); + response.setVersion(HttpVersion.HTTP_1_0); response.setHeader("Date", DateUtils.formatDate(now)); response.setHeader("Expires", DateUtils.formatDate(tenSecondsFromNow)); response.setHeader("Via", "1.1 someproxy"); @@ -826,7 +828,7 @@ public class TestResponseCachingPolicy { @Test public void test302WithExplicitCachingHeaders() { - response.setStatusCode(HttpStatus.SC_MOVED_TEMPORARILY); + response.setCode(HttpStatus.SC_MOVED_TEMPORARILY); response.setHeader("Date", DateUtils.formatDate(now)); response.setHeader("Cache-Control","max-age=300"); Assert.assertTrue(policy.isResponseCacheable(request, response)); @@ -835,7 +837,7 @@ public class TestResponseCachingPolicy { @Test public void test303WithExplicitCachingHeadersUnderDefaultBehavior() { // RFC 2616 says: 303 should not be cached - response.setStatusCode(HttpStatus.SC_SEE_OTHER); + response.setCode(HttpStatus.SC_SEE_OTHER); response.setHeader("Date", DateUtils.formatDate(now)); response.setHeader("Cache-Control","max-age=300"); Assert.assertFalse(policy.isResponseCacheable(request, response)); @@ -846,7 +848,7 @@ public class TestResponseCachingPolicy { // HTTPbis working group says ok if explicitly indicated by // response headers policy = new ResponseCachingPolicy(0, true, false, true); - response.setStatusCode(HttpStatus.SC_SEE_OTHER); + response.setCode(HttpStatus.SC_SEE_OTHER); response.setHeader("Date", DateUtils.formatDate(now)); response.setHeader("Cache-Control","max-age=300"); Assert.assertTrue(policy.isResponseCacheable(request, response)); @@ -854,7 +856,7 @@ public class TestResponseCachingPolicy { @Test public void test307WithExplicitCachingHeaders() { - response.setStatusCode(HttpStatus.SC_TEMPORARY_REDIRECT); + response.setCode(HttpStatus.SC_TEMPORARY_REDIRECT); response.setHeader("Date", DateUtils.formatDate(now)); response.setHeader("Cache-Control","max-age=300"); Assert.assertTrue(policy.isResponseCacheable(request, response)); @@ -862,7 +864,7 @@ public class TestResponseCachingPolicy { @Test public void otherStatusCodesAreCacheableWithExplicitCachingHeaders() { - response.setStatusCode(HttpStatus.SC_NOT_FOUND); + response.setCode(HttpStatus.SC_NOT_FOUND); response.setHeader("Date", DateUtils.formatDate(now)); response.setHeader("Cache-Control","max-age=300"); Assert.assertTrue(policy.isResponseCacheable(request, response)); 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 2df1eb63c..43043e79a 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 @@ -32,32 +32,32 @@ import static junit.framework.TestCase.assertTrue; import java.io.ByteArrayInputStream; import java.util.Date; +import org.apache.hc.client5.http.HttpRoute; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.client5.http.methods.HttpHead; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.ClientProtocolException; 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.HttpEntity; import org.apache.hc.core5.http.HttpHost; -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.HttpVersion; -import org.apache.hc.core5.http.entity.ByteArrayEntity; -import org.apache.hc.core5.http.entity.InputStreamEntity; -import org.apache.hc.core5.http.message.BasicHttpRequest; -import org.apache.hc.core5.http.message.BasicHttpResponse; +import org.apache.hc.core5.http.io.entity.ByteArrayEntity; +import org.apache.hc.core5.http.io.entity.InputStreamEntity; +import org.apache.hc.core5.http.message.BasicClassicHttpRequest; +import org.apache.hc.core5.http.message.BasicClassicHttpResponse; import org.junit.Before; import org.junit.Test; public class TestResponseProtocolCompliance { - private HttpHost host; + private HttpRoute route; private ResponseProtocolCompliance impl; @Before public void setUp() { - host = new HttpHost("foo.example.com", 80); + route = new HttpRoute(new HttpHost("foo.example.com", 80)); impl = new ResponseProtocolCompliance(); } @@ -65,7 +65,7 @@ public class TestResponseProtocolCompliance { public boolean set; } - private void setMinimalResponseHeaders(final HttpResponse resp) { + private void setMinimalResponseHeaders(final ClassicHttpResponse resp) { resp.setHeader("Date", DateUtils.formatDate(new Date())); resp.setHeader("Server", "MyServer/1.0"); } @@ -81,8 +81,8 @@ public class TestResponseProtocolCompliance { return bais; } - private HttpResponse makePartialResponse(final int nbytes) { - final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); + private ClassicHttpResponse makePartialResponse(final int nbytes) { + final ClassicHttpResponse resp = new BasicClassicHttpResponse(HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); setMinimalResponseHeaders(resp); resp.setHeader("Content-Length","" + nbytes); resp.setHeader("Content-Range","0-127/256"); @@ -91,9 +91,9 @@ public class TestResponseProtocolCompliance { @Test public void consumesBodyIfOriginSendsOneInResponseToHEAD() throws Exception { - final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(new HttpHead("http://foo.example.com/"), host); + final RoutedHttpRequest wrapper = RoutedHttpRequest.adapt(new HttpHead("http://foo.example.com/"), route);; final int nbytes = 128; - final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); + final ClassicHttpResponse resp = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); setMinimalResponseHeaders(resp); resp.setHeader("Content-Length","" + nbytes); @@ -108,9 +108,9 @@ public class TestResponseProtocolCompliance { @Test(expected=ClientProtocolException.class) public void throwsExceptionIfOriginReturnsPartialResponseWhenNotRequested() throws Exception { - final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(new HttpGet("http://foo.example.com/"), host); + final RoutedHttpRequest wrapper = RoutedHttpRequest.adapt(new HttpGet("http://foo.example.com/"), route);; final int nbytes = 128; - final HttpResponse resp = makePartialResponse(nbytes); + final ClassicHttpResponse resp = makePartialResponse(nbytes); resp.setEntity(HttpTestUtils.makeBody(nbytes)); impl.ensureProtocolCompliance(wrapper, resp); @@ -118,9 +118,9 @@ public class TestResponseProtocolCompliance { @Test public void consumesPartialContentFromOriginEvenIfNotRequested() throws Exception { - final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(new HttpGet("http://foo.example.com/"), host); + final RoutedHttpRequest wrapper = RoutedHttpRequest.adapt(new HttpGet("http://foo.example.com/"), route);; final int nbytes = 128; - final HttpResponse resp = makePartialResponse(nbytes); + final ClassicHttpResponse resp = makePartialResponse(nbytes); final Flag closed = new Flag(); final ByteArrayInputStream bais = makeTrackableBody(nbytes, closed); @@ -135,15 +135,15 @@ public class TestResponseProtocolCompliance { @Test public void consumesBodyOf100ContinueResponseIfItArrives() throws Exception { - final HttpRequest req = new BasicHttpRequest("POST", "/", HttpVersion.HTTP_1_1); + final ClassicHttpRequest req = new BasicClassicHttpRequest("POST", "/"); final int nbytes = 128; req.setHeader("Content-Length","" + nbytes); req.setHeader("Content-Type", "application/octet-stream"); final HttpEntity postBody = new ByteArrayEntity(HttpTestUtils.getRandomBytes(nbytes)); req.setEntity(postBody); - final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(req, host); + final RoutedHttpRequest wrapper = RoutedHttpRequest.adapt(req, route);; - final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_CONTINUE, "Continue"); + final ClassicHttpResponse resp = new BasicClassicHttpResponse(HttpStatus.SC_CONTINUE, "Continue"); final Flag closed = new Flag(); final ByteArrayInputStream bais = makeTrackableBody(nbytes, closed); resp.setEntity(new InputStreamEntity(bais, -1)); diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestSizeLimitedResponseReader.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestSizeLimitedResponseReader.java index 47e4a1ce4..bedab1fee 100644 --- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestSizeLimitedResponseReader.java +++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestSizeLimitedResponseReader.java @@ -27,20 +27,17 @@ package org.apache.hc.client5.http.impl.cache; import java.io.IOException; -import java.lang.reflect.Proxy; import java.util.concurrent.atomic.AtomicBoolean; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpGet; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpEntity; 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.HttpVersion; -import org.apache.hc.core5.http.entity.ByteArrayEntity; -import org.apache.hc.core5.http.entity.EntityUtils; -import org.apache.hc.core5.http.entity.StringEntity; -import org.apache.hc.core5.http.message.BasicHttpResponse; +import org.apache.hc.core5.http.io.entity.ByteArrayEntity; +import org.apache.hc.core5.http.io.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.StringEntity; +import org.apache.hc.core5.http.message.BasicClassicHttpResponse; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -60,13 +57,13 @@ public class TestSizeLimitedResponseReader { @Test public void testLargeResponseIsTooLarge() throws Exception { final byte[] buf = new byte[] { 1, 2, 3, 4, 5 }; - final CloseableHttpResponse response = make200Response(buf); + final ClassicHttpResponse response = make200Response(buf); impl = new SizeLimitedResponseReader(new HeapResourceFactory(), MAX_SIZE, request, response); impl.readResponse(); final boolean tooLarge = impl.isLimitReached(); - final HttpResponse result = impl.getReconstructedResponse(); + final ClassicHttpResponse result = impl.getReconstructedResponse(); final byte[] body = EntityUtils.toByteArray(result.getEntity()); Assert.assertTrue(tooLarge); @@ -76,13 +73,13 @@ public class TestSizeLimitedResponseReader { @Test public void testExactSizeResponseIsNotTooLarge() throws Exception { final byte[] buf = new byte[] { 1, 2, 3, 4 }; - final CloseableHttpResponse response = make200Response(buf); + final ClassicHttpResponse response = make200Response(buf); impl = new SizeLimitedResponseReader(new HeapResourceFactory(), MAX_SIZE, request, response); impl.readResponse(); final boolean tooLarge = impl.isLimitReached(); - final HttpResponse reconstructed = impl.getReconstructedResponse(); + final ClassicHttpResponse reconstructed = impl.getReconstructedResponse(); final byte[] result = EntityUtils.toByteArray(reconstructed.getEntity()); Assert.assertFalse(tooLarge); @@ -92,13 +89,13 @@ public class TestSizeLimitedResponseReader { @Test public void testSmallResponseIsNotTooLarge() throws Exception { final byte[] buf = new byte[] { 1, 2, 3 }; - final CloseableHttpResponse response = make200Response(buf); + final ClassicHttpResponse response = make200Response(buf); impl = new SizeLimitedResponseReader(new HeapResourceFactory(), MAX_SIZE, request, response); impl.readResponse(); final boolean tooLarge = impl.isLimitReached(); - final HttpResponse reconstructed = impl.getReconstructedResponse(); + final ClassicHttpResponse reconstructed = impl.getReconstructedResponse(); final byte[] result = EntityUtils.toByteArray(reconstructed.getEntity()); Assert.assertFalse(tooLarge); @@ -107,7 +104,7 @@ public class TestSizeLimitedResponseReader { @Test public void testResponseWithNoEntityIsNotTooLarge() throws Exception { - final CloseableHttpResponse response = make200Response(); + final ClassicHttpResponse response = make200Response(); impl = new SizeLimitedResponseReader(new HeapResourceFactory(), MAX_SIZE, request, response); @@ -119,7 +116,7 @@ public class TestSizeLimitedResponseReader { @Test public void testTooLargeEntityHasOriginalContentTypes() throws Exception { - final CloseableHttpResponse response = make200Response(); + final ClassicHttpResponse response = make200Response(); final StringEntity entity = new StringEntity("large entity content"); response.setEntity(entity); @@ -127,7 +124,7 @@ public class TestSizeLimitedResponseReader { impl.readResponse(); final boolean tooLarge = impl.isLimitReached(); - final HttpResponse result = impl.getReconstructedResponse(); + final ClassicHttpResponse result = impl.getReconstructedResponse(); final HttpEntity reconstructedEntity = result.getEntity(); Assert.assertEquals(entity.getContentEncoding(), reconstructedEntity.getContentEncoding()); Assert.assertEquals(entity.getContentType(), reconstructedEntity.getContentType()); @@ -141,16 +138,12 @@ public class TestSizeLimitedResponseReader { @Test public void testTooLargeResponseCombinedClosed() throws Exception { final AtomicBoolean closed = new AtomicBoolean(false); - final CloseableHttpResponse response = (CloseableHttpResponse) Proxy - .newProxyInstance(ResponseProxyHandler.class.getClassLoader(), - new Class[] { CloseableHttpResponse.class }, - new ResponseProxyHandler(new BasicHttpResponse( - HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK")) { - @Override - public void close() throws IOException { - closed.set(true); - } - }); + final ClassicHttpResponse response = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK") { + @Override + public void close() throws IOException { + closed.set(true); + } + }; final StringEntity entity = new StringEntity("large entity content"); response.setEntity(entity); @@ -158,7 +151,7 @@ public class TestSizeLimitedResponseReader { impl.readResponse(); final boolean tooLarge = impl.isLimitReached(); - try (CloseableHttpResponse result = impl.getReconstructedResponse()) { + try (ClassicHttpResponse result = impl.getReconstructedResponse()) { final HttpEntity reconstructedEntity = result.getEntity(); Assert.assertEquals(entity.getContentEncoding(), reconstructedEntity.getContentEncoding()); Assert.assertEquals(entity.getContentType(), reconstructedEntity.getContentType()); @@ -175,14 +168,14 @@ public class TestSizeLimitedResponseReader { @Test public void testResponseCopiesAllOriginalHeaders() throws Exception { final byte[] buf = new byte[] { 1, 2, 3 }; - final CloseableHttpResponse response = make200Response(buf); + final ClassicHttpResponse response = make200Response(buf); response.setHeader("Content-Encoding", "gzip"); impl = new SizeLimitedResponseReader(new HeapResourceFactory(), MAX_SIZE, request, response); impl.readResponse(); final boolean tooLarge = impl.isLimitReached(); - final HttpResponse reconstructed = impl.getReconstructedResponse(); + final ClassicHttpResponse reconstructed = impl.getReconstructedResponse(); final byte[] result = EntityUtils.toByteArray(reconstructed.getEntity()); Assert.assertFalse(tooLarge); @@ -190,16 +183,14 @@ public class TestSizeLimitedResponseReader { Assert.assertEquals("gzip", reconstructed.getFirstHeader("Content-Encoding").getValue()); } - private CloseableHttpResponse make200Response() { - return Proxies.enhanceResponse(new BasicHttpResponse( - HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK")); + private ClassicHttpResponse make200Response() { + return new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); } - private CloseableHttpResponse make200Response(final byte[] buf) { - final HttpResponse response = new BasicHttpResponse( - HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); + private ClassicHttpResponse make200Response(final byte[] buf) { + final ClassicHttpResponse response = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK"); response.setEntity(new ByteArrayEntity(buf)); - return Proxies.enhanceResponse(response); + return response; } } diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestStaleWhileRevalidationReleasesConnection.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestStaleWhileRevalidationReleasesConnection.java index a0025d187..17d4399c6 100644 --- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestStaleWhileRevalidationReleasesConnection.java +++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestStaleWhileRevalidationReleasesConnection.java @@ -40,17 +40,18 @@ import org.apache.hc.client5.http.impl.sync.CloseableHttpClient; import org.apache.hc.client5.http.impl.sync.HttpClientBuilder; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.client5.http.protocol.ClientProtocolException; +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.HttpRequest; -import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.MethodNotSupportedException; -import org.apache.hc.core5.http.bootstrap.io.HttpServer; -import org.apache.hc.core5.http.bootstrap.io.ServerBootstrap; import org.apache.hc.core5.http.config.SocketConfig; -import org.apache.hc.core5.http.entity.ByteArrayEntity; +import org.apache.hc.core5.http.impl.io.bootstrap.HttpServer; +import org.apache.hc.core5.http.impl.io.bootstrap.ServerBootstrap; import org.apache.hc.core5.http.io.HttpRequestHandler; +import org.apache.hc.core5.http.io.entity.ByteArrayEntity; import org.apache.hc.core5.http.protocol.BasicHttpContext; import org.apache.hc.core5.http.protocol.HttpContext; import org.junit.After; @@ -195,7 +196,7 @@ public class TestStaleWhileRevalidationReleasesConnection { httpget.setHeader(cacheHandler.getUserContentHeader(),content); } - HttpResponse response = null; + ClassicHttpResponse response = null; try { response = cachingClient.execute(httpget, localContext); return null; @@ -256,12 +257,12 @@ public class TestStaleWhileRevalidationReleasesConnection { * @throws java.io.IOException in case of an IO problem */ @Override - public void handle(final HttpRequest request, - final HttpResponse response, + public void handle(final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { - final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ROOT); + final String method = request.getMethod().toUpperCase(Locale.ROOT); if (!"GET".equals(method) && !"POST".equals(method) && !"PUT".equals(method) @@ -270,7 +271,7 @@ public class TestStaleWhileRevalidationReleasesConnection { (method + " not supported by " + getClass().getName()); } - response.setStatusCode(org.apache.hc.core5.http.HttpStatus.SC_OK); + response.setCode(org.apache.hc.core5.http.HttpStatus.SC_OK); response.addHeader("Cache-Control",getCacheContent(request)); final byte[] content = getHeaderContent(request); final ByteArrayEntity bae = new ByteArrayEntity(content); diff --git a/httpclient5-fluent/src/examples/org/apache/hc/client5/http/examples/fluent/FluentExecutor.java b/httpclient5-fluent/src/examples/org/apache/hc/client5/http/examples/fluent/FluentExecutor.java index 8137390a4..c6c5dedf4 100644 --- a/httpclient5-fluent/src/examples/org/apache/hc/client5/http/examples/fluent/FluentExecutor.java +++ b/httpclient5-fluent/src/examples/org/apache/hc/client5/http/examples/fluent/FluentExecutor.java @@ -33,7 +33,7 @@ import org.apache.hc.client5.http.fluent.Form; import org.apache.hc.client5.http.fluent.Request; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpVersion; -import org.apache.hc.core5.http.entity.ContentType; +import org.apache.hc.core5.http.ContentType; /** * This example demonstrates how the he HttpClient fluent API can be used to execute multiple diff --git a/httpclient5-fluent/src/examples/org/apache/hc/client5/http/examples/fluent/FluentRequests.java b/httpclient5-fluent/src/examples/org/apache/hc/client5/http/examples/fluent/FluentRequests.java index bdf7d9a3e..1318f2f27 100644 --- a/httpclient5-fluent/src/examples/org/apache/hc/client5/http/examples/fluent/FluentRequests.java +++ b/httpclient5-fluent/src/examples/org/apache/hc/client5/http/examples/fluent/FluentRequests.java @@ -32,7 +32,7 @@ import org.apache.hc.client5.http.fluent.Form; import org.apache.hc.client5.http.fluent.Request; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpVersion; -import org.apache.hc.core5.http.entity.ContentType; +import org.apache.hc.core5.http.ContentType; /** * This example demonstrates basics of request execution with the HttpClient fluent API. diff --git a/httpclient5-fluent/src/examples/org/apache/hc/client5/http/examples/fluent/FluentResponseHandling.java b/httpclient5-fluent/src/examples/org/apache/hc/client5/http/examples/fluent/FluentResponseHandling.java index f02728c04..b989eaa8a 100644 --- a/httpclient5-fluent/src/examples/org/apache/hc/client5/http/examples/fluent/FluentResponseHandling.java +++ b/httpclient5-fluent/src/examples/org/apache/hc/client5/http/examples/fluent/FluentResponseHandling.java @@ -37,11 +37,12 @@ import javax.xml.parsers.ParserConfigurationException; import org.apache.hc.client5.http.fluent.Request; import org.apache.hc.client5.http.protocol.ClientProtocolException; import org.apache.hc.client5.http.protocol.HttpResponseException; -import org.apache.hc.client5.http.sync.ResponseHandler; +import org.apache.hc.core5.http.ClassicHttpResponse; +import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.HttpResponse; -import org.apache.hc.core5.http.StatusLine; -import org.apache.hc.core5.http.entity.ContentType; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.io.ResponseHandler; +import org.apache.hc.core5.http.io.entity.EntityUtils; import org.w3c.dom.Document; import org.xml.sax.SAXException; @@ -56,13 +57,11 @@ public class FluentResponseHandling { .execute().handleResponse(new ResponseHandler() { @Override - public Document handleResponse(final HttpResponse response) throws IOException { - StatusLine statusLine = response.getStatusLine(); + public Document handleResponse(final ClassicHttpResponse response) throws IOException { + int status = response.getCode(); HttpEntity entity = response.getEntity(); - if (statusLine.getStatusCode() >= 300) { - throw new HttpResponseException( - statusLine.getStatusCode(), - statusLine.getReasonPhrase()); + if (status >= HttpStatus.SC_REDIRECTION) { + throw new HttpResponseException(status, response.getReasonPhrase()); } if (entity == null) { throw new ClientProtocolException("Response contains no content"); @@ -70,7 +69,7 @@ public class FluentResponseHandling { DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); try { DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); - ContentType contentType = ContentType.getOrDefault(entity); + ContentType contentType = EntityUtils.getContentTypeOrDefault(entity); if (!contentType.equals(ContentType.APPLICATION_XML)) { throw new ClientProtocolException("Unexpected content type:" + contentType); } diff --git a/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/Async.java b/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/Async.java index f66c4a276..7c6462d76 100644 --- a/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/Async.java +++ b/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/Async.java @@ -28,9 +28,9 @@ package org.apache.hc.client5.http.fluent; import java.util.concurrent.Future; -import org.apache.hc.client5.http.sync.ResponseHandler; import org.apache.hc.core5.concurrent.BasicFuture; import org.apache.hc.core5.concurrent.FutureCallback; +import org.apache.hc.core5.http.io.ResponseHandler; public class Async { diff --git a/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/Content.java b/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/Content.java index fbc6d1004..1ef83c897 100644 --- a/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/Content.java +++ b/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/Content.java @@ -31,7 +31,7 @@ import java.io.InputStream; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; -import org.apache.hc.core5.http.entity.ContentType; +import org.apache.hc.core5.http.ContentType; /** * This class represents arbitrary content of a specific type that can be consumed diff --git a/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/ContentResponseHandler.java b/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/ContentResponseHandler.java index 803e612c1..dae1d058d 100644 --- a/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/ContentResponseHandler.java +++ b/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/ContentResponseHandler.java @@ -30,8 +30,7 @@ import java.io.IOException; import org.apache.hc.client5.http.impl.sync.AbstractResponseHandler; import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.entity.ContentType; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.EntityUtils; /** * {@link org.apache.hc.client5.http.sync.ResponseHandler} implementation that converts @@ -47,7 +46,7 @@ public class ContentResponseHandler extends AbstractResponseHandler { @Override public Content handleEntity(final HttpEntity entity) throws IOException { return entity != null ? - new Content(EntityUtils.toByteArray(entity), ContentType.getOrDefault(entity)) : + new Content(EntityUtils.toByteArray(entity), EntityUtils.getContentTypeOrDefault(entity)) : Content.NO_CONTENT; } diff --git a/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/Executor.java b/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/Executor.java index 6975c33cb..2cf9393c7 100644 --- a/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/Executor.java +++ b/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/Executor.java @@ -27,6 +27,7 @@ package org.apache.hc.client5.http.fluent; import java.io.IOException; +import java.net.URISyntaxException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.concurrent.TimeUnit; @@ -141,7 +142,13 @@ public class Executor { * @since 4.4 */ public Executor auth(final String host, final Credentials creds) { - return auth(HttpHost.create(host), creds); + final HttpHost httpHost; + try { + httpHost = HttpHost.create(host); + } catch (URISyntaxException ex) { + throw new IllegalArgumentException("Invalid host: " + host); + } + return auth(httpHost, creds); } public Executor authPreemptive(final HttpHost host) { @@ -160,7 +167,13 @@ public class Executor { * @since 4.4 */ public Executor authPreemptive(final String host) { - return authPreemptive(HttpHost.create(host)); + final HttpHost httpHost; + try { + httpHost = HttpHost.create(host); + } catch (URISyntaxException ex) { + throw new IllegalArgumentException("Invalid host: " + host); + } + return authPreemptive(httpHost); } public Executor authPreemptiveProxy(final HttpHost proxy) { @@ -179,7 +192,13 @@ public class Executor { * @since 4.4 */ public Executor authPreemptiveProxy(final String proxy) { - return authPreemptiveProxy(HttpHost.create(proxy)); + final HttpHost httpHost; + try { + httpHost = HttpHost.create(proxy); + } catch (URISyntaxException ex) { + throw new IllegalArgumentException("Invalid host: " + proxy); + } + return authPreemptiveProxy(httpHost); } public Executor auth(final Credentials cred) { @@ -256,7 +275,7 @@ public class Executor { * @since 4.4 */ public static void closeIdleConnections() { - CONNMGR.closeIdleConnections(0, TimeUnit.MICROSECONDS); + CONNMGR.closeIdle(0, TimeUnit.MICROSECONDS); } } diff --git a/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/InternalByteArrayEntity.java b/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/InternalByteArrayEntity.java deleted file mode 100644 index cba592df1..000000000 --- a/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/InternalByteArrayEntity.java +++ /dev/null @@ -1,105 +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 - * . - * - */ - -package org.apache.hc.client5.http.fluent; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.apache.hc.core5.http.entity.AbstractHttpEntity; -import org.apache.hc.core5.http.entity.ContentType; -import org.apache.hc.core5.util.Args; - -class InternalByteArrayEntity extends AbstractHttpEntity implements Cloneable { - - private final byte[] b; - private final int off, len; - - public InternalByteArrayEntity(final byte[] b, final ContentType contentType) { - super(); - Args.notNull(b, "Source byte array"); - this.b = b; - this.off = 0; - this.len = this.b.length; - if (contentType != null) { - setContentType(contentType.toString()); - } - } - - public InternalByteArrayEntity(final byte[] b, final int off, final int len, final ContentType contentType) { - super(); - Args.notNull(b, "Source byte array"); - if ((off < 0) || (off > b.length) || (len < 0) || - ((off + len) < 0) || ((off + len) > b.length)) { - throw new IndexOutOfBoundsException("off: " + off + " len: " + len + " b.length: " + b.length); - } - this.b = b; - this.off = off; - this.len = len; - if (contentType != null) { - setContentType(contentType.toString()); - } - } - - public InternalByteArrayEntity(final byte[] b) { - this(b, null); - } - - public InternalByteArrayEntity(final byte[] b, final int off, final int len) { - this(b, off, len, null); - } - - @Override - public boolean isRepeatable() { - return true; - } - - @Override - public long getContentLength() { - return this.len; - } - - @Override - public InputStream getContent() { - return new ByteArrayInputStream(this.b, this.off, this.len); - } - - @Override - public void writeTo(final OutputStream outstream) throws IOException { - Args.notNull(outstream, "Output stream"); - outstream.write(this.b, this.off, this.len); - outstream.flush(); - } - - @Override - public boolean isStreaming() { - return false; - } - -} diff --git a/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/InternalFileEntity.java b/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/InternalFileEntity.java deleted file mode 100644 index 6920cf8bc..000000000 --- a/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/InternalFileEntity.java +++ /dev/null @@ -1,85 +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 - * . - * - */ - -package org.apache.hc.client5.http.fluent; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.apache.hc.core5.http.entity.AbstractHttpEntity; -import org.apache.hc.core5.http.entity.ContentType; -import org.apache.hc.core5.util.Args; - -class InternalFileEntity extends AbstractHttpEntity implements Cloneable { - - private final File file; - - public InternalFileEntity(final File file, final ContentType contentType) { - super(); - this.file = Args.notNull(file, "File"); - if (contentType != null) { - setContentType(contentType.toString()); - } - } - - @Override - public boolean isRepeatable() { - return true; - } - - @Override - public long getContentLength() { - return this.file.length(); - } - - @Override - public InputStream getContent() throws IOException { - return new FileInputStream(this.file); - } - - @Override - public void writeTo(final OutputStream outstream) throws IOException { - Args.notNull(outstream, "Output stream"); - try (InputStream instream = new FileInputStream(this.file)) { - final byte[] tmp = new byte[4096]; - int l; - while ((l = instream.read(tmp)) != -1) { - outstream.write(tmp, 0, l); - } - outstream.flush(); - } - } - - @Override - public boolean isStreaming() { - return false; - } - -} diff --git a/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/InternalHttpRequest.java b/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/InternalHttpRequest.java deleted file mode 100644 index 46c715e01..000000000 --- a/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/InternalHttpRequest.java +++ /dev/null @@ -1,142 +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 - * . - * - */ - -package org.apache.hc.client5.http.fluent; - -import java.net.URI; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; - -import org.apache.hc.client5.http.config.RequestConfig; -import org.apache.hc.client5.http.methods.Configurable; -import org.apache.hc.client5.http.methods.HttpExecutionAware; -import org.apache.hc.client5.http.methods.HttpUriRequest; -import org.apache.hc.core5.annotation.NotThreadSafe; -import org.apache.hc.core5.concurrent.Cancellable; -import org.apache.hc.core5.http.HttpVersion; -import org.apache.hc.core5.http.ProtocolVersion; -import org.apache.hc.core5.http.RequestLine; -import org.apache.hc.core5.http.message.AbstractHttpMessage; -import org.apache.hc.core5.http.message.BasicRequestLine; -import org.apache.hc.core5.util.Args; - -@NotThreadSafe -class InternalHttpRequest extends AbstractHttpMessage - implements HttpUriRequest, HttpExecutionAware, Configurable { - - private static final long serialVersionUID = 1L; - private final String method; - private ProtocolVersion version; - private URI uri; - private RequestConfig config; - - private final AtomicBoolean aborted; - private final AtomicReference cancellableRef; - - InternalHttpRequest(final String method, final URI requestURI) { - Args.notBlank(method, "Method"); - Args.notNull(requestURI, "Request URI"); - this.method = method; - this.uri = requestURI; - this.aborted = new AtomicBoolean(false); - this.cancellableRef = new AtomicReference<>(null); - } - - public void setProtocolVersion(final ProtocolVersion version) { - this.version = version; - } - - @Override - public ProtocolVersion getProtocolVersion() { - return version != null ? version : HttpVersion.HTTP_1_1; - } - - @Override - public String getMethod() { - return this.method; - } - - @Override - public URI getURI() { - return this.uri; - } - - @Override - public void abort() throws UnsupportedOperationException { - if (this.aborted.compareAndSet(false, true)) { - final Cancellable cancellable = this.cancellableRef.getAndSet(null); - if (cancellable != null) { - cancellable.cancel(); - } - } - } - - @Override - public boolean isAborted() { - return this.aborted.get(); - } - - @Override - public void setCancellable(final Cancellable cancellable) { - if (!this.aborted.get()) { - this.cancellableRef.set(cancellable); - } - } - - @Override - public RequestLine getRequestLine() { - final ProtocolVersion ver = getProtocolVersion(); - final URI uriCopy = getURI(); - String uritext = null; - if (uriCopy != null) { - uritext = uriCopy.toASCIIString(); - } - if (uritext == null || uritext.isEmpty()) { - uritext = "/"; - } - return new BasicRequestLine(getMethod(), uritext, ver); - } - - @Override - public RequestConfig getConfig() { - return config; - } - - public void setConfig(final RequestConfig config) { - this.config = config; - } - - public void setURI(final URI uri) { - this.uri = uri; - } - - @Override - public String toString() { - return getMethod() + " " + getURI() + " " + getProtocolVersion(); - } - -} diff --git a/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/InternalInputStreamEntity.java b/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/InternalInputStreamEntity.java deleted file mode 100644 index f99fadba5..000000000 --- a/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/InternalInputStreamEntity.java +++ /dev/null @@ -1,98 +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 - * . - * - */ - -package org.apache.hc.client5.http.fluent; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.apache.hc.core5.http.entity.AbstractHttpEntity; -import org.apache.hc.core5.http.entity.ContentType; -import org.apache.hc.core5.util.Args; - -class InternalInputStreamEntity extends AbstractHttpEntity { - - private final InputStream content; - private final long length; - - public InternalInputStreamEntity(final InputStream instream, final long length, final ContentType contentType) { - super(); - this.content = Args.notNull(instream, "Source input stream"); - this.length = length; - if (contentType != null) { - setContentType(contentType.toString()); - } - } - - @Override - public boolean isRepeatable() { - return false; - } - - @Override - public long getContentLength() { - return this.length; - } - - @Override - public InputStream getContent() throws IOException { - return this.content; - } - - @Override - public void writeTo(final OutputStream outstream) throws IOException { - Args.notNull(outstream, "Output stream"); - try (InputStream instream = this.content) { - final byte[] buffer = new byte[4096]; - int l; - if (this.length < 0) { - // consume until EOF - while ((l = instream.read(buffer)) != -1) { - outstream.write(buffer, 0, l); - } - } else { - // consume no more than length - long remaining = this.length; - while (remaining > 0) { - l = instream.read(buffer, 0, (int) Math.min(4096, remaining)); - if (l == -1) { - break; - } - outstream.write(buffer, 0, l); - remaining -= l; - } - } - } - } - - @Override - public boolean isStreaming() { - return true; - } - -} diff --git a/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/Request.java b/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/Request.java index 70c6288a0..4a0f82ecd 100644 --- a/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/Request.java +++ b/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/Request.java @@ -30,6 +30,7 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; +import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; @@ -51,16 +52,20 @@ import org.apache.hc.client5.http.methods.HttpPatch; import org.apache.hc.client5.http.methods.HttpPost; import org.apache.hc.client5.http.methods.HttpPut; import org.apache.hc.client5.http.methods.HttpTrace; -import org.apache.hc.client5.http.utils.URLEncodedUtils; +import org.apache.hc.client5.http.methods.HttpUriRequestBase; +import org.apache.hc.core5.http.ClassicHttpResponse; +import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.HttpHeaders; import org.apache.hc.core5.http.HttpHost; -import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.HttpVersion; import org.apache.hc.core5.http.NameValuePair; -import org.apache.hc.core5.http.entity.ContentType; +import org.apache.hc.core5.http.io.entity.ByteArrayEntity; +import org.apache.hc.core5.http.io.entity.FileEntity; +import org.apache.hc.core5.http.io.entity.InputStreamEntity; import org.apache.hc.core5.http.protocol.HttpContext; +import org.apache.hc.core5.net.URLEncodedUtils; public class Request { @@ -68,7 +73,7 @@ public class Request { public static final Locale DATE_LOCALE = Locale.US; public static final TimeZone TIME_ZONE = TimeZone.getTimeZone("GMT"); - private final InternalHttpRequest request; + private final HttpUriRequestBase request; private Boolean useExpectContinue; private Integer socketTmeout; private Integer connectTimeout; @@ -77,83 +82,83 @@ public class Request { private SimpleDateFormat dateFormatter; public static Request create(final String methodName, final String uri) { - return new Request(new InternalHttpRequest(methodName, URI.create(uri))); + return new Request(new HttpUriRequestBase(methodName, URI.create(uri))); } public static Request create(final String methodName, final URI uri) { - return new Request(new InternalHttpRequest(methodName, uri)); + return new Request(new HttpUriRequestBase(methodName, uri)); } public static Request Get(final URI uri) { - return new Request(new InternalHttpRequest(HttpGet.METHOD_NAME, uri)); + return new Request(new HttpUriRequestBase(HttpGet.METHOD_NAME, uri)); } public static Request Get(final String uri) { - return new Request(new InternalHttpRequest(HttpGet.METHOD_NAME, URI.create(uri))); + return new Request(new HttpUriRequestBase(HttpGet.METHOD_NAME, URI.create(uri))); } public static Request Head(final URI uri) { - return new Request(new InternalHttpRequest(HttpHead.METHOD_NAME, uri)); + return new Request(new HttpUriRequestBase(HttpHead.METHOD_NAME, uri)); } public static Request Head(final String uri) { - return new Request(new InternalHttpRequest(HttpHead.METHOD_NAME, URI.create(uri))); + return new Request(new HttpUriRequestBase(HttpHead.METHOD_NAME, URI.create(uri))); } public static Request Post(final URI uri) { - return new Request(new InternalHttpRequest(HttpPost.METHOD_NAME, uri)); + return new Request(new HttpUriRequestBase(HttpPost.METHOD_NAME, uri)); } public static Request Post(final String uri) { - return new Request(new InternalHttpRequest(HttpPost.METHOD_NAME, URI.create(uri))); + return new Request(new HttpUriRequestBase(HttpPost.METHOD_NAME, URI.create(uri))); } public static Request Patch(final URI uri) { - return new Request(new InternalHttpRequest(HttpPatch.METHOD_NAME, uri)); + return new Request(new HttpUriRequestBase(HttpPatch.METHOD_NAME, uri)); } public static Request Patch(final String uri) { - return new Request(new InternalHttpRequest(HttpPatch.METHOD_NAME, URI.create(uri))); + return new Request(new HttpUriRequestBase(HttpPatch.METHOD_NAME, URI.create(uri))); } public static Request Put(final URI uri) { - return new Request(new InternalHttpRequest(HttpPut.METHOD_NAME, uri)); + return new Request(new HttpUriRequestBase(HttpPut.METHOD_NAME, uri)); } public static Request Put(final String uri) { - return new Request(new InternalHttpRequest(HttpPut.METHOD_NAME, URI.create(uri))); + return new Request(new HttpUriRequestBase(HttpPut.METHOD_NAME, URI.create(uri))); } public static Request Trace(final URI uri) { - return new Request(new InternalHttpRequest(HttpTrace.METHOD_NAME, uri)); + return new Request(new HttpUriRequestBase(HttpTrace.METHOD_NAME, uri)); } public static Request Trace(final String uri) { - return new Request(new InternalHttpRequest(HttpTrace.METHOD_NAME, URI.create(uri))); + return new Request(new HttpUriRequestBase(HttpTrace.METHOD_NAME, URI.create(uri))); } public static Request Delete(final URI uri) { - return new Request(new InternalHttpRequest(HttpDelete.METHOD_NAME, uri)); + return new Request(new HttpUriRequestBase(HttpDelete.METHOD_NAME, uri)); } public static Request Delete(final String uri) { - return new Request(new InternalHttpRequest(HttpDelete.METHOD_NAME, URI.create(uri))); + return new Request(new HttpUriRequestBase(HttpDelete.METHOD_NAME, URI.create(uri))); } public static Request Options(final URI uri) { - return new Request(new InternalHttpRequest(HttpOptions.METHOD_NAME, uri)); + return new Request(new HttpUriRequestBase(HttpOptions.METHOD_NAME, uri)); } public static Request Options(final String uri) { - return new Request(new InternalHttpRequest(HttpOptions.METHOD_NAME, URI.create(uri))); + return new Request(new HttpUriRequestBase(HttpOptions.METHOD_NAME, URI.create(uri))); } - Request(final InternalHttpRequest request) { + Request(final HttpUriRequestBase request) { super(); this.request = request; } - HttpResponse internalExecute( + ClassicHttpResponse internalExecute( final CloseableHttpClient client, final HttpContext localContext) throws IOException { final RequestConfig.Builder builder; @@ -261,7 +266,7 @@ public class Request { //// HTTP protocol parameter operations public Request version(final HttpVersion version) { - this.request.setProtocolVersion(version); + this.request.setVersion(version); return this; } @@ -298,7 +303,11 @@ public class Request { * @since 4.4 */ public Request viaProxy(final String proxy) { - this.proxy = HttpHost.create(proxy); + try { + this.proxy = HttpHost.create(proxy); + } catch (URISyntaxException e) { + throw new IllegalArgumentException("Invalid host"); + } return this; } @@ -330,46 +339,46 @@ public class Request { public Request bodyString(final String s, final ContentType contentType) { final Charset charset = contentType != null ? contentType.getCharset() : null; final byte[] raw = charset != null ? s.getBytes(charset) : s.getBytes(); - return body(new InternalByteArrayEntity(raw, contentType)); + return body(new ByteArrayEntity(raw, contentType)); } public Request bodyFile(final File file, final ContentType contentType) { - return body(new InternalFileEntity(file, contentType)); + return body(new FileEntity(file, contentType)); } public Request bodyByteArray(final byte[] b) { - return body(new InternalByteArrayEntity(b)); + return body(new ByteArrayEntity(b)); } /** * @since 4.4 */ public Request bodyByteArray(final byte[] b, final ContentType contentType) { - return body(new InternalByteArrayEntity(b, contentType)); + return body(new ByteArrayEntity(b, contentType)); } public Request bodyByteArray(final byte[] b, final int off, final int len) { - return body(new InternalByteArrayEntity(b, off, len)); + return body(new ByteArrayEntity(b, off, len)); } /** * @since 4.4 */ public Request bodyByteArray(final byte[] b, final int off, final int len, final ContentType contentType) { - return body(new InternalByteArrayEntity(b, off, len, contentType)); + return body(new ByteArrayEntity(b, off, len, contentType)); } public Request bodyStream(final InputStream instream) { - return body(new InternalInputStreamEntity(instream, -1, null)); + return body(new InputStreamEntity(instream, -1, null)); } public Request bodyStream(final InputStream instream, final ContentType contentType) { - return body(new InternalInputStreamEntity(instream, -1, contentType)); + return body(new InputStreamEntity(instream, -1, contentType)); } @Override public String toString() { - return this.request.getRequestLine().toString(); + return this.request.toString(); } } diff --git a/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/Response.java b/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/Response.java index 61b462c86..62954ce8a 100644 --- a/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/Response.java +++ b/httpclient5-fluent/src/main/java/org/apache/hc/client5/http/fluent/Response.java @@ -31,21 +31,24 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; +import org.apache.hc.client5.http.protocol.ClientProtocolException; import org.apache.hc.client5.http.protocol.HttpResponseException; -import org.apache.hc.client5.http.sync.ResponseHandler; +import org.apache.hc.core5.http.ClassicHttpResponse; +import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.HttpEntity; +import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpResponse; -import org.apache.hc.core5.http.StatusLine; -import org.apache.hc.core5.http.entity.ByteArrayEntity; -import org.apache.hc.core5.http.entity.ContentType; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.io.ResponseHandler; +import org.apache.hc.core5.http.io.entity.ByteArrayEntity; +import org.apache.hc.core5.http.io.entity.EntityUtils; public class Response { - private final HttpResponse response; + private final ClassicHttpResponse response; private boolean consumed; - Response(final HttpResponse response) { + Response(final ClassicHttpResponse response) { super(); this.response = response; } @@ -87,6 +90,8 @@ public class Response { assertNotConsumed(); try { return handler.handleResponse(this.response); + } catch (HttpException ex) { + throw new ClientProtocolException(ex); } finally { dispose(); } @@ -103,7 +108,7 @@ public class Response { if (entity != null) { final ByteArrayEntity byteArrayEntity = new ByteArrayEntity( EntityUtils.toByteArray(entity)); - final ContentType contentType = ContentType.getOrDefault(entity); + final ContentType contentType = EntityUtils.getContentTypeOrDefault(entity); byteArrayEntity.setContentType(contentType.toString()); this.response.setEntity(byteArrayEntity); } @@ -115,10 +120,9 @@ public class Response { public void saveContent(final File file) throws IOException { assertNotConsumed(); - final StatusLine statusLine = response.getStatusLine(); - if (statusLine.getStatusCode() >= 300) { - throw new HttpResponseException(statusLine.getStatusCode(), - statusLine.getReasonPhrase()); + final int status = response.getCode(); + if (status >= HttpStatus.SC_REDIRECTION) { + throw new HttpResponseException(status, response.getReasonPhrase()); } try (FileOutputStream out = new FileOutputStream(file)) { final HttpEntity entity = this.response.getEntity(); diff --git a/httpclient5-fluent/src/test/java/org/apache/hc/client5/http/fluent/TestFluent.java b/httpclient5-fluent/src/test/java/org/apache/hc/client5/http/fluent/TestFluent.java index 4a3eb2a01..471df11d2 100644 --- a/httpclient5-fluent/src/test/java/org/apache/hc/client5/http/fluent/TestFluent.java +++ b/httpclient5-fluent/src/test/java/org/apache/hc/client5/http/fluent/TestFluent.java @@ -33,16 +33,16 @@ import java.nio.charset.Charset; import org.apache.hc.client5.http.localserver.LocalServerTestBase; import org.apache.hc.client5.http.protocol.ClientProtocolException; -import org.apache.hc.client5.http.sync.ResponseHandler; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; +import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpHost; -import org.apache.hc.core5.http.HttpRequest; -import org.apache.hc.core5.http.HttpResponse; -import org.apache.hc.core5.http.entity.ContentType; -import org.apache.hc.core5.http.entity.EntityUtils; -import org.apache.hc.core5.http.entity.StringEntity; import org.apache.hc.core5.http.io.HttpRequestHandler; +import org.apache.hc.core5.http.io.ResponseHandler; +import org.apache.hc.core5.http.io.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.StringEntity; import org.apache.hc.core5.http.protocol.HttpContext; import org.junit.After; import org.junit.Assert; @@ -58,8 +58,8 @@ public class TestFluent extends LocalServerTestBase { @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { response.setEntity(new StringEntity("All is well", ContentType.TEXT_PLAIN)); } @@ -69,13 +69,13 @@ public class TestFluent extends LocalServerTestBase { @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity responseEntity = null; final HttpEntity requestEntity = request.getEntity(); if (requestEntity != null) { - final ContentType contentType = ContentType.getOrDefault(requestEntity); + final ContentType contentType = EntityUtils.getContentTypeOrDefault(requestEntity); if (ContentType.TEXT_PLAIN.getMimeType().equals(contentType.getMimeType())) { responseEntity = new StringEntity( EntityUtils.toString(requestEntity), ContentType.TEXT_PLAIN); @@ -164,7 +164,7 @@ public class TestFluent extends LocalServerTestBase { @Override public Object handleResponse( - final HttpResponse response) throws IOException { + final ClassicHttpResponse response) throws IOException { return null; } diff --git a/httpclient5-osgi/pom.xml b/httpclient5-osgi/pom.xml index 887d76f6e..2893477f6 100644 --- a/httpclient5-osgi/pom.xml +++ b/httpclient5-osgi/pom.xml @@ -40,7 +40,7 @@ bundle - "5.0-alpha1" + "5.0-alpha2" "2.7" 2.4.1 4.5.0 @@ -198,17 +198,7 @@ org.osgi.framework, org.osgi.service.cm, org.apache.logging.log4j;version=${log4j.osgi.import.version}, - org.apache.hc.core5.concurrent;version=${httpcore.osgi.import.version}, - org.apache.hc.core5.pool;version=${httpcore.osgi.import.version}, - org.apache.hc.core5.ssl;version=${httpcore.osgi.import.version}, - org.apache.hc.core5.util;version=${httpcore.osgi.import.version}, - org.apache.hc.core5.http;version=${httpcore.osgi.import.version}, - org.apache.hc.core5.http.config;version=${httpcore.osgi.import.version}, - org.apache.hc.core5.http.entity;version=${httpcore.osgi.import.version}, - org.apache.hc.core5.http.message;version=${httpcore.osgi.import.version}, - org.apache.hc.core5.http.io;version=${httpcore.osgi.import.version}, - org.apache.hc.core5.http.protocol;version=${httpcore.osgi.import.version}, - org.apache.hc.core5.http.impl.io;version=${httpcore.osgi.import.version}, + org.apache.hc.core5.*;version=${httpcore.osgi.import.version}, net.sf.ehcache.*;resolution:=optional, net.spy.memcached.*;resolution:=optional diff --git a/httpclient5-osgi/src/test/java/org/apache/hc/client5/http/osgi/impl/MimeExportedIT.java b/httpclient5-osgi/src/test/java/org/apache/hc/client5/http/osgi/impl/MimeExportedIT.java index 198eae153..f060271ad 100644 --- a/httpclient5-osgi/src/test/java/org/apache/hc/client5/http/osgi/impl/MimeExportedIT.java +++ b/httpclient5-osgi/src/test/java/org/apache/hc/client5/http/osgi/impl/MimeExportedIT.java @@ -43,7 +43,7 @@ import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder; import org.apache.hc.client5.http.entity.mime.StringBody; import org.apache.hc.client5.http.methods.HttpPost; import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.entity.ContentType; +import org.apache.hc.core5.http.ContentType; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Configuration; diff --git a/httpclient5-win/src/examples/org/apache/hc/client5/http/examples/client/win/ClientWinAuth.java b/httpclient5-win/src/examples/org/apache/hc/client5/http/examples/client/win/ClientWinAuth.java index fafbbca1c..e5696f01c 100644 --- a/httpclient5-win/src/examples/org/apache/hc/client5/http/examples/client/win/ClientWinAuth.java +++ b/httpclient5-win/src/examples/org/apache/hc/client5/http/examples/client/win/ClientWinAuth.java @@ -31,7 +31,7 @@ import org.apache.hc.client5.http.impl.sync.CloseableHttpClient; import org.apache.hc.client5.http.impl.win.WinHttpClients; import org.apache.hc.client5.http.methods.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpGet; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.EntityUtils; /** * This example demonstrates how to create HttpClient pre-configured @@ -52,11 +52,11 @@ public class ClientWinAuth { try { HttpGet httpget = new HttpGet("http://winhost/"); - System.out.println("Executing request " + httpget.getRequestLine()); + System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri()); CloseableHttpResponse response = httpclient.execute(httpget); try { System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); + System.out.println(response.getCode() + " " + response.getReasonPhrase()); EntityUtils.consume(response.getEntity()); } finally { response.close(); diff --git a/httpclient5-win/src/main/java/org/apache/hc/client5/http/impl/win/WindowsNTLMSchemeFactory.java b/httpclient5-win/src/main/java/org/apache/hc/client5/http/impl/win/WindowsNTLMSchemeFactory.java index 6b4de54d8..0615cdba8 100644 --- a/httpclient5-win/src/main/java/org/apache/hc/client5/http/impl/win/WindowsNTLMSchemeFactory.java +++ b/httpclient5-win/src/main/java/org/apache/hc/client5/http/impl/win/WindowsNTLMSchemeFactory.java @@ -30,7 +30,8 @@ package org.apache.hc.client5.http.impl.win; import org.apache.hc.client5.http.auth.AuthScheme; import org.apache.hc.client5.http.auth.AuthSchemeProvider; import org.apache.hc.client5.http.config.AuthSchemes; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.protocol.HttpContext; /** @@ -42,7 +43,7 @@ import org.apache.hc.core5.http.protocol.HttpContext; * * @since 4.4 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class WindowsNTLMSchemeFactory implements AuthSchemeProvider { private final String servicePrincipalName; diff --git a/httpclient5-win/src/main/java/org/apache/hc/client5/http/impl/win/WindowsNegotiateScheme.java b/httpclient5-win/src/main/java/org/apache/hc/client5/http/impl/win/WindowsNegotiateScheme.java index 2f9e1b24a..1695bb127 100644 --- a/httpclient5-win/src/main/java/org/apache/hc/client5/http/impl/win/WindowsNegotiateScheme.java +++ b/httpclient5-win/src/main/java/org/apache/hc/client5/http/impl/win/WindowsNegotiateScheme.java @@ -29,7 +29,6 @@ package org.apache.hc.client5.http.impl.win; import java.security.Principal; import org.apache.commons.codec.binary.Base64; -import org.apache.hc.client5.http.RouteInfo; import org.apache.hc.client5.http.auth.AuthChallenge; import org.apache.hc.client5.http.auth.AuthScheme; import org.apache.hc.client5.http.auth.AuthenticationException; @@ -37,11 +36,10 @@ import org.apache.hc.client5.http.auth.BasicUserPrincipal; import org.apache.hc.client5.http.auth.CredentialsProvider; import org.apache.hc.client5.http.auth.MalformedChallengeException; import org.apache.hc.client5.http.config.AuthSchemes; -import org.apache.hc.client5.http.protocol.HttpClientContext; -import org.apache.hc.core5.annotation.NotThreadSafe; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.protocol.HttpContext; +import org.apache.hc.core5.net.URIAuthority; import org.apache.hc.core5.util.Args; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -68,7 +66,6 @@ import com.sun.jna.ptr.IntByReference; * * @since 4.4 */ -@NotThreadSafe public class WindowsNegotiateScheme implements AuthScheme { private final Logger log = LogManager.getLogger(getClass()); @@ -196,7 +193,7 @@ public class WindowsNegotiateScheme implements AuthScheme { throw new Win32Exception(rc); } - final String targetName = getServicePrincipalName(context); + final String targetName = getServicePrincipalName(request); response = getToken(null, null, targetName); } catch (final RuntimeException ex) { failAuthCleanup(); @@ -213,7 +210,7 @@ public class WindowsNegotiateScheme implements AuthScheme { final byte[] continueTokenBytes = Base64.decodeBase64(challenge); final SecBufferDesc continueTokenBuffer = new SecBufferDesc( Sspi.SECBUFFER_TOKEN, continueTokenBytes); - final String targetName = getServicePrincipalName(context); + final String targetName = getServicePrincipalName(request); response = getToken(this.sspiContext, continueTokenBuffer, targetName); } catch (final RuntimeException ex) { failAuthCleanup(); @@ -236,23 +233,14 @@ public class WindowsNegotiateScheme implements AuthScheme { // at http://www.chromium.org/developers/design-documents/http-authentication). Here, // I've chosen to use the host that has been provided in HttpHost so that I don't incur // any additional DNS lookup cost. - private String getServicePrincipalName(final HttpContext context) { - final String spn; + private String getServicePrincipalName(final HttpRequest request) { + String spn = null; if (this.servicePrincipalName != null) { spn = this.servicePrincipalName; } else { - final HttpClientContext clientContext = HttpClientContext.adapt(context); - final HttpHost target = clientContext.getTargetHost(); - if (target != null) { - spn = "HTTP/" + target.getHostName(); - } else { - final RouteInfo route = clientContext.getHttpRoute(); - if (route != null) { - spn = "HTTP/" + route.getTargetHost().getHostName(); - } else { - // Should not happen - spn = null; - } + final URIAuthority authority = request.getAuthority(); + if (authority != null) { + spn = "HTTP/" + authority.getHostName(); } } if (this.log.isDebugEnabled()) { diff --git a/httpclient5-win/src/main/java/org/apache/hc/client5/http/impl/win/WindowsNegotiateSchemeFactory.java b/httpclient5-win/src/main/java/org/apache/hc/client5/http/impl/win/WindowsNegotiateSchemeFactory.java index aa4afd695..96379ee3a 100644 --- a/httpclient5-win/src/main/java/org/apache/hc/client5/http/impl/win/WindowsNegotiateSchemeFactory.java +++ b/httpclient5-win/src/main/java/org/apache/hc/client5/http/impl/win/WindowsNegotiateSchemeFactory.java @@ -30,7 +30,8 @@ package org.apache.hc.client5.http.impl.win; import org.apache.hc.client5.http.auth.AuthScheme; import org.apache.hc.client5.http.auth.AuthSchemeProvider; import org.apache.hc.client5.http.config.AuthSchemes; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.protocol.HttpContext; /** @@ -42,7 +43,7 @@ import org.apache.hc.core5.http.protocol.HttpContext; * * @since 4.4 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class WindowsNegotiateSchemeFactory implements AuthSchemeProvider { private final String servicePrincipalName; diff --git a/httpclient5-win/src/test/java/org/apache/hc/client5/http/impl/win/TestWindowsNegotiateScheme.java b/httpclient5-win/src/test/java/org/apache/hc/client5/http/impl/win/TestWindowsNegotiateScheme.java index e59ae401b..716c86d3d 100644 --- a/httpclient5-win/src/test/java/org/apache/hc/client5/http/impl/win/TestWindowsNegotiateScheme.java +++ b/httpclient5-win/src/test/java/org/apache/hc/client5/http/impl/win/TestWindowsNegotiateScheme.java @@ -34,18 +34,18 @@ import org.apache.hc.client5.http.config.AuthSchemes; import org.apache.hc.client5.http.impl.sync.CloseableHttpClient; import org.apache.hc.client5.http.impl.sync.HttpClientBuilder; import org.apache.hc.client5.http.localserver.LocalServerTestBase; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.sync.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpGet; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; 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.HttpResponse; import org.apache.hc.core5.http.HttpStatus; import org.apache.hc.core5.http.config.Registry; import org.apache.hc.core5.http.config.RegistryBuilder; -import org.apache.hc.core5.http.entity.EntityUtils; import org.apache.hc.core5.http.io.HttpRequestHandler; +import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.http.protocol.HttpContext; import org.junit.After; import org.junit.Assume; @@ -69,11 +69,11 @@ public class TestWindowsNegotiateScheme extends LocalServerTestBase { @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { response.addHeader(HttpHeaders.WWW_AUTHENTICATE, AuthSchemes.SPNEGO); - response.setStatusCode(HttpStatus.SC_UNAUTHORIZED); + response.setCode(HttpStatus.SC_UNAUTHORIZED); } }); diff --git a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientAbortMethod.java b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientAbortMethod.java index 6b161a0b3..33cb670ea 100644 --- a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientAbortMethod.java +++ b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientAbortMethod.java @@ -29,7 +29,7 @@ package org.apache.hc.client5.http.examples; import org.apache.hc.client5.http.impl.sync.CloseableHttpClient; import org.apache.hc.client5.http.impl.sync.HttpClients; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.sync.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpGet; /** @@ -41,10 +41,10 @@ public class ClientAbortMethod { try (CloseableHttpClient httpclient = HttpClients.createDefault()) { HttpGet httpget = new HttpGet("http://httpbin.org/get"); - System.out.println("Executing request " + httpget.getURI()); + System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri()); try (CloseableHttpResponse response = httpclient.execute(httpget)) { System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); + System.out.println(response.getCode() + " " + response.getReasonPhrase()); // Do not feel like reading the response body // Call abort on the request object httpget.abort(); diff --git a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientAuthentication.java b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientAuthentication.java index bab167f74..922c663c4 100644 --- a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientAuthentication.java +++ b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientAuthentication.java @@ -31,9 +31,9 @@ import org.apache.hc.client5.http.auth.UsernamePasswordCredentials; import org.apache.hc.client5.http.impl.sync.BasicCredentialsProvider; import org.apache.hc.client5.http.impl.sync.CloseableHttpClient; import org.apache.hc.client5.http.impl.sync.HttpClients; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.sync.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpGet; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.EntityUtils; /** * A simple example that uses HttpClient to execute an HTTP request against @@ -51,10 +51,10 @@ public class ClientAuthentication { .build()) { HttpGet httpget = new HttpGet("http://httpbin.org/basic-auth/user/passwd"); - System.out.println("Executing request " + httpget.getRequestLine()); + System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri()); try (CloseableHttpResponse response = httpclient.execute(httpget)) { System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); + System.out.println(response.getCode() + " " + response.getReasonPhrase()); System.out.println(EntityUtils.toString(response.getEntity())); } } diff --git a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientChunkEncodedPost.java b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientChunkEncodedPost.java index cfbf55004..f745f18f3 100644 --- a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientChunkEncodedPost.java +++ b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientChunkEncodedPost.java @@ -31,11 +31,11 @@ import java.io.FileInputStream; import org.apache.hc.client5.http.impl.sync.CloseableHttpClient; import org.apache.hc.client5.http.impl.sync.HttpClients; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.sync.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpPost; -import org.apache.hc.core5.http.entity.ContentType; -import org.apache.hc.core5.http.entity.EntityUtils; -import org.apache.hc.core5.http.entity.InputStreamEntity; +import org.apache.hc.core5.http.ContentType; +import org.apache.hc.core5.http.io.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.InputStreamEntity; /** * Example how to use unbuffered chunk-encoded POST request. @@ -63,10 +63,10 @@ public class ClientChunkEncodedPost { httppost.setEntity(reqEntity); - System.out.println("Executing request: " + httppost.getRequestLine()); + System.out.println("Executing request " + httppost.getMethod() + " " + httppost.getUri()); try (CloseableHttpResponse response = httpclient.execute(httppost)) { System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); + System.out.println(response.getCode() + " " + response.getReasonPhrase()); System.out.println(EntityUtils.toString(response.getEntity())); } } diff --git a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientConfiguration.java b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientConfiguration.java index 5128f56f0..6eda01e50 100644 --- a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientConfiguration.java +++ b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientConfiguration.java @@ -53,29 +53,28 @@ import org.apache.hc.client5.http.impl.sync.BasicCredentialsProvider; import org.apache.hc.client5.http.impl.sync.CloseableHttpClient; import org.apache.hc.client5.http.impl.sync.HttpClients; import org.apache.hc.client5.http.io.ManagedHttpClientConnection; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.sync.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.socket.ConnectionSocketFactory; import org.apache.hc.client5.http.socket.PlainConnectionSocketFactory; import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory; +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.HttpHost; -import org.apache.hc.core5.http.HttpRequest; -import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.ParseException; import org.apache.hc.core5.http.config.ConnectionConfig; -import org.apache.hc.core5.http.config.MessageConstraints; +import org.apache.hc.core5.http.config.H1Config; import org.apache.hc.core5.http.config.Registry; import org.apache.hc.core5.http.config.RegistryBuilder; import org.apache.hc.core5.http.config.SocketConfig; -import org.apache.hc.core5.http.entity.EntityUtils; -import org.apache.hc.core5.http.impl.DefaultHttpResponseFactory; +import org.apache.hc.core5.http.impl.io.DefaultClassicHttpResponseFactory; import org.apache.hc.core5.http.impl.io.DefaultHttpRequestWriterFactory; import org.apache.hc.core5.http.io.HttpMessageParser; import org.apache.hc.core5.http.io.HttpMessageParserFactory; import org.apache.hc.core5.http.io.HttpMessageWriterFactory; +import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.http.message.BasicHeader; import org.apache.hc.core5.http.message.BasicLineParser; import org.apache.hc.core5.http.message.LineParser; @@ -92,10 +91,10 @@ public class ClientConfiguration { // Use custom message parser / writer to customize the way HTTP // messages are parsed from and written out to the data stream. - HttpMessageParserFactory responseParserFactory = new DefaultHttpResponseParserFactory() { + HttpMessageParserFactory responseParserFactory = new DefaultHttpResponseParserFactory() { @Override - public HttpMessageParser create(MessageConstraints constraints) { + public HttpMessageParser create(H1Config h1Config) { LineParser lineParser = new BasicLineParser() { @Override @@ -108,18 +107,18 @@ public class ClientConfiguration { } }; - return new LenientHttpResponseParser(lineParser, DefaultHttpResponseFactory.INSTANCE, constraints); + return new LenientHttpResponseParser(lineParser, DefaultClassicHttpResponseFactory.INSTANCE, h1Config); } }; - HttpMessageWriterFactory requestWriterFactory = new DefaultHttpRequestWriterFactory(); + HttpMessageWriterFactory requestWriterFactory = new DefaultHttpRequestWriterFactory(); // Use a custom connection factory to customize the process of // initialization of outgoing HTTP connections. Beside standard connection // configuration parameters HTTP connection factory can define message // parser / writer routines to be employed by individual connections. HttpConnectionFactory connFactory = new ManagedHttpClientConnectionFactory( - requestWriterFactory, responseParserFactory); + H1Config.DEFAULT, requestWriterFactory, responseParserFactory); // Client HTTP connection objects when fully initialized can be bound to // an arbitrary network socket. The process of network socket initialization, @@ -167,7 +166,7 @@ public class ClientConfiguration { connManager.setValidateAfterInactivity(1000); // Create message constraints - MessageConstraints messageConstraints = MessageConstraints.custom() + H1Config messageConstraints = H1Config.custom() .setMaxHeaderCount(200) .setMaxLineLength(2000) .build(); @@ -176,7 +175,6 @@ public class ClientConfiguration { .setMalformedInputAction(CodingErrorAction.IGNORE) .setUnmappableInputAction(CodingErrorAction.IGNORE) .setCharset(StandardCharsets.UTF_8) - .setMessageConstraints(messageConstraints) .build(); // Configure the connection manager to use connection configuration either // by default or for a specific host. @@ -228,12 +226,10 @@ public class ClientConfiguration { context.setCookieStore(cookieStore); context.setCredentialsProvider(credentialsProvider); - System.out.println("executing request " + httpget.getURI()); + System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri()); try (CloseableHttpResponse response = httpclient.execute(httpget, context)) { - HttpEntity entity = response.getEntity(); - System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); + System.out.println(response.getCode() + " " + response.getReasonPhrase()); System.out.println(EntityUtils.toString(response.getEntity())); // Once the request has been executed the local context can diff --git a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientConnectionRelease.java b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientConnectionRelease.java index 08a8d9d91..79f2d5aa3 100644 --- a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientConnectionRelease.java +++ b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientConnectionRelease.java @@ -32,7 +32,7 @@ import java.io.InputStream; import org.apache.hc.client5.http.impl.sync.CloseableHttpClient; import org.apache.hc.client5.http.impl.sync.HttpClients; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.sync.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.core5.http.HttpEntity; @@ -46,10 +46,10 @@ public class ClientConnectionRelease { try (CloseableHttpClient httpclient = HttpClients.createDefault()) { HttpGet httpget = new HttpGet("http://httpbin.org/get"); - System.out.println("Executing request " + httpget.getRequestLine()); + System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri()); try (CloseableHttpResponse response = httpclient.execute(httpget)) { System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); + System.out.println(response.getCode() + " " + response.getReasonPhrase()); // Get hold of the response entity HttpEntity entity = response.getEntity(); diff --git a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientCustomContext.java b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientCustomContext.java index 73074f742..a9190b173 100644 --- a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientCustomContext.java +++ b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientCustomContext.java @@ -34,10 +34,10 @@ import org.apache.hc.client5.http.cookie.Cookie; import org.apache.hc.client5.http.cookie.CookieStore; import org.apache.hc.client5.http.impl.sync.CloseableHttpClient; import org.apache.hc.client5.http.impl.sync.HttpClients; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.sync.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.client5.http.protocol.HttpClientContext; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.EntityUtils; /** * This example demonstrates the use of a local HTTP context populated with @@ -56,12 +56,12 @@ public class ClientCustomContext { localContext.setCookieStore(cookieStore); HttpGet httpget = new HttpGet("http://httpbin.org/cookies"); - System.out.println("Executing request " + httpget.getRequestLine()); + System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri()); // Pass local context as a parameter try (CloseableHttpResponse response = httpclient.execute(httpget, localContext)) { System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); + System.out.println(response.getCode() + " " + response.getReasonPhrase()); List cookies = cookieStore.getCookies(); for (int i = 0; i < cookies.size(); i++) { System.out.println("Local cookie: " + cookies.get(i)); diff --git a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientCustomPublicSuffixList.java b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientCustomPublicSuffixList.java index 996c136c9..4d42544bd 100644 --- a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientCustomPublicSuffixList.java +++ b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientCustomPublicSuffixList.java @@ -33,15 +33,14 @@ import org.apache.hc.client5.http.cookie.CookieSpecProvider; import org.apache.hc.client5.http.impl.cookie.RFC6265CookieSpecProvider; import org.apache.hc.client5.http.impl.sync.CloseableHttpClient; import org.apache.hc.client5.http.impl.sync.HttpClients; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.sync.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.client5.http.psl.PublicSuffixMatcher; import org.apache.hc.client5.http.psl.PublicSuffixMatcherLoader; import org.apache.hc.client5.http.ssl.DefaultHostnameVerifier; -import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.config.Lookup; import org.apache.hc.core5.http.config.RegistryBuilder; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.EntityUtils; /** * This example demonstrates how to use a custom public suffix list. @@ -74,13 +73,11 @@ public class ClientCustomPublicSuffixList { HttpGet httpget = new HttpGet("https://httpbin.org/get"); - System.out.println("executing request " + httpget.getRequestLine()); + System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri()); try (CloseableHttpResponse response = httpclient.execute(httpget)) { - HttpEntity entity = response.getEntity(); - System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); + System.out.println(response.getCode() + " " + response.getReasonPhrase()); System.out.println(EntityUtils.toString(response.getEntity())); } } diff --git a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientCustomSSL.java b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientCustomSSL.java index 11d351ad7..18afa8e2b 100644 --- a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientCustomSSL.java +++ b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientCustomSSL.java @@ -32,12 +32,11 @@ import javax.net.ssl.SSLContext; import org.apache.hc.client5.http.impl.sync.CloseableHttpClient; import org.apache.hc.client5.http.impl.sync.HttpClients; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.sync.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory; import org.apache.hc.client5.http.ssl.TrustSelfSignedStrategy; -import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.ssl.SSLContexts; /** @@ -64,13 +63,11 @@ public class ClientCustomSSL { HttpGet httpget = new HttpGet("https://httpbin.org/"); - System.out.println("Executing request " + httpget.getRequestLine()); + System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri()); try (CloseableHttpResponse response = httpclient.execute(httpget)) { - HttpEntity entity = response.getEntity(); - System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); + System.out.println(response.getCode() + " " + response.getReasonPhrase()); System.out.println(EntityUtils.toString(response.getEntity())); } } diff --git a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientEvictExpiredConnections.java b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientEvictExpiredConnections.java index c46ab29f8..94ca97af6 100644 --- a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientEvictExpiredConnections.java +++ b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientEvictExpiredConnections.java @@ -31,9 +31,9 @@ import java.util.concurrent.TimeUnit; import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager; import org.apache.hc.client5.http.impl.sync.CloseableHttpClient; import org.apache.hc.client5.http.impl.sync.HttpClients; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.sync.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpGet; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.pool.PoolStats; /** @@ -61,11 +61,11 @@ public class ClientEvictExpiredConnections { String requestURI = urisToGet[i]; HttpGet request = new HttpGet(requestURI); - System.out.println("Executing request " + requestURI); + System.out.println("Executing request " + request.getMethod() + " " + request.getRequestUri()); try (CloseableHttpResponse response = httpclient.execute(request)) { System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); + System.out.println(response.getCode() + " " + response.getReasonPhrase()); EntityUtils.consume(response.getEntity()); } } diff --git a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientExecuteProxy.java b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientExecuteProxy.java index c17a7c050..e67a13c14 100644 --- a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientExecuteProxy.java +++ b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientExecuteProxy.java @@ -30,10 +30,10 @@ package org.apache.hc.client5.http.examples; import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.impl.sync.CloseableHttpClient; import org.apache.hc.client5.http.impl.sync.HttpClients; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.sync.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.core5.http.HttpHost; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.EntityUtils; /** * How to send a request via proxy. @@ -53,11 +53,12 @@ public class ClientExecuteProxy { HttpGet request = new HttpGet("/get"); request.setConfig(config); - System.out.println("Executing request " + request.getRequestLine() + " to " + target + " via " + proxy); + System.out.println("Executing request " + request.getMethod() + " " + request.getUri() + + " via " + proxy); try (CloseableHttpResponse response = httpclient.execute(target, request)) { System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); + System.out.println(response.getCode() + " " + response.getReasonPhrase()); System.out.println(EntityUtils.toString(response.getEntity())); } } diff --git a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientExecuteSOCKS.java b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientExecuteSOCKS.java index 0b07388fd..64a25d876 100644 --- a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientExecuteSOCKS.java +++ b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientExecuteSOCKS.java @@ -37,14 +37,14 @@ import org.apache.hc.client5.http.ConnectTimeoutException; import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager; import org.apache.hc.client5.http.impl.sync.CloseableHttpClient; import org.apache.hc.client5.http.impl.sync.HttpClients; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.sync.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.socket.ConnectionSocketFactory; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.config.Registry; import org.apache.hc.core5.http.config.RegistryBuilder; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.http.protocol.HttpContext; /** @@ -69,10 +69,11 @@ public class ClientExecuteSOCKS { HttpHost target = new HttpHost("httpbin.org", 80, "http"); HttpGet request = new HttpGet("/get"); - System.out.println("Executing request " + request + " to " + target + " via SOCKS proxy " + socksaddr); + System.out.println("Executing request " + request.getMethod() + " " + request.getUri() + + " via SOCKS proxy " + socksaddr); try (CloseableHttpResponse response = httpclient.execute(target, request, context)) { System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); + System.out.println(response.getCode() + " " + response.getReasonPhrase()); System.out.println(EntityUtils.toString(response.getEntity())); } } diff --git a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientFormLogin.java b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientFormLogin.java index c9185e5ba..b37a06e26 100644 --- a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientFormLogin.java +++ b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientFormLogin.java @@ -33,12 +33,12 @@ import org.apache.hc.client5.http.cookie.BasicCookieStore; import org.apache.hc.client5.http.cookie.Cookie; import org.apache.hc.client5.http.impl.sync.CloseableHttpClient; import org.apache.hc.client5.http.impl.sync.HttpClients; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.sync.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.client5.http.methods.HttpUriRequest; import org.apache.hc.client5.http.methods.RequestBuilder; import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.EntityUtils; /** * A example that demonstrates how HttpClient APIs can be used to perform @@ -55,7 +55,7 @@ public class ClientFormLogin { try (CloseableHttpResponse response1 = httpclient.execute(httpget)) { HttpEntity entity = response1.getEntity(); - System.out.println("Login form get: " + response1.getStatusLine()); + System.out.println("Login form get: " + response1.getCode() + " " + response1.getReasonPhrase()); EntityUtils.consume(entity); System.out.println("Initial set of cookies:"); @@ -77,7 +77,7 @@ public class ClientFormLogin { try (CloseableHttpResponse response2 = httpclient.execute(login)) { HttpEntity entity = response2.getEntity(); - System.out.println("Login form get: " + response2.getStatusLine()); + System.out.println("Login form get: " + response2.getCode() + " " + response2.getReasonPhrase()); EntityUtils.consume(entity); System.out.println("Post logon cookies:"); diff --git a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientMultiThreadedExecution.java b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientMultiThreadedExecution.java index 72bfa9050..eac025025 100644 --- a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientMultiThreadedExecution.java +++ b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientMultiThreadedExecution.java @@ -29,10 +29,10 @@ package org.apache.hc.client5.http.examples; import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager; import org.apache.hc.client5.http.impl.sync.CloseableHttpClient; import org.apache.hc.client5.http.impl.sync.HttpClients; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.sync.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.http.protocol.BasicHttpContext; import org.apache.hc.core5.http.protocol.HttpContext; @@ -102,7 +102,7 @@ public class ClientMultiThreadedExecution { @Override public void run() { try { - System.out.println(id + " - about to get something from " + httpget.getURI()); + System.out.println(id + " - about to get something from " + httpget.getUri()); try (CloseableHttpResponse response = httpClient.execute(httpget, context)) { System.out.println(id + " - get executed"); // get the response body as an array of bytes diff --git a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientMultipartFormPost.java b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientMultipartFormPost.java index b1a0082fa..a84706e79 100644 --- a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientMultipartFormPost.java +++ b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientMultipartFormPost.java @@ -33,11 +33,11 @@ import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder; import org.apache.hc.client5.http.entity.mime.StringBody; import org.apache.hc.client5.http.impl.sync.CloseableHttpClient; import org.apache.hc.client5.http.impl.sync.HttpClients; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.sync.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpPost; +import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.entity.ContentType; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.EntityUtils; /** * Example how to use multipart/form encoded POST request. @@ -64,10 +64,10 @@ public class ClientMultipartFormPost { httppost.setEntity(reqEntity); - System.out.println("executing request " + httppost.getRequestLine()); + System.out.println("executing request " + httppost); try (CloseableHttpResponse response = httpclient.execute(httppost)) { System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); + System.out.println(response); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); diff --git a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientPreemptiveBasicAuthentication.java b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientPreemptiveBasicAuthentication.java index 847c7ddeb..86724955d 100644 --- a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientPreemptiveBasicAuthentication.java +++ b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientPreemptiveBasicAuthentication.java @@ -30,11 +30,11 @@ import org.apache.hc.client5.http.auth.UsernamePasswordCredentials; import org.apache.hc.client5.http.impl.auth.BasicScheme; import org.apache.hc.client5.http.impl.sync.CloseableHttpClient; import org.apache.hc.client5.http.impl.sync.HttpClients; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.sync.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.core5.http.HttpHost; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.EntityUtils; /** * An example of HttpClient can be customized to authenticate @@ -61,11 +61,11 @@ public class ClientPreemptiveBasicAuthentication { HttpGet httpget = new HttpGet("http://httpbin.org/hidden-basic-auth/user/passwd"); - System.out.println("Executing request " + httpget.getRequestLine() + " to target " + target); + System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri()); for (int i = 0; i < 3; i++) { try (CloseableHttpResponse response = httpclient.execute(httpget, localContext)) { System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); + System.out.println(response.getCode() + " " + response.getReasonPhrase()); System.out.println(EntityUtils.toString(response.getEntity())); } } diff --git a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientPreemptiveDigestAuthentication.java b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientPreemptiveDigestAuthentication.java index 66ad18f5d..12ac4ff94 100644 --- a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientPreemptiveDigestAuthentication.java +++ b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientPreemptiveDigestAuthentication.java @@ -32,11 +32,11 @@ import org.apache.hc.client5.http.impl.auth.BasicAuthCache; import org.apache.hc.client5.http.impl.auth.DigestScheme; import org.apache.hc.client5.http.impl.sync.CloseableHttpClient; import org.apache.hc.client5.http.impl.sync.HttpClients; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.sync.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.core5.http.HttpHost; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.EntityUtils; /** * An example of HttpClient can be customized to authenticate @@ -68,11 +68,11 @@ public class ClientPreemptiveDigestAuthentication { HttpGet httpget = new HttpGet("http://httpbin.org/digest-auth/auth/user/passwd"); - System.out.println("Executing request " + httpget.getRequestLine() + " to target " + target); + System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri()); for (int i = 0; i < 3; i++) { try (CloseableHttpResponse response = httpclient.execute(target, httpget, localContext)) { System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); + System.out.println(response.getCode() + " " + response.getReasonPhrase()); EntityUtils.consume(response.getEntity()); } } diff --git a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientProxyAuthentication.java b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientProxyAuthentication.java index f1e9f27db..11b682e3d 100644 --- a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientProxyAuthentication.java +++ b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientProxyAuthentication.java @@ -32,10 +32,10 @@ import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.impl.sync.BasicCredentialsProvider; import org.apache.hc.client5.http.impl.sync.CloseableHttpClient; import org.apache.hc.client5.http.impl.sync.HttpClients; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.sync.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.core5.http.HttpHost; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.EntityUtils; /** * A simple example that uses HttpClient to execute an HTTP request @@ -62,11 +62,12 @@ public class ClientProxyAuthentication { HttpGet httpget = new HttpGet("/basic-auth/user/passwd"); httpget.setConfig(config); - System.out.println("Executing request " + httpget.getRequestLine() + " to " + target + " via " + proxy); + System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri() + + " via " + proxy); try (CloseableHttpResponse response = httpclient.execute(target, httpget)) { System.out.println("----------------------------------------"); - System.out.println(response.getStatusLine()); + System.out.println(response.getCode() + " " + response.getReasonPhrase()); System.out.println(EntityUtils.toString(response.getEntity())); } } diff --git a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientWithRequestFuture.java b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientWithRequestFuture.java index 8dfd98aeb..e51778eff 100644 --- a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientWithRequestFuture.java +++ b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientWithRequestFuture.java @@ -38,10 +38,10 @@ import org.apache.hc.client5.http.impl.sync.HttpClientBuilder; import org.apache.hc.client5.http.impl.sync.HttpRequestFutureTask; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.client5.http.protocol.HttpClientContext; -import org.apache.hc.client5.http.sync.ResponseHandler; import org.apache.hc.core5.concurrent.FutureCallback; -import org.apache.hc.core5.http.HttpResponse; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.io.ResponseHandler; public class ClientWithRequestFuture { @@ -56,9 +56,9 @@ public class ClientWithRequestFuture { // Because things are asynchronous, you must provide a ResponseHandler ResponseHandler handler = new ResponseHandler() { @Override - public Boolean handleResponse(HttpResponse response) throws IOException { + public Boolean handleResponse(ClassicHttpResponse response) throws IOException { // simply return true if the status was OK - return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK; + return response.getCode() == HttpStatus.SC_OK; } }; @@ -115,4 +115,4 @@ public class ClientWithRequestFuture { System.out.println("It was ok? " + wasItOk4); } } -} \ No newline at end of file +} diff --git a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientWithResponseHandler.java b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientWithResponseHandler.java index 1ec5d0205..7e1905cb6 100644 --- a/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientWithResponseHandler.java +++ b/httpclient5/src/examples/org/apache/hc/client5/http/examples/ClientWithResponseHandler.java @@ -33,11 +33,12 @@ import org.apache.hc.client5.http.impl.sync.CloseableHttpClient; import org.apache.hc.client5.http.impl.sync.HttpClients; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.client5.http.protocol.ClientProtocolException; -import org.apache.hc.client5.http.sync.ResponseHandler; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.HttpResponse; +import org.apache.hc.core5.http.HttpStatus; import org.apache.hc.core5.http.ParseException; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.io.ResponseHandler; +import org.apache.hc.core5.http.io.entity.EntityUtils; /** * This example demonstrates the use of the {@link ResponseHandler} to simplify @@ -49,16 +50,16 @@ public class ClientWithResponseHandler { try (CloseableHttpClient httpclient = HttpClients.createDefault()) { HttpGet httpget = new HttpGet("http://httpbin.org/get"); - System.out.println("Executing request " + httpget.getRequestLine()); + System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri()); // Create a custom response handler ResponseHandler responseHandler = new ResponseHandler() { @Override public String handleResponse( - final HttpResponse response) throws IOException { - int status = response.getStatusLine().getStatusCode(); - if (status >= 200 && status < 300) { + final ClassicHttpResponse response) throws IOException { + int status = response.getCode(); + if (status >= HttpStatus.SC_SUCCESS && status < HttpStatus.SC_REDIRECTION) { HttpEntity entity = response.getEntity(); try { return entity != null ? EntityUtils.toString(entity) : null; diff --git a/httpclient5/src/examples/org/apache/hc/client5/http/examples/QuickStart.java b/httpclient5/src/examples/org/apache/hc/client5/http/examples/QuickStart.java index 1621057e5..9edd9caac 100644 --- a/httpclient5/src/examples/org/apache/hc/client5/http/examples/QuickStart.java +++ b/httpclient5/src/examples/org/apache/hc/client5/http/examples/QuickStart.java @@ -32,12 +32,12 @@ import java.util.List; import org.apache.hc.client5.http.entity.UrlEncodedFormEntity; import org.apache.hc.client5.http.impl.sync.CloseableHttpClient; import org.apache.hc.client5.http.impl.sync.HttpClients; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.sync.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.client5.http.methods.HttpPost; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.NameValuePair; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.http.message.BasicNameValuePair; public class QuickStart { @@ -53,7 +53,7 @@ public class QuickStart { // connection cannot be safely re-used and will be shut down and discarded // by the connection manager. try (CloseableHttpResponse response1 = httpclient.execute(httpGet)) { - System.out.println(response1.getStatusLine()); + System.out.println(response1.getCode() + " " + response1.getReasonPhrase()); HttpEntity entity1 = response1.getEntity(); // do something useful with the response body // and ensure it is fully consumed @@ -67,7 +67,7 @@ public class QuickStart { httpPost.setEntity(new UrlEncodedFormEntity(nvps)); try (CloseableHttpResponse response2 = httpclient.execute(httpPost)) { - System.out.println(response2.getStatusLine()); + System.out.println(response2.getCode() + " " + response2.getReasonPhrase()); HttpEntity entity2 = response2.getEntity(); // do something useful with the response body // and ensure it is fully consumed diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/ConnectTimeoutException.java b/httpclient5/src/main/java/org/apache/hc/client5/http/ConnectTimeoutException.java index c105eaa93..d65ad62c6 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/ConnectTimeoutException.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/ConnectTimeoutException.java @@ -32,7 +32,6 @@ import java.io.InterruptedIOException; import java.net.InetAddress; import java.util.Arrays; -import org.apache.hc.core5.annotation.Immutable; import org.apache.hc.core5.http.HttpHost; /** @@ -42,7 +41,6 @@ import org.apache.hc.core5.http.HttpHost; * * @since 4.0 */ -@Immutable public class ConnectTimeoutException extends InterruptedIOException { private static final long serialVersionUID = -4816682903149535989L; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/ConnectionPoolTimeoutException.java b/httpclient5/src/main/java/org/apache/hc/client5/http/ConnectionPoolTimeoutException.java index 995118252..586b9c3fa 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/ConnectionPoolTimeoutException.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/ConnectionPoolTimeoutException.java @@ -27,8 +27,6 @@ package org.apache.hc.client5.http; -import org.apache.hc.core5.annotation.Immutable; - /** * A timeout while waiting for an available connection * from a connection manager. @@ -36,7 +34,6 @@ import org.apache.hc.core5.annotation.Immutable; * * @since 4.0 */ -@Immutable public class ConnectionPoolTimeoutException extends ConnectTimeoutException { private static final long serialVersionUID = -7898874842020245128L; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/HttpHostConnectException.java b/httpclient5/src/main/java/org/apache/hc/client5/http/HttpHostConnectException.java index 7f60757ce..0d08a54e7 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/HttpHostConnectException.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/HttpHostConnectException.java @@ -31,7 +31,6 @@ import java.net.ConnectException; import java.net.InetAddress; import java.util.Arrays; -import org.apache.hc.core5.annotation.Immutable; import org.apache.hc.core5.http.HttpHost; /** @@ -40,7 +39,6 @@ import org.apache.hc.core5.http.HttpHost; * * @since 4.0 */ -@Immutable public class HttpHostConnectException extends ConnectException { private static final long serialVersionUID = -3194482710275220224L; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/HttpRoute.java b/httpclient5/src/main/java/org/apache/hc/client5/http/HttpRoute.java index b9bafcc19..8558386fa 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/HttpRoute.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/HttpRoute.java @@ -34,7 +34,8 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.util.Args; import org.apache.hc.core5.util.LangUtils; @@ -44,7 +45,7 @@ import org.apache.hc.core5.util.LangUtils; * * @since 4.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public final class HttpRoute implements RouteInfo, Cloneable { /** The target host to connect to. */ diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/RouteTracker.java b/httpclient5/src/main/java/org/apache/hc/client5/http/RouteTracker.java index 68eb2dda9..38d8ef2ab 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/RouteTracker.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/RouteTracker.java @@ -29,7 +29,6 @@ package org.apache.hc.client5.http; import java.net.InetAddress; -import org.apache.hc.core5.annotation.NotThreadSafe; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.util.Args; import org.apache.hc.core5.util.Asserts; @@ -40,7 +39,6 @@ import org.apache.hc.core5.util.LangUtils; * * @since 4.0 */ -@NotThreadSafe public final class RouteTracker implements RouteInfo, Cloneable { /** The target host to connect to. */ diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/UnsupportedSchemeException.java b/httpclient5/src/main/java/org/apache/hc/client5/http/UnsupportedSchemeException.java index 8e6c1b8c3..bf445fad7 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/UnsupportedSchemeException.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/UnsupportedSchemeException.java @@ -29,14 +29,11 @@ package org.apache.hc.client5.http; import java.io.IOException; -import org.apache.hc.core5.annotation.Immutable; - /** * Signals failure to establish connection using an unknown protocol scheme. * * @since 4.3 */ -@Immutable public class UnsupportedSchemeException extends IOException { private static final long serialVersionUID = 3597127619218687636L; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/auth/AuthChallenge.java b/httpclient5/src/main/java/org/apache/hc/client5/http/auth/AuthChallenge.java index ab6a6f88e..c5a968624 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/auth/AuthChallenge.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/auth/AuthChallenge.java @@ -31,7 +31,8 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.NameValuePair; import org.apache.hc.core5.util.Args; @@ -41,7 +42,7 @@ import org.apache.hc.core5.util.Args; * * @since 5.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public final class AuthChallenge { private final String scheme; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/auth/AuthExchange.java b/httpclient5/src/main/java/org/apache/hc/client5/http/auth/AuthExchange.java index 2594b496e..669787b94 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/auth/AuthExchange.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/auth/AuthExchange.java @@ -28,7 +28,6 @@ package org.apache.hc.client5.http.auth; import java.util.Queue; -import org.apache.hc.core5.annotation.NotThreadSafe; import org.apache.hc.core5.util.Args; /** @@ -37,7 +36,6 @@ import org.apache.hc.core5.util.Args; * * @since 4.5 */ -@NotThreadSafe public class AuthExchange { public enum State { diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/auth/AuthScope.java b/httpclient5/src/main/java/org/apache/hc/client5/http/auth/AuthScope.java index 8a5055492..294aa7806 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/auth/AuthScope.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/auth/AuthScope.java @@ -28,7 +28,8 @@ package org.apache.hc.client5.http.auth; import java.util.Locale; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.util.Args; import org.apache.hc.core5.util.LangUtils; @@ -42,7 +43,7 @@ import org.apache.hc.core5.util.LangUtils; *

* @since 4.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class AuthScope { /** diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/auth/AuthenticationException.java b/httpclient5/src/main/java/org/apache/hc/client5/http/auth/AuthenticationException.java index d803b28f0..80d208a71 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/auth/AuthenticationException.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/auth/AuthenticationException.java @@ -26,7 +26,6 @@ */ package org.apache.hc.client5.http.auth; -import org.apache.hc.core5.annotation.Immutable; import org.apache.hc.core5.http.ProtocolException; /** @@ -35,7 +34,6 @@ import org.apache.hc.core5.http.ProtocolException; * * @since 4.0 */ -@Immutable public class AuthenticationException extends ProtocolException { private static final long serialVersionUID = -6794031905674764776L; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/auth/BasicUserPrincipal.java b/httpclient5/src/main/java/org/apache/hc/client5/http/auth/BasicUserPrincipal.java index b92d217a1..b062675ea 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/auth/BasicUserPrincipal.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/auth/BasicUserPrincipal.java @@ -29,7 +29,8 @@ package org.apache.hc.client5.http.auth; import java.io.Serializable; import java.security.Principal; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.util.Args; import org.apache.hc.core5.util.LangUtils; @@ -38,7 +39,7 @@ import org.apache.hc.core5.util.LangUtils; * * @since 4.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public final class BasicUserPrincipal implements Principal, Serializable { private static final long serialVersionUID = -2266305184969850467L; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/auth/InvalidCredentialsException.java b/httpclient5/src/main/java/org/apache/hc/client5/http/auth/InvalidCredentialsException.java index 926f7605a..74631a531 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/auth/InvalidCredentialsException.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/auth/InvalidCredentialsException.java @@ -26,7 +26,8 @@ */ package org.apache.hc.client5.http.auth; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; /** * Authentication credentials required to respond to a authentication @@ -35,7 +36,7 @@ import org.apache.hc.core5.annotation.Immutable; * * @since 4.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class InvalidCredentialsException extends AuthenticationException { private static final long serialVersionUID = -4834003835215460648L; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/auth/KerberosCredentials.java b/httpclient5/src/main/java/org/apache/hc/client5/http/auth/KerberosCredentials.java index 778fefe11..fc49bcb34 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/auth/KerberosCredentials.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/auth/KerberosCredentials.java @@ -29,7 +29,8 @@ package org.apache.hc.client5.http.auth; import java.io.Serializable; import java.security.Principal; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.ietf.jgss.GSSCredential; /** @@ -37,7 +38,7 @@ import org.ietf.jgss.GSSCredential; * * @since 4.4 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class KerberosCredentials implements Credentials, Serializable { private static final long serialVersionUID = 487421613855550713L; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/auth/MalformedChallengeException.java b/httpclient5/src/main/java/org/apache/hc/client5/http/auth/MalformedChallengeException.java index a2a6540f5..d2ba02e9d 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/auth/MalformedChallengeException.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/auth/MalformedChallengeException.java @@ -26,7 +26,6 @@ */ package org.apache.hc.client5.http.auth; -import org.apache.hc.core5.annotation.Immutable; import org.apache.hc.core5.http.ProtocolException; /** @@ -36,7 +35,6 @@ import org.apache.hc.core5.http.ProtocolException; * * @since 4.0 */ -@Immutable public class MalformedChallengeException extends ProtocolException { private static final long serialVersionUID = 814586927989932284L; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/auth/NTCredentials.java b/httpclient5/src/main/java/org/apache/hc/client5/http/auth/NTCredentials.java index ddaa66d31..e9698bba7 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/auth/NTCredentials.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/auth/NTCredentials.java @@ -30,7 +30,8 @@ import java.io.Serializable; import java.security.Principal; import java.util.Locale; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.util.Args; import org.apache.hc.core5.util.LangUtils; @@ -40,7 +41,7 @@ import org.apache.hc.core5.util.LangUtils; * * @since 4.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class NTCredentials implements Credentials, Serializable { private static final long serialVersionUID = -7385699315228907265L; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/auth/NTUserPrincipal.java b/httpclient5/src/main/java/org/apache/hc/client5/http/auth/NTUserPrincipal.java index 484049840..78e36ff2c 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/auth/NTUserPrincipal.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/auth/NTUserPrincipal.java @@ -30,7 +30,8 @@ import java.io.Serializable; import java.security.Principal; import java.util.Locale; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.util.Args; import org.apache.hc.core5.util.LangUtils; @@ -39,7 +40,7 @@ import org.apache.hc.core5.util.LangUtils; * * @since 4.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class NTUserPrincipal implements Principal, Serializable { private static final long serialVersionUID = -6870169797924406894L; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/auth/UsernamePasswordCredentials.java b/httpclient5/src/main/java/org/apache/hc/client5/http/auth/UsernamePasswordCredentials.java index bea1f8051..ca49b694c 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/auth/UsernamePasswordCredentials.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/auth/UsernamePasswordCredentials.java @@ -29,7 +29,8 @@ package org.apache.hc.client5.http.auth; import java.io.Serializable; import java.security.Principal; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.util.Args; import org.apache.hc.core5.util.LangUtils; @@ -39,7 +40,7 @@ import org.apache.hc.core5.util.LangUtils; * * @since 4.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class UsernamePasswordCredentials implements Credentials, Serializable { private static final long serialVersionUID = 243343858802739403L; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/auth/util/ByteArrayBuilder.java b/httpclient5/src/main/java/org/apache/hc/client5/http/auth/util/ByteArrayBuilder.java index e606fb451..138f68156 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/auth/util/ByteArrayBuilder.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/auth/util/ByteArrayBuilder.java @@ -35,14 +35,15 @@ import java.nio.charset.CoderResult; import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; /** * Builder class for sequences of bytes. * * @since 5.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class ByteArrayBuilder { private CharsetEncoder charsetEncoder; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/config/AuthSchemes.java b/httpclient5/src/main/java/org/apache/hc/client5/http/config/AuthSchemes.java index fda4e011a..a33454cb0 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/config/AuthSchemes.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/config/AuthSchemes.java @@ -27,14 +27,15 @@ package org.apache.hc.client5.http.config; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; /** * Standard authentication schemes supported by HttpClient. * * @since 4.3 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public final class AuthSchemes { /** diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/config/CookieSpecs.java b/httpclient5/src/main/java/org/apache/hc/client5/http/config/CookieSpecs.java index 718e183cf..5c2465f7c 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/config/CookieSpecs.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/config/CookieSpecs.java @@ -27,14 +27,15 @@ package org.apache.hc.client5.http.config; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; /** * Standard cookie specifications supported by HttpClient. * * @since 4.3 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public final class CookieSpecs { /** diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/config/RequestConfig.java b/httpclient5/src/main/java/org/apache/hc/client5/http/config/RequestConfig.java index fa6c35768..d7f86d720 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/config/RequestConfig.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/config/RequestConfig.java @@ -31,13 +31,14 @@ import java.net.InetAddress; import java.util.Collection; import java.util.concurrent.TimeUnit; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.HttpHost; /** * Immutable class encapsulating request configuration items. */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class RequestConfig implements Cloneable { private static final int DEFAULT_CONNECTION_REQUEST_TIMEOUT = (int) TimeUnit.MILLISECONDS.convert(3, TimeUnit.MINUTES); @@ -65,7 +66,7 @@ public class RequestConfig implements Cloneable { * Intended for CDI compatibility */ protected RequestConfig() { - this(false, null, null, false, null, false, false, false, 0, false, null, null, + this(false, null, null, null, false, false, 0, false, null, null, DEFAULT_CONNECTION_REQUEST_TIMEOUT, DEFAULT_CONNECT_TIMEOUT, DEFAULT_SOCKET_TIMEOUT, false); } @@ -73,10 +74,8 @@ public class RequestConfig implements Cloneable { final boolean expectContinueEnabled, final HttpHost proxy, final InetAddress localAddress, - final boolean staleConnectionCheckEnabled, final String cookieSpec, final boolean redirectsEnabled, - final boolean relativeRedirectsAllowed, final boolean circularRedirectsAllowed, final int maxRedirects, final boolean authenticationEnabled, @@ -343,10 +342,8 @@ public class RequestConfig implements Cloneable { private boolean expectContinueEnabled; private HttpHost proxy; private InetAddress localAddress; - private boolean staleConnectionCheckEnabled; private String cookieSpec; private boolean redirectsEnabled; - private boolean relativeRedirectsAllowed; private boolean circularRedirectsAllowed; private int maxRedirects; private boolean authenticationEnabled; @@ -359,10 +356,8 @@ public class RequestConfig implements Cloneable { Builder() { super(); - this.staleConnectionCheckEnabled = false; this.redirectsEnabled = true; this.maxRedirects = 50; - this.relativeRedirectsAllowed = true; this.authenticationEnabled = true; this.connectionRequestTimeout = DEFAULT_CONNECTION_REQUEST_TIMEOUT; this.connectTimeout = DEFAULT_CONNECT_TIMEOUT; @@ -395,11 +390,6 @@ public class RequestConfig implements Cloneable { return this; } - public Builder setRelativeRedirectsAllowed(final boolean relativeRedirectsAllowed) { - this.relativeRedirectsAllowed = relativeRedirectsAllowed; - return this; - } - public Builder setCircularRedirectsAllowed(final boolean circularRedirectsAllowed) { this.circularRedirectsAllowed = circularRedirectsAllowed; return this; @@ -445,20 +435,13 @@ public class RequestConfig implements Cloneable { return this; } - public Builder setStaleConnectionCheckEnabled(final boolean staleConnectionCheckEnabled) { - this.staleConnectionCheckEnabled = staleConnectionCheckEnabled; - return this; - } - public RequestConfig build() { return new RequestConfig( expectContinueEnabled, proxy, localAddress, - staleConnectionCheckEnabled, cookieSpec, redirectsEnabled, - relativeRedirectsAllowed, circularRedirectsAllowed, maxRedirects, authenticationEnabled, diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/cookie/BasicCookieStore.java b/httpclient5/src/main/java/org/apache/hc/client5/http/cookie/BasicCookieStore.java index 340fe55ab..4d3e0afdb 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/cookie/BasicCookieStore.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/cookie/BasicCookieStore.java @@ -33,8 +33,8 @@ import java.util.Iterator; import java.util.List; import java.util.TreeSet; -import org.apache.hc.core5.annotation.GuardedBy; -import org.apache.hc.core5.annotation.ThreadSafe; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; /** * Default implementation of {@link CookieStore} @@ -42,12 +42,11 @@ import org.apache.hc.core5.annotation.ThreadSafe; * * @since 4.0 */ -@ThreadSafe +@Contract(threading = ThreadingBehavior.SAFE) public class BasicCookieStore implements CookieStore, Serializable { private static final long serialVersionUID = -7581093305228232025L; - @GuardedBy("this") private final TreeSet cookies; public BasicCookieStore() { diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/cookie/CookieIdentityComparator.java b/httpclient5/src/main/java/org/apache/hc/client5/http/cookie/CookieIdentityComparator.java index 487baba56..fb17ec14e 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/cookie/CookieIdentityComparator.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/cookie/CookieIdentityComparator.java @@ -30,7 +30,8 @@ package org.apache.hc.client5.http.cookie; import java.io.Serializable; import java.util.Comparator; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; /** * This cookie comparator can be used to compare identity of cookies. @@ -40,7 +41,7 @@ import org.apache.hc.core5.annotation.Immutable; * * @since 4.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class CookieIdentityComparator implements Serializable, Comparator { private static final long serialVersionUID = 4466565437490631532L; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/cookie/CookieOrigin.java b/httpclient5/src/main/java/org/apache/hc/client5/http/cookie/CookieOrigin.java index 3b3335bdc..a79434f9e 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/cookie/CookieOrigin.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/cookie/CookieOrigin.java @@ -28,7 +28,8 @@ package org.apache.hc.client5.http.cookie; import java.util.Locale; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.util.Args; import org.apache.hc.core5.util.TextUtils; @@ -38,7 +39,7 @@ import org.apache.hc.core5.util.TextUtils; * * @since 4.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public final class CookieOrigin { private final String host; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/cookie/CookiePathComparator.java b/httpclient5/src/main/java/org/apache/hc/client5/http/cookie/CookiePathComparator.java index 89ef64e08..6401ba356 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/cookie/CookiePathComparator.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/cookie/CookiePathComparator.java @@ -30,7 +30,8 @@ package org.apache.hc.client5.http.cookie; import java.io.Serializable; import java.util.Comparator; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; /** * This cookie comparator ensures that multiple cookies satisfying @@ -47,7 +48,7 @@ import org.apache.hc.core5.annotation.Immutable; * * @since 4.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class CookiePathComparator implements Serializable, Comparator { public static final CookiePathComparator INSTANCE = new CookiePathComparator(); diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/cookie/CookiePriorityComparator.java b/httpclient5/src/main/java/org/apache/hc/client5/http/cookie/CookiePriorityComparator.java index d7e55897e..f0ff1ac82 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/cookie/CookiePriorityComparator.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/cookie/CookiePriorityComparator.java @@ -30,7 +30,8 @@ package org.apache.hc.client5.http.cookie; import java.util.Comparator; import java.util.Date; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; /** * This cookie comparator ensures that cookies with longer paths take precedence over @@ -39,7 +40,7 @@ import org.apache.hc.core5.annotation.Immutable; * * @since 4.4 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class CookiePriorityComparator implements Comparator { public static final CookiePriorityComparator INSTANCE = new CookiePriorityComparator(); diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/cookie/CookieRestrictionViolationException.java b/httpclient5/src/main/java/org/apache/hc/client5/http/cookie/CookieRestrictionViolationException.java index 7c72a49d4..f7a3dc43f 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/cookie/CookieRestrictionViolationException.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/cookie/CookieRestrictionViolationException.java @@ -27,15 +27,12 @@ package org.apache.hc.client5.http.cookie; -import org.apache.hc.core5.annotation.Immutable; - /** * Signals that a cookie violates a restriction imposed by the cookie * specification. * * @since 4.1 */ -@Immutable public class CookieRestrictionViolationException extends MalformedCookieException { private static final long serialVersionUID = 7371235577078589013L; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/cookie/MalformedCookieException.java b/httpclient5/src/main/java/org/apache/hc/client5/http/cookie/MalformedCookieException.java index 68cde0073..a24768abf 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/cookie/MalformedCookieException.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/cookie/MalformedCookieException.java @@ -27,7 +27,6 @@ package org.apache.hc.client5.http.cookie; -import org.apache.hc.core5.annotation.Immutable; import org.apache.hc.core5.http.ProtocolException; /** @@ -37,7 +36,6 @@ import org.apache.hc.core5.http.ProtocolException; * * @since 4.0 */ -@Immutable public class MalformedCookieException extends ProtocolException { private static final long serialVersionUID = -6695462944287282185L; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/DecompressingEntity.java b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/DecompressingEntity.java index a838e3386..fbc8bcc62 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/DecompressingEntity.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/DecompressingEntity.java @@ -31,7 +31,7 @@ import java.io.InputStream; import java.io.OutputStream; import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.entity.HttpEntityWrapper; +import org.apache.hc.core5.http.io.entity.HttpEntityWrapper; import org.apache.hc.core5.util.Args; /** diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/DeflateDecompressingEntity.java b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/DeflateDecompressingEntity.java index 3b64b431f..34c89cc43 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/DeflateDecompressingEntity.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/DeflateDecompressingEntity.java @@ -32,7 +32,7 @@ import java.io.InputStream; import org.apache.hc.core5.http.HttpEntity; /** - * {@link org.apache.hc.core5.http.entity.HttpEntityWrapper} responsible for + * {@link org.apache.hc.core5.http.io.entity.HttpEntityWrapper} responsible for * handling deflate Content Coded responses. In RFC2616 terms, {@code deflate} * means a {@code zlib} stream as defined in RFC1950. Some server * implementations have misinterpreted RFC2616 to mean that a diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/EntityBuilder.java b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/EntityBuilder.java index 730139292..774c17514 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/EntityBuilder.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/EntityBuilder.java @@ -33,17 +33,16 @@ import java.io.Serializable; import java.util.Arrays; import java.util.List; -import org.apache.hc.core5.annotation.NotThreadSafe; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.NameValuePair; -import org.apache.hc.core5.http.entity.AbstractHttpEntity; -import org.apache.hc.core5.http.entity.BasicHttpEntity; -import org.apache.hc.core5.http.entity.ByteArrayEntity; -import org.apache.hc.core5.http.entity.ContentType; -import org.apache.hc.core5.http.entity.FileEntity; -import org.apache.hc.core5.http.entity.InputStreamEntity; -import org.apache.hc.core5.http.entity.SerializableEntity; -import org.apache.hc.core5.http.entity.StringEntity; +import org.apache.hc.core5.http.io.entity.AbstractHttpEntity; +import org.apache.hc.core5.http.io.entity.BasicHttpEntity; +import org.apache.hc.core5.http.io.entity.ByteArrayEntity; +import org.apache.hc.core5.http.ContentType; +import org.apache.hc.core5.http.io.entity.FileEntity; +import org.apache.hc.core5.http.io.entity.InputStreamEntity; +import org.apache.hc.core5.http.io.entity.SerializableEntity; +import org.apache.hc.core5.http.io.entity.StringEntity; /** * Builder for {@link HttpEntity} instances. @@ -63,7 +62,6 @@ import org.apache.hc.core5.http.entity.StringEntity; * * @since 4.3 */ -@NotThreadSafe public class EntityBuilder { private String text; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/GzipCompressingEntity.java b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/GzipCompressingEntity.java index 85863cc8d..295aa78ad 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/GzipCompressingEntity.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/GzipCompressingEntity.java @@ -59,7 +59,7 @@ import java.io.OutputStream; import java.util.zip.GZIPOutputStream; import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.entity.HttpEntityWrapper; +import org.apache.hc.core5.http.io.entity.HttpEntityWrapper; import org.apache.hc.core5.util.Args; /** diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/GzipDecompressingEntity.java b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/GzipDecompressingEntity.java index b3bef556d..07d252026 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/GzipDecompressingEntity.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/GzipDecompressingEntity.java @@ -33,7 +33,7 @@ import java.util.zip.GZIPInputStream; import org.apache.hc.core5.http.HttpEntity; /** - * {@link org.apache.hc.core5.http.entity.HttpEntityWrapper} for handling gzip + * {@link org.apache.hc.core5.http.io.entity.HttpEntityWrapper} for handling gzip * Content Coded responses. * * @since 4.1 diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/LazyDecompressingInputStream.java b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/LazyDecompressingInputStream.java index 802fa9a82..88b581853 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/LazyDecompressingInputStream.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/LazyDecompressingInputStream.java @@ -29,12 +29,9 @@ package org.apache.hc.client5.http.entity; import java.io.IOException; import java.io.InputStream; -import org.apache.hc.core5.annotation.NotThreadSafe; - /** * Lazy init InputStream wrapper. */ -@NotThreadSafe class LazyDecompressingInputStream extends InputStream { private final InputStream wrappedStream; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/UrlEncodedFormEntity.java b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/UrlEncodedFormEntity.java index a4025321e..c058c2579 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/UrlEncodedFormEntity.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/UrlEncodedFormEntity.java @@ -30,11 +30,10 @@ import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.List; -import org.apache.hc.client5.http.utils.URLEncodedUtils; -import org.apache.hc.core5.annotation.NotThreadSafe; +import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.NameValuePair; -import org.apache.hc.core5.http.entity.ContentType; -import org.apache.hc.core5.http.entity.StringEntity; +import org.apache.hc.core5.http.io.entity.StringEntity; +import org.apache.hc.core5.net.URLEncodedUtils; /** * An entity composed of a list of url-encoded pairs. @@ -42,7 +41,6 @@ import org.apache.hc.core5.http.entity.StringEntity; * * @since 4.0 */ -@NotThreadSafe // AbstractHttpEntity is not thread-safe public class UrlEncodedFormEntity extends StringEntity { /** diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/AbstractContentBody.java b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/AbstractContentBody.java index 79a782d8d..f76d70450 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/AbstractContentBody.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/AbstractContentBody.java @@ -29,7 +29,7 @@ package org.apache.hc.client5.http.entity.mime; import java.nio.charset.Charset; -import org.apache.hc.core5.http.entity.ContentType; +import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.util.Args; /** diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/AbstractMultipartForm.java b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/AbstractMultipartForm.java index e147a434a..0ef2266da 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/AbstractMultipartForm.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/AbstractMultipartForm.java @@ -58,7 +58,7 @@ abstract class AbstractMultipartForm { private static void writeBytes( final ByteArrayBuffer b, final OutputStream out) throws IOException { - out.write(b.buffer(), 0, b.length()); + out.write(b.array(), 0, b.length()); } private static void writeBytes( diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/ByteArrayBody.java b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/ByteArrayBody.java index 1fde3a7ea..54e63ad22 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/ByteArrayBody.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/ByteArrayBody.java @@ -29,7 +29,7 @@ package org.apache.hc.client5.http.entity.mime; import java.io.IOException; import java.io.OutputStream; -import org.apache.hc.core5.http.entity.ContentType; +import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.util.Args; /** diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/FileBody.java b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/FileBody.java index 6a89ba29e..1b359f82d 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/FileBody.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/FileBody.java @@ -33,7 +33,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import org.apache.hc.core5.http.entity.ContentType; +import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.util.Args; /** diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/FormBodyPartBuilder.java b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/FormBodyPartBuilder.java index 652f8dcf1..25bf4f2eb 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/FormBodyPartBuilder.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/FormBodyPartBuilder.java @@ -29,7 +29,7 @@ package org.apache.hc.client5.http.entity.mime; import java.util.List; -import org.apache.hc.core5.http.entity.ContentType; +import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.util.Args; import org.apache.hc.core5.util.Asserts; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/InputStreamBody.java b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/InputStreamBody.java index 461caf8bd..3a1b06ae8 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/InputStreamBody.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/InputStreamBody.java @@ -31,7 +31,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import org.apache.hc.core5.http.entity.ContentType; +import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.util.Args; /** diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/MultipartEntityBuilder.java b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/MultipartEntityBuilder.java index 20ec3bcc7..4f98ea6a4 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/MultipartEntityBuilder.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/MultipartEntityBuilder.java @@ -35,9 +35,9 @@ import java.util.Collections; import java.util.List; import java.util.Random; +import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.NameValuePair; -import org.apache.hc.core5.http.entity.ContentType; import org.apache.hc.core5.http.message.BasicNameValuePair; import org.apache.hc.core5.util.Args; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/MultipartFormEntity.java b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/MultipartFormEntity.java index 49b3e43f8..d0a59e9a7 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/MultipartFormEntity.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/MultipartFormEntity.java @@ -32,12 +32,14 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.util.List; import java.util.Set; +import org.apache.hc.core5.function.Supplier; import org.apache.hc.core5.http.ContentTooLongException; +import org.apache.hc.core5.http.ContentType; +import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.TrailerSupplier; -import org.apache.hc.core5.http.entity.ContentType; class MultipartFormEntity implements HttpEntity { @@ -108,7 +110,7 @@ class MultipartFormEntity implements HttpEntity { } @Override - public TrailerSupplier getTrailers() { + public Supplier> getTrailers() { return null; } @@ -117,4 +119,8 @@ class MultipartFormEntity implements HttpEntity { return null; } + @Override + public void close() throws IOException { + } + } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/StringBody.java b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/StringBody.java index a8a6f0b52..0f1d88089 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/StringBody.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/StringBody.java @@ -36,7 +36,7 @@ import java.io.Reader; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; -import org.apache.hc.core5.http.entity.ContentType; +import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.util.Args; /** diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/BasicResponseHandler.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/BasicResponseHandler.java index d95163f45..c2ca96804 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/BasicResponseHandler.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/BasicResponseHandler.java @@ -31,11 +31,12 @@ import java.io.IOException; import org.apache.hc.client5.http.impl.sync.AbstractResponseHandler; import org.apache.hc.client5.http.protocol.ClientProtocolException; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.ParseException; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.EntityUtils; /** * A {@link org.apache.hc.client5.http.sync.ResponseHandler} that returns the response body as a String @@ -44,13 +45,13 @@ import org.apache.hc.core5.http.entity.EntityUtils; *

* If this is used with * {@link org.apache.hc.client5.http.sync.HttpClient#execute( - * org.apache.hc.client5.http.methods.HttpUriRequest, org.apache.hc.client5.http.sync.ResponseHandler)}, + * org.apache.hc.core5.http.ClassicHttpRequest, org.apache.hc.client5.http.sync.ResponseHandler)}, * HttpClient may handle redirects (3xx responses) internally. *

* * @since 4.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class BasicResponseHandler extends AbstractResponseHandler { /** @@ -66,8 +67,7 @@ public class BasicResponseHandler extends AbstractResponseHandler { } @Override - public String handleResponse( - final HttpResponse response) throws IOException { + public String handleResponse(final ClassicHttpResponse response) throws IOException { return super.handleResponse(response); } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/DefaultConnectionKeepAliveStrategy.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/DefaultConnectionKeepAliveStrategy.java index 87cc279e7..1461fffb0 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/DefaultConnectionKeepAliveStrategy.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/DefaultConnectionKeepAliveStrategy.java @@ -29,11 +29,12 @@ package org.apache.hc.client5.http.impl; import java.util.Iterator; import org.apache.hc.client5.http.ConnectionKeepAliveStrategy; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.http.message.MessageSupport; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.HeaderElement; import org.apache.hc.core5.http.HeaderElements; import org.apache.hc.core5.http.HttpResponse; -import org.apache.hc.core5.http.message.BasicHeaderElementIterator; import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.util.Args; @@ -46,7 +47,7 @@ import org.apache.hc.core5.util.Args; * * @since 4.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class DefaultConnectionKeepAliveStrategy implements ConnectionKeepAliveStrategy { public static final DefaultConnectionKeepAliveStrategy INSTANCE = new DefaultConnectionKeepAliveStrategy(); @@ -54,8 +55,7 @@ public class DefaultConnectionKeepAliveStrategy implements ConnectionKeepAliveSt @Override public long getKeepAliveDuration(final HttpResponse response, final HttpContext context) { Args.notNull(response, "HTTP response"); - final Iterator it = new BasicHeaderElementIterator( - response.headerIterator(HeaderElements.KEEP_ALIVE)); + final Iterator it = MessageSupport.iterate(response, HeaderElements.KEEP_ALIVE); while (it.hasNext()) { final HeaderElement he = it.next(); final String param = he.getName(); diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/DefaultSchemePortResolver.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/DefaultSchemePortResolver.java index 2fe053280..4611b08fd 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/DefaultSchemePortResolver.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/DefaultSchemePortResolver.java @@ -28,7 +28,8 @@ package org.apache.hc.client5.http.impl; import org.apache.hc.client5.http.SchemePortResolver; import org.apache.hc.client5.http.UnsupportedSchemeException; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.util.Args; @@ -37,7 +38,7 @@ import org.apache.hc.core5.util.Args; * * @since 4.3 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class DefaultSchemePortResolver implements SchemePortResolver { public static final DefaultSchemePortResolver INSTANCE = new DefaultSchemePortResolver(); diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/BasicAuthCache.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/BasicAuthCache.java index a2f120af6..dfd1aa4f9 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/BasicAuthCache.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/BasicAuthCache.java @@ -40,7 +40,8 @@ import org.apache.hc.client5.http.UnsupportedSchemeException; import org.apache.hc.client5.http.auth.AuthCache; import org.apache.hc.client5.http.auth.AuthScheme; import org.apache.hc.client5.http.impl.DefaultSchemePortResolver; -import org.apache.hc.core5.annotation.ThreadSafe; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.util.Args; import org.apache.logging.log4j.LogManager; @@ -56,7 +57,7 @@ import org.apache.logging.log4j.Logger; * * @since 4.1 */ -@ThreadSafe +@Contract(threading = ThreadingBehavior.SAFE_CONDITIONAL) public class BasicAuthCache implements AuthCache { private final Logger log = LogManager.getLogger(getClass()); diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/BasicScheme.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/BasicScheme.java index 32c9270c2..ef5a8b8b9 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/BasicScheme.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/BasicScheme.java @@ -32,6 +32,7 @@ import java.io.ObjectOutputStream; import java.io.Serializable; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; +import java.nio.charset.UnsupportedCharsetException; import java.security.Principal; import java.util.HashMap; import java.util.List; @@ -47,20 +48,17 @@ import org.apache.hc.client5.http.auth.Credentials; import org.apache.hc.client5.http.auth.CredentialsProvider; import org.apache.hc.client5.http.auth.MalformedChallengeException; import org.apache.hc.client5.http.auth.util.ByteArrayBuilder; -import org.apache.hc.core5.annotation.NotThreadSafe; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.NameValuePair; import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.util.Args; -import org.apache.hc.core5.util.CharsetUtils; /** * Basic authentication scheme as defined in RFC 2617. * * @since 4.0 */ -@NotThreadSafe public class BasicScheme implements AuthScheme, Serializable { private static final long serialVersionUID = -1931571557597830536L; @@ -184,8 +182,9 @@ public class BasicScheme implements AuthScheme, Serializable { @SuppressWarnings("unchecked") private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); - this.charset = CharsetUtils.get(in.readUTF()); - if (this.charset == null) { + try { + this.charset = Charset.forName(in.readUTF()); + } catch (UnsupportedCharsetException ex) { this.charset = StandardCharsets.US_ASCII; } } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/BasicSchemeFactory.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/BasicSchemeFactory.java index 65a36840e..50b588ae0 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/BasicSchemeFactory.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/BasicSchemeFactory.java @@ -31,7 +31,8 @@ import java.nio.charset.Charset; import org.apache.hc.client5.http.auth.AuthScheme; import org.apache.hc.client5.http.auth.AuthSchemeProvider; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.protocol.HttpContext; /** @@ -40,7 +41,7 @@ import org.apache.hc.core5.http.protocol.HttpContext; * * @since 4.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class BasicSchemeFactory implements AuthSchemeProvider { private final Charset charset; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/DigestScheme.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/DigestScheme.java index 053611753..1b7cb9d37 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/DigestScheme.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/DigestScheme.java @@ -30,6 +30,7 @@ import java.io.IOException; import java.io.Serializable; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; +import java.nio.charset.UnsupportedCharsetException; import java.security.MessageDigest; import java.security.Principal; import java.security.SecureRandom; @@ -51,7 +52,7 @@ import org.apache.hc.client5.http.auth.Credentials; import org.apache.hc.client5.http.auth.CredentialsProvider; import org.apache.hc.client5.http.auth.MalformedChallengeException; import org.apache.hc.client5.http.auth.util.ByteArrayBuilder; -import org.apache.hc.core5.annotation.NotThreadSafe; +import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpRequest; @@ -61,7 +62,6 @@ import org.apache.hc.core5.http.message.BasicNameValuePair; import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.util.Args; import org.apache.hc.core5.util.CharArrayBuffer; -import org.apache.hc.core5.util.CharsetUtils; /** * Digest authentication scheme as defined in RFC 2617. @@ -77,7 +77,6 @@ import org.apache.hc.core5.util.CharsetUtils; * * @since 4.0 */ -@NotThreadSafe public class DigestScheme implements AuthScheme, Serializable { private static final long serialVersionUID = 3883908186234566916L; @@ -160,7 +159,7 @@ public class DigestScheme implements AuthScheme, Serializable { @Override public boolean isChallengeComplete() { final String s = this.paramMap.get("stale"); - return "true".equalsIgnoreCase(s) ? false : this.complete; + return !"true".equalsIgnoreCase(s) && this.complete; } @Override @@ -218,8 +217,8 @@ public class DigestScheme implements AuthScheme, Serializable { private String createDigestResponse(final HttpRequest request) throws AuthenticationException { - final String uri = request.getRequestLine().getUri(); - final String method = request.getRequestLine().getMethod(); + final String uri = request.getPath(); + final String method = request.getMethod(); final String realm = this.paramMap.get("realm"); final String nonce = this.paramMap.get("nonce"); final String opaque = this.paramMap.get("opaque"); @@ -238,7 +237,8 @@ public class DigestScheme implements AuthScheme, Serializable { final String variant = tok.nextToken().trim(); qopset.add(variant.toLowerCase(Locale.ROOT)); } - if (request.getEntity() != null && qopset.contains("auth-int")) { + final HttpEntity entity = request instanceof ClassicHttpRequest ? ((ClassicHttpRequest) request).getEntity() : null; + if (entity != null && qopset.contains("auth-int")) { qop = QOP_AUTH_INT; } else if (qopset.contains("auth")) { qop = QOP_AUTH; @@ -254,8 +254,10 @@ public class DigestScheme implements AuthScheme, Serializable { } final String charsetName = this.paramMap.get("charset"); - Charset charset = charsetName != null ? CharsetUtils.lookup(charsetName) : null; - if (charset == null) { + Charset charset; + try { + charset = charsetName != null ? Charset.forName(charsetName) : StandardCharsets.ISO_8859_1; + } catch (UnsupportedCharsetException ex) { charset = StandardCharsets.ISO_8859_1; } @@ -324,7 +326,7 @@ public class DigestScheme implements AuthScheme, Serializable { a2 = buffer.append(method).append(":").append(uri).toByteArray(); } else if (qop == QOP_AUTH_INT) { // Method ":" digest-uri-value ":" H(entity-body) - final HttpEntity entity = request.getEntity(); + final HttpEntity entity = request instanceof ClassicHttpRequest ? ((ClassicHttpRequest) request).getEntity() : null; if (entity != null && !entity.isRepeatable()) { // If the entity is not repeatable, try falling back onto QOP_AUTH if (qopset.contains("auth")) { diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/DigestSchemeFactory.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/DigestSchemeFactory.java index 1c547f53c..d073d4ee9 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/DigestSchemeFactory.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/DigestSchemeFactory.java @@ -29,7 +29,8 @@ package org.apache.hc.client5.http.impl.auth; import org.apache.hc.client5.http.auth.AuthScheme; import org.apache.hc.client5.http.auth.AuthSchemeProvider; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.protocol.HttpContext; /** @@ -38,7 +39,7 @@ import org.apache.hc.core5.http.protocol.HttpContext; * * @since 4.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class DigestSchemeFactory implements AuthSchemeProvider { @Override diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/GGSSchemeBase.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/GGSSchemeBase.java index 07c0b2571..0a0cdbcef 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/GGSSchemeBase.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/GGSSchemeBase.java @@ -42,7 +42,6 @@ import org.apache.hc.client5.http.auth.CredentialsProvider; import org.apache.hc.client5.http.auth.InvalidCredentialsException; import org.apache.hc.client5.http.auth.KerberosCredentials; import org.apache.hc.client5.http.auth.MalformedChallengeException; -import org.apache.hc.core5.annotation.NotThreadSafe; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.protocol.HttpContext; @@ -59,7 +58,6 @@ import org.ietf.jgss.Oid; /** * @since 4.2 */ -@NotThreadSafe public abstract class GGSSchemeBase implements AuthScheme { enum State { diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/HttpAuthenticator.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/HttpAuthenticator.java index d35ceb668..4237b389d 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/HttpAuthenticator.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/HttpAuthenticator.java @@ -99,7 +99,7 @@ public class HttpAuthenticator { final HttpClientContext clientContext = HttpClientContext.adapt(context); - if (response.getStatusLine().getStatusCode() == challengeCode) { + if (response.getCode() == challengeCode) { this.log.debug("Authentication required"); if (authExchange.getState() == AuthExchange.State.SUCCESS) { clearCache(host, clientContext); diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/KerberosScheme.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/KerberosScheme.java index 0193af3cf..76e6e22ce 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/KerberosScheme.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/KerberosScheme.java @@ -27,7 +27,6 @@ package org.apache.hc.client5.http.impl.auth; import org.apache.hc.client5.http.DnsResolver; -import org.apache.hc.core5.annotation.NotThreadSafe; import org.ietf.jgss.GSSException; import org.ietf.jgss.Oid; @@ -36,7 +35,6 @@ import org.ietf.jgss.Oid; * * @since 4.2 */ -@NotThreadSafe public class KerberosScheme extends GGSSchemeBase { private static final String KERBEROS_OID = "1.2.840.113554.1.2.2"; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/KerberosSchemeFactory.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/KerberosSchemeFactory.java index 058fc752a..9a2b85464 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/KerberosSchemeFactory.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/KerberosSchemeFactory.java @@ -29,7 +29,8 @@ package org.apache.hc.client5.http.impl.auth; import org.apache.hc.client5.http.DnsResolver; import org.apache.hc.client5.http.auth.AuthScheme; import org.apache.hc.client5.http.auth.AuthSchemeProvider; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.protocol.HttpContext; /** @@ -38,7 +39,7 @@ import org.apache.hc.core5.http.protocol.HttpContext; * * @since 4.2 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class KerberosSchemeFactory implements AuthSchemeProvider { private final DnsResolver dnsResolver; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/NTLMEngineException.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/NTLMEngineException.java index 05edcc800..c63bf3409 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/NTLMEngineException.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/NTLMEngineException.java @@ -27,7 +27,6 @@ package org.apache.hc.client5.http.impl.auth; import org.apache.hc.client5.http.auth.AuthenticationException; -import org.apache.hc.core5.annotation.Immutable; /** * Signals NTLM protocol failure. @@ -35,7 +34,6 @@ import org.apache.hc.core5.annotation.Immutable; * * @since 4.0 */ -@Immutable public class NTLMEngineException extends AuthenticationException { private static final long serialVersionUID = 6027981323731768824L; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/NTLMEngineImpl.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/NTLMEngineImpl.java index ed05d906a..6b114ba75 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/NTLMEngineImpl.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/NTLMEngineImpl.java @@ -39,8 +39,6 @@ import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; import org.apache.hc.client5.http.auth.util.ByteArrayBuilder; -import org.apache.hc.core5.annotation.NotThreadSafe; -import org.apache.hc.core5.util.CharsetUtils; /** * Provides an implementation for NTLMv1, NTLMv2, and NTLM2 Session forms of the NTLM @@ -48,11 +46,10 @@ import org.apache.hc.core5.util.CharsetUtils; * * @since 4.1 */ -@NotThreadSafe final class NTLMEngineImpl implements NTLMEngine { /** Unicode encoding */ - private static final Charset UNICODE_LITTLE_UNMARKED = CharsetUtils.lookup("UnicodeLittleUnmarked"); + private static final Charset UNICODE_LITTLE_UNMARKED = Charset.forName("UnicodeLittleUnmarked"); /** Character encoding */ private static final Charset DEFAULT_CHARSET = StandardCharsets.US_ASCII; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/NTLMScheme.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/NTLMScheme.java index a6706b703..47ed39841 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/NTLMScheme.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/NTLMScheme.java @@ -36,7 +36,6 @@ import org.apache.hc.client5.http.auth.Credentials; import org.apache.hc.client5.http.auth.CredentialsProvider; import org.apache.hc.client5.http.auth.MalformedChallengeException; import org.apache.hc.client5.http.auth.NTCredentials; -import org.apache.hc.core5.annotation.NotThreadSafe; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.protocol.HttpContext; @@ -48,7 +47,6 @@ import org.apache.hc.core5.util.Args; * * @since 4.0 */ -@NotThreadSafe public class NTLMScheme implements AuthScheme { enum State { diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/NTLMSchemeFactory.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/NTLMSchemeFactory.java index 357b5d5be..83fd4b179 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/NTLMSchemeFactory.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/NTLMSchemeFactory.java @@ -29,7 +29,8 @@ package org.apache.hc.client5.http.impl.auth; import org.apache.hc.client5.http.auth.AuthScheme; import org.apache.hc.client5.http.auth.AuthSchemeProvider; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.protocol.HttpContext; /** @@ -39,7 +40,7 @@ import org.apache.hc.core5.http.protocol.HttpContext; * * @since 4.1 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class NTLMSchemeFactory implements AuthSchemeProvider { @Override diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/SPNegoScheme.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/SPNegoScheme.java index dfd0c4471..bf5f21a3e 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/SPNegoScheme.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/SPNegoScheme.java @@ -27,7 +27,6 @@ package org.apache.hc.client5.http.impl.auth; import org.apache.hc.client5.http.DnsResolver; -import org.apache.hc.core5.annotation.NotThreadSafe; import org.ietf.jgss.GSSException; import org.ietf.jgss.Oid; @@ -37,7 +36,6 @@ import org.ietf.jgss.Oid; * * @since 4.2 */ -@NotThreadSafe public class SPNegoScheme extends GGSSchemeBase { private static final String SPNEGO_OID = "1.3.6.1.5.5.2"; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/SPNegoSchemeFactory.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/SPNegoSchemeFactory.java index 0c51ea03a..97bf5ebb4 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/SPNegoSchemeFactory.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/SPNegoSchemeFactory.java @@ -29,7 +29,8 @@ package org.apache.hc.client5.http.impl.auth; import org.apache.hc.client5.http.DnsResolver; import org.apache.hc.client5.http.auth.AuthScheme; import org.apache.hc.client5.http.auth.AuthSchemeProvider; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.protocol.HttpContext; /** @@ -38,7 +39,7 @@ import org.apache.hc.core5.http.protocol.HttpContext; * * @since 4.2 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class SPNegoSchemeFactory implements AuthSchemeProvider { private final DnsResolver dnsResolver; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/SystemDefaultCredentialsProvider.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/SystemDefaultCredentialsProvider.java index 737fbe789..57674b36d 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/SystemDefaultCredentialsProvider.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/SystemDefaultCredentialsProvider.java @@ -29,6 +29,8 @@ package org.apache.hc.client5.http.impl.auth; import java.net.Authenticator; import java.net.MalformedURLException; import java.net.PasswordAuthentication; +import java.net.URI; +import java.net.URISyntaxException; import java.net.URL; import java.util.Locale; import java.util.Map; @@ -41,11 +43,12 @@ import org.apache.hc.client5.http.auth.NTCredentials; import org.apache.hc.client5.http.auth.UsernamePasswordCredentials; import org.apache.hc.client5.http.config.AuthSchemes; import org.apache.hc.client5.http.impl.sync.BasicCredentialsProvider; -import org.apache.hc.core5.annotation.ThreadSafe; +import org.apache.hc.client5.http.protocol.HttpClientContext; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.protocol.HttpContext; -import org.apache.hc.core5.http.protocol.HttpCoreContext; import org.apache.hc.core5.util.Args; /** @@ -54,7 +57,7 @@ import org.apache.hc.core5.util.Args; * * @since 4.3 */ -@ThreadSafe +@Contract(threading = ThreadingBehavior.SAFE) public class SystemDefaultCredentialsProvider implements CredentialsStore { private static final Map SCHEME_MAP; @@ -68,7 +71,7 @@ public class SystemDefaultCredentialsProvider implements CredentialsStore { SCHEME_MAP.put(AuthSchemes.KERBEROS.toUpperCase(Locale.ROOT), "Kerberos"); } - private static String translateScheme(final String key) { + private static String translateAuthScheme(final String key) { if (key == null) { return null; } @@ -94,14 +97,19 @@ public class SystemDefaultCredentialsProvider implements CredentialsStore { private static PasswordAuthentication getSystemCreds( final AuthScope authscope, final Authenticator.RequestorType requestorType, - final HttpContext context) { + final HttpClientContext context) { final String hostname = authscope.getHost(); final int port = authscope.getPort(); final HttpHost origin = authscope.getOrigin(); - final String protocol = origin != null ? origin.getSchemeName() : - (port == 443 ? "https" : "http"); - - final URL targetHostURL = getTargetHostURL(context); + final String protocol = origin != null ? origin.getSchemeName() : (port == 443 ? "https" : "http"); + final HttpRequest request = context != null ? context.getRequest() : null; + URL targetHostURL; + try { + final URI uri = request != null ? request.getUri() : null; + targetHostURL = uri != null ? uri.toURL() : null; + } catch (URISyntaxException | MalformedURLException ignore) { + targetHostURL = null; + } // use null addr, because the authentication fails if it does not exactly match the expected realm's host return Authenticator.requestPasswordAuthentication( hostname, @@ -109,24 +117,11 @@ public class SystemDefaultCredentialsProvider implements CredentialsStore { port, protocol, authscope.getRealm(), - translateScheme(authscope.getScheme()), + translateAuthScheme(authscope.getScheme()), targetHostURL, requestorType); } - private static URL getTargetHostURL(final HttpContext context) { - if (context == null) { - return null; - } - final HttpRequest httpRequest = (HttpRequest)context.getAttribute(HttpCoreContext.HTTP_REQUEST); - final String uri = httpRequest.getRequestLine().getUri(); - try { - return new URL(uri); - } catch (final MalformedURLException e) { - return null; - } - } - @Override public Credentials getCredentials(final AuthScope authscope, final HttpContext context) { Args.notNull(authscope, "Auth scope"); @@ -136,9 +131,12 @@ public class SystemDefaultCredentialsProvider implements CredentialsStore { } final String host = authscope.getHost(); if (host != null) { - PasswordAuthentication systemcreds = getSystemCreds(authscope, Authenticator.RequestorType.SERVER, context); + final HttpClientContext clientContext = context != null ? HttpClientContext.adapt(context) : null; + PasswordAuthentication systemcreds = getSystemCreds( + authscope, Authenticator.RequestorType.SERVER, clientContext); if (systemcreds == null) { - systemcreds = getSystemCreds(authscope, Authenticator.RequestorType.PROXY, context); + systemcreds = getSystemCreds( + authscope, Authenticator.RequestorType.PROXY, clientContext); } if (systemcreds == null) { final String proxyHost = System.getProperty("http.proxyHost"); diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/UnsupportedDigestAlgorithmException.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/UnsupportedDigestAlgorithmException.java index 4a65696da..5307867f1 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/UnsupportedDigestAlgorithmException.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/UnsupportedDigestAlgorithmException.java @@ -26,8 +26,6 @@ */ package org.apache.hc.client5.http.impl.auth; -import org.apache.hc.core5.annotation.Immutable; - /** * Authentication credentials required to respond to a authentication * challenge are invalid @@ -35,7 +33,6 @@ import org.apache.hc.core5.annotation.Immutable; * * @since 4.0 */ -@Immutable public class UnsupportedDigestAlgorithmException extends RuntimeException { private static final long serialVersionUID = 319558534317118022L; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/AbstractCookieAttributeHandler.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/AbstractCookieAttributeHandler.java index fe3fda4a5..242392327 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/AbstractCookieAttributeHandler.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/AbstractCookieAttributeHandler.java @@ -30,13 +30,14 @@ import org.apache.hc.client5.http.cookie.Cookie; import org.apache.hc.client5.http.cookie.CookieAttributeHandler; import org.apache.hc.client5.http.cookie.CookieOrigin; import org.apache.hc.client5.http.cookie.MalformedCookieException; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; /** * * @since 4.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public abstract class AbstractCookieAttributeHandler implements CookieAttributeHandler { @Override diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/AbstractCookieSpec.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/AbstractCookieSpec.java index 5cc993031..d6f8707c4 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/AbstractCookieSpec.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/AbstractCookieSpec.java @@ -35,7 +35,8 @@ import java.util.concurrent.ConcurrentHashMap; import org.apache.hc.client5.http.cookie.CommonCookieAttributeHandler; import org.apache.hc.client5.http.cookie.CookieAttributeHandler; import org.apache.hc.client5.http.cookie.CookieSpec; -import org.apache.hc.core5.annotation.ThreadSafe; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.util.Asserts; /** @@ -46,7 +47,7 @@ import org.apache.hc.core5.util.Asserts; * * @since 4.0 */ -@ThreadSafe +@Contract(threading = ThreadingBehavior.SAFE) public abstract class AbstractCookieSpec implements CookieSpec { /** diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/BasicClientCookie.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/BasicClientCookie.java index e5b6a3e5c..4ded0355f 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/BasicClientCookie.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/BasicClientCookie.java @@ -34,7 +34,6 @@ import java.util.Locale; import java.util.Map; import org.apache.hc.client5.http.cookie.SetCookie; -import org.apache.hc.core5.annotation.NotThreadSafe; import org.apache.hc.core5.util.Args; /** @@ -42,7 +41,6 @@ import org.apache.hc.core5.util.Args; * * @since 4.0 */ -@NotThreadSafe public class BasicClientCookie implements SetCookie, Cloneable, Serializable { private static final long serialVersionUID = -3869795591041535538L; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/BasicDomainHandler.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/BasicDomainHandler.java index 6911d0e28..bfed82a00 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/BasicDomainHandler.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/BasicDomainHandler.java @@ -34,8 +34,9 @@ import org.apache.hc.client5.http.cookie.CookieOrigin; import org.apache.hc.client5.http.cookie.CookieRestrictionViolationException; import org.apache.hc.client5.http.cookie.MalformedCookieException; import org.apache.hc.client5.http.cookie.SetCookie; -import org.apache.hc.client5.http.utils.InetAddressUtils; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; +import org.apache.hc.core5.net.InetAddressUtils; import org.apache.hc.core5.util.Args; import org.apache.hc.core5.util.TextUtils; @@ -43,7 +44,7 @@ import org.apache.hc.core5.util.TextUtils; * * @since 4.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class BasicDomainHandler implements CommonCookieAttributeHandler { public BasicDomainHandler() { diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/BasicExpiresHandler.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/BasicExpiresHandler.java index d27dfa9f8..d90dfafcf 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/BasicExpiresHandler.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/BasicExpiresHandler.java @@ -33,14 +33,15 @@ import org.apache.hc.client5.http.cookie.Cookie; import org.apache.hc.client5.http.cookie.MalformedCookieException; import org.apache.hc.client5.http.cookie.SetCookie; import org.apache.hc.client5.http.utils.DateUtils; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.util.Args; /** * * @since 4.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class BasicExpiresHandler extends AbstractCookieAttributeHandler implements CommonCookieAttributeHandler { /** Valid date patterns */ diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/BasicMaxAgeHandler.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/BasicMaxAgeHandler.java index 3f4c11896..74cba3375 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/BasicMaxAgeHandler.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/BasicMaxAgeHandler.java @@ -32,14 +32,15 @@ import org.apache.hc.client5.http.cookie.CommonCookieAttributeHandler; import org.apache.hc.client5.http.cookie.Cookie; import org.apache.hc.client5.http.cookie.MalformedCookieException; import org.apache.hc.client5.http.cookie.SetCookie; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.util.Args; /** * * @since 4.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class BasicMaxAgeHandler extends AbstractCookieAttributeHandler implements CommonCookieAttributeHandler { public BasicMaxAgeHandler() { diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/BasicPathHandler.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/BasicPathHandler.java index 4d767de17..b98f5acd5 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/BasicPathHandler.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/BasicPathHandler.java @@ -32,7 +32,8 @@ import org.apache.hc.client5.http.cookie.CookieOrigin; import org.apache.hc.client5.http.cookie.CookieRestrictionViolationException; import org.apache.hc.client5.http.cookie.MalformedCookieException; import org.apache.hc.client5.http.cookie.SetCookie; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.util.Args; import org.apache.hc.core5.util.TextUtils; @@ -40,7 +41,7 @@ import org.apache.hc.core5.util.TextUtils; * * @since 4.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class BasicPathHandler implements CommonCookieAttributeHandler { public BasicPathHandler() { diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/BasicSecureHandler.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/BasicSecureHandler.java index 7163b8e57..99406a7d6 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/BasicSecureHandler.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/BasicSecureHandler.java @@ -31,14 +31,15 @@ import org.apache.hc.client5.http.cookie.Cookie; import org.apache.hc.client5.http.cookie.CookieOrigin; import org.apache.hc.client5.http.cookie.MalformedCookieException; import org.apache.hc.client5.http.cookie.SetCookie; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.util.Args; /** * * @since 4.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class BasicSecureHandler extends AbstractCookieAttributeHandler implements CommonCookieAttributeHandler { public BasicSecureHandler() { diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/CookieSpecBase.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/CookieSpecBase.java index a95da81f9..dd10e2f42 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/CookieSpecBase.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/CookieSpecBase.java @@ -37,7 +37,8 @@ import org.apache.hc.client5.http.cookie.Cookie; import org.apache.hc.client5.http.cookie.CookieAttributeHandler; import org.apache.hc.client5.http.cookie.CookieOrigin; import org.apache.hc.client5.http.cookie.MalformedCookieException; -import org.apache.hc.core5.annotation.ThreadSafe; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.HeaderElement; import org.apache.hc.core5.http.NameValuePair; import org.apache.hc.core5.util.Args; @@ -47,7 +48,7 @@ import org.apache.hc.core5.util.Args; * * @since 4.0 */ -@ThreadSafe +@Contract(threading = ThreadingBehavior.SAFE_CONDITIONAL) public abstract class CookieSpecBase extends AbstractCookieSpec { public CookieSpecBase() { diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/IgnoreSpec.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/IgnoreSpec.java index 4ef4611da..fee891103 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/IgnoreSpec.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/IgnoreSpec.java @@ -33,7 +33,8 @@ import java.util.List; import org.apache.hc.client5.http.cookie.Cookie; import org.apache.hc.client5.http.cookie.CookieOrigin; import org.apache.hc.client5.http.cookie.MalformedCookieException; -import org.apache.hc.core5.annotation.ThreadSafe; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.Header; /** @@ -41,7 +42,7 @@ import org.apache.hc.core5.http.Header; * * @since 4.1 */ -@ThreadSafe +@Contract(threading = ThreadingBehavior.SAFE) public class IgnoreSpec extends CookieSpecBase { @Override diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/IgnoreSpecProvider.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/IgnoreSpecProvider.java index 84ce18711..e7bf1fcad 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/IgnoreSpecProvider.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/IgnoreSpecProvider.java @@ -29,7 +29,8 @@ package org.apache.hc.client5.http.impl.cookie; import org.apache.hc.client5.http.cookie.CookieSpec; import org.apache.hc.client5.http.cookie.CookieSpecProvider; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.protocol.HttpContext; /** @@ -37,7 +38,7 @@ import org.apache.hc.core5.http.protocol.HttpContext; * * @since 4.4 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class IgnoreSpecProvider implements CookieSpecProvider { private volatile CookieSpec cookieSpec; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/LaxExpiresHandler.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/LaxExpiresHandler.java index 4e1789080..100c5d7f3 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/LaxExpiresHandler.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/LaxExpiresHandler.java @@ -39,7 +39,8 @@ import org.apache.hc.client5.http.cookie.CommonCookieAttributeHandler; import org.apache.hc.client5.http.cookie.Cookie; import org.apache.hc.client5.http.cookie.MalformedCookieException; import org.apache.hc.client5.http.cookie.SetCookie; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.message.ParserCursor; import org.apache.hc.core5.util.Args; @@ -47,7 +48,7 @@ import org.apache.hc.core5.util.Args; * * @since 4.4 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class LaxExpiresHandler extends AbstractCookieAttributeHandler implements CommonCookieAttributeHandler { static final TimeZone UTC = TimeZone.getTimeZone("UTC"); diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/LaxMaxAgeHandler.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/LaxMaxAgeHandler.java index afd57c6f5..cf3639cfa 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/LaxMaxAgeHandler.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/LaxMaxAgeHandler.java @@ -34,7 +34,8 @@ import org.apache.hc.client5.http.cookie.CommonCookieAttributeHandler; import org.apache.hc.client5.http.cookie.Cookie; import org.apache.hc.client5.http.cookie.MalformedCookieException; import org.apache.hc.client5.http.cookie.SetCookie; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.util.Args; import org.apache.hc.core5.util.TextUtils; @@ -42,7 +43,7 @@ import org.apache.hc.core5.util.TextUtils; * * @since 4.4 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class LaxMaxAgeHandler extends AbstractCookieAttributeHandler implements CommonCookieAttributeHandler { private final static Pattern MAX_AGE_PATTERN = Pattern.compile("^\\-?[0-9]+$"); diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/PublicSuffixDomainFilter.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/PublicSuffixDomainFilter.java index ee2a77f83..8093f0b1c 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/PublicSuffixDomainFilter.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/PublicSuffixDomainFilter.java @@ -36,7 +36,8 @@ import org.apache.hc.client5.http.cookie.MalformedCookieException; import org.apache.hc.client5.http.cookie.SetCookie; import org.apache.hc.client5.http.psl.PublicSuffixList; import org.apache.hc.client5.http.psl.PublicSuffixMatcher; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.util.Args; /** @@ -50,7 +51,7 @@ import org.apache.hc.core5.util.Args; * * @since 4.4 */ -@Immutable // dependencies are expected to be immutable or thread-safe +@Contract(threading = ThreadingBehavior.IMMUTABLE_CONDITIONAL) public class PublicSuffixDomainFilter implements CommonCookieAttributeHandler { private final CommonCookieAttributeHandler handler; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/RFC6265CookieSpec.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/RFC6265CookieSpec.java index 17b20d47f..08b0317ce 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/RFC6265CookieSpec.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/RFC6265CookieSpec.java @@ -44,7 +44,8 @@ import org.apache.hc.client5.http.cookie.CookieOrigin; import org.apache.hc.client5.http.cookie.CookiePriorityComparator; import org.apache.hc.client5.http.cookie.CookieSpec; import org.apache.hc.client5.http.cookie.MalformedCookieException; -import org.apache.hc.core5.annotation.ThreadSafe; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.FormattedHeader; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.ParseException; @@ -59,7 +60,7 @@ import org.apache.hc.core5.util.CharArrayBuffer; * * @since 4.5 */ -@ThreadSafe +@Contract(threading = ThreadingBehavior.SAFE_CONDITIONAL) public class RFC6265CookieSpec implements CookieSpec { private final static char PARAM_DELIMITER = ';'; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/RFC6265CookieSpecProvider.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/RFC6265CookieSpecProvider.java index 47e3a91e0..adaa7ef3d 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/RFC6265CookieSpecProvider.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/RFC6265CookieSpecProvider.java @@ -33,7 +33,8 @@ import org.apache.hc.client5.http.cookie.CookieSpec; import org.apache.hc.client5.http.cookie.CookieSpecProvider; import org.apache.hc.client5.http.cookie.MalformedCookieException; import org.apache.hc.client5.http.psl.PublicSuffixMatcher; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.protocol.HttpContext; /** @@ -43,7 +44,7 @@ import org.apache.hc.core5.http.protocol.HttpContext; * * @since 4.4 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE_CONDITIONAL) public class RFC6265CookieSpecProvider implements CookieSpecProvider { public enum CompatibilityLevel { diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/RFC6265LaxSpec.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/RFC6265LaxSpec.java index cc31dc3a7..0514df39c 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/RFC6265LaxSpec.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/RFC6265LaxSpec.java @@ -28,7 +28,8 @@ package org.apache.hc.client5.http.impl.cookie; import org.apache.hc.client5.http.cookie.CommonCookieAttributeHandler; -import org.apache.hc.core5.annotation.ThreadSafe; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; /** * Standard {@link org.apache.hc.client5.http.cookie.CookieSpec} implementation that enforces a more relaxed @@ -38,7 +39,7 @@ import org.apache.hc.core5.annotation.ThreadSafe; * * @since 4.4 */ -@ThreadSafe +@Contract(threading = ThreadingBehavior.SAFE) public class RFC6265LaxSpec extends RFC6265CookieSpecBase { public RFC6265LaxSpec() { diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/RFC6265StrictSpec.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/RFC6265StrictSpec.java index 3779ab4b1..774753c8b 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/RFC6265StrictSpec.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/cookie/RFC6265StrictSpec.java @@ -29,7 +29,8 @@ package org.apache.hc.client5.http.impl.cookie; import org.apache.hc.client5.http.cookie.CommonCookieAttributeHandler; import org.apache.hc.client5.http.utils.DateUtils; -import org.apache.hc.core5.annotation.ThreadSafe; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; /** * Standard {@link org.apache.hc.client5.http.cookie.CookieSpec} implementation that enforces syntax @@ -38,7 +39,7 @@ import org.apache.hc.core5.annotation.ThreadSafe; * * @since 4.4 */ -@ThreadSafe +@Contract(threading = ThreadingBehavior.SAFE) public class RFC6265StrictSpec extends RFC6265CookieSpecBase { final static String[] DATE_PATTERNS = { diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/BasicHttpClientConnectionManager.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/BasicHttpClientConnectionManager.java index a6bb3c910..4d18e5393 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/BasicHttpClientConnectionManager.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/BasicHttpClientConnectionManager.java @@ -45,8 +45,8 @@ import org.apache.hc.client5.http.io.ManagedHttpClientConnection; import org.apache.hc.client5.http.socket.ConnectionSocketFactory; import org.apache.hc.client5.http.socket.PlainConnectionSocketFactory; import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory; -import org.apache.hc.core5.annotation.GuardedBy; -import org.apache.hc.core5.annotation.ThreadSafe; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.config.ConnectionConfig; import org.apache.hc.core5.http.config.Lookup; @@ -79,7 +79,7 @@ import org.apache.logging.log4j.Logger; * * @since 4.3 */ -@ThreadSafe +@Contract(threading = ThreadingBehavior.SAFE) public class BasicHttpClientConnectionManager implements HttpClientConnectionManager, Closeable { private final Logger log = LogManager.getLogger(getClass()); @@ -87,28 +87,13 @@ public class BasicHttpClientConnectionManager implements HttpClientConnectionMan private final HttpClientConnectionOperator connectionOperator; private final HttpConnectionFactory connFactory; - @GuardedBy("this") private ManagedHttpClientConnection conn; - - @GuardedBy("this") private HttpRoute route; - - @GuardedBy("this") private Object state; - - @GuardedBy("this") private long updated; - - @GuardedBy("this") private long expiry; - - @GuardedBy("this") private boolean leased; - - @GuardedBy("this") private SocketConfig socketConfig; - - @GuardedBy("this") private ConnectionConfig connConfig; private final AtomicBoolean isShutdown; @@ -358,7 +343,7 @@ public class BasicHttpClientConnectionManager implements HttpClientConnectionMan } @Override - public synchronized void closeExpiredConnections() { + public synchronized void closeExpired() { if (this.isShutdown.get()) { return; } @@ -368,7 +353,7 @@ public class BasicHttpClientConnectionManager implements HttpClientConnectionMan } @Override - public synchronized void closeIdleConnections(final long idletime, final TimeUnit tunit) { + public synchronized void closeIdle(final long idletime, final TimeUnit tunit) { Args.notNull(tunit, "Time unit"); if (this.isShutdown.get()) { return; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/CPool.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/CPool.java deleted file mode 100644 index 16115314f..000000000 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/CPool.java +++ /dev/null @@ -1,83 +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 - * . - * - */ -package org.apache.hc.client5.http.impl.io; - -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; - -import org.apache.hc.client5.http.HttpRoute; -import org.apache.hc.client5.http.io.ManagedHttpClientConnection; -import org.apache.hc.core5.annotation.ThreadSafe; -import org.apache.hc.core5.pool.PoolEntryCallback; -import org.apache.hc.core5.pool.io.AbstractConnPool; -import org.apache.hc.core5.pool.io.ConnFactory; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -/** - * @since 4.3 - */ -@ThreadSafe -class CPool extends AbstractConnPool { - - private static final AtomicLong COUNTER = new AtomicLong(); - - private final Logger log = LogManager.getLogger(CPool.class); - private final long timeToLive; - private final TimeUnit tunit; - - public CPool( - final ConnFactory connFactory, - final int defaultMaxPerRoute, final int maxTotal, - final long timeToLive, final TimeUnit tunit) { - super(connFactory, defaultMaxPerRoute, maxTotal); - this.timeToLive = timeToLive; - this.tunit = tunit; - } - - @Override - protected CPoolEntry createEntry(final HttpRoute route, final ManagedHttpClientConnection conn) { - final String id = Long.toString(COUNTER.getAndIncrement()); - return new CPoolEntry(this.log, id, route, conn, this.timeToLive, this.tunit); - } - - @Override - protected boolean validate(final CPoolEntry entry) { - return !entry.getConnection().isStale(); - } - - @Override - protected void enumAvailable(final PoolEntryCallback callback) { - super.enumAvailable(callback); - } - - @Override - protected void enumLeased(final PoolEntryCallback callback) { - super.enumLeased(callback); - } - -} diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/CPoolEntry.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/CPoolEntry.java deleted file mode 100644 index a52105e18..000000000 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/CPoolEntry.java +++ /dev/null @@ -1,101 +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 - * . - * - */ -package org.apache.hc.client5.http.impl.io; - -import java.io.IOException; -import java.util.Date; -import java.util.concurrent.TimeUnit; - -import org.apache.hc.client5.http.HttpRoute; -import org.apache.hc.client5.http.io.ManagedHttpClientConnection; -import org.apache.hc.core5.annotation.ThreadSafe; -import org.apache.hc.core5.http.io.HttpClientConnection; -import org.apache.hc.core5.pool.PoolEntry; -import org.apache.logging.log4j.Logger; - -/** - * @since 4.3 - */ -@ThreadSafe -class CPoolEntry extends PoolEntry { - - private final Logger log; - private volatile boolean routeComplete; - - public CPoolEntry( - final Logger log, - final String id, - final HttpRoute route, - final ManagedHttpClientConnection conn, - final long timeToLive, final TimeUnit tunit) { - super(id, route, conn, timeToLive, tunit); - this.log = log; - } - - public void markRouteComplete() { - this.routeComplete = true; - } - - public boolean isRouteComplete() { - return this.routeComplete; - } - - public void closeConnection() throws IOException { - final HttpClientConnection conn = getConnection(); - conn.close(); - } - - public void shutdownConnection() throws IOException { - final HttpClientConnection conn = getConnection(); - conn.shutdown(); - } - - @Override - public boolean isExpired(final long now) { - final boolean expired = super.isExpired(now); - if (expired && this.log.isDebugEnabled()) { - this.log.debug("Connection " + this + " expired @ " + new Date(getExpiry())); - } - return expired; - } - - @Override - public boolean isClosed() { - final HttpClientConnection conn = getConnection(); - return !conn.isOpen(); - } - - @Override - public void close() { - try { - closeConnection(); - } catch (final IOException ex) { - this.log.debug("I/O error closing connection", ex); - } - } - -} diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/CPoolProxy.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/CPoolProxy.java index d28e049cc..de76b606f 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/CPoolProxy.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/CPoolProxy.java @@ -32,40 +32,54 @@ import java.net.SocketAddress; import javax.net.ssl.SSLSession; +import org.apache.hc.client5.http.HttpRoute; import org.apache.hc.client5.http.io.ManagedHttpClientConnection; -import org.apache.hc.core5.annotation.NotThreadSafe; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpConnectionMetrics; import org.apache.hc.core5.http.HttpException; -import org.apache.hc.core5.http.HttpRequest; -import org.apache.hc.core5.http.HttpResponse; +import org.apache.hc.core5.http.ProtocolVersion; import org.apache.hc.core5.http.io.HttpClientConnection; import org.apache.hc.core5.http.protocol.HttpContext; +import org.apache.hc.core5.pool.PoolEntry; /** * @since 4.3 */ -@NotThreadSafe class CPoolProxy implements ManagedHttpClientConnection, HttpContext { - private volatile CPoolEntry poolEntry; + private volatile PoolEntry poolEntry; + private volatile boolean routeComplete; - CPoolProxy(final CPoolEntry entry) { + CPoolProxy(final PoolEntry entry) { super(); this.poolEntry = entry; } - CPoolEntry getPoolEntry() { + PoolEntry getPoolEntry() { return this.poolEntry; } - CPoolEntry detach() { - final CPoolEntry local = this.poolEntry; + boolean isDetached() { + return this.poolEntry == null; + } + + PoolEntry detach() { + final PoolEntry local = this.poolEntry; this.poolEntry = null; return local; } + public void markRouteComplete() { + this.routeComplete = true; + } + + public boolean isRouteComplete() { + return this.routeComplete; + } + ManagedHttpClientConnection getConnection() { - final CPoolEntry local = this.poolEntry; + final PoolEntry local = this.poolEntry; if (local == null) { return null; } @@ -82,32 +96,40 @@ class CPoolProxy implements ManagedHttpClientConnection, HttpContext { @Override public void close() throws IOException { - final CPoolEntry local = this.poolEntry; + final PoolEntry local = this.poolEntry; if (local != null) { - local.closeConnection(); + final ManagedHttpClientConnection conn = local.getConnection(); + if (conn != null) { + conn.close(); + } } } @Override public void shutdown() throws IOException { - final CPoolEntry local = this.poolEntry; + final PoolEntry local = this.poolEntry; if (local != null) { - local.shutdownConnection(); + final ManagedHttpClientConnection conn = local.getConnection(); + if (conn != null) { + conn.close(); + } } } @Override public boolean isOpen() { - final CPoolEntry local = this.poolEntry; + final PoolEntry local = this.poolEntry; if (local != null) { - return !local.isClosed(); - } else { - return false; + final ManagedHttpClientConnection conn = local.getConnection(); + if (conn != null) { + return conn.isOpen(); + } } + return false; } @Override - public boolean isStale() { + public boolean isStale() throws IOException { final HttpClientConnection conn = getConnection(); if (conn != null) { return conn.isStale(); @@ -116,6 +138,11 @@ class CPoolProxy implements ManagedHttpClientConnection, HttpContext { } } + @Override + public ProtocolVersion getProtocolVersion() { + return getValidConnection().getProtocolVersion(); + } + @Override public void setSocketTimeout(final int timeout) { getValidConnection().setSocketTimeout(timeout); @@ -152,7 +179,7 @@ class CPoolProxy implements ManagedHttpClientConnection, HttpContext { } @Override - public void terminateRequest(final HttpRequest request) throws HttpException, IOException { + public void terminateRequest(final ClassicHttpRequest request) throws HttpException, IOException { getValidConnection().terminateRequest(request); } @@ -162,22 +189,22 @@ class CPoolProxy implements ManagedHttpClientConnection, HttpContext { } @Override - public void sendRequestHeader(final HttpRequest request) throws HttpException, IOException { + public void sendRequestHeader(final ClassicHttpRequest request) throws HttpException, IOException { getValidConnection().sendRequestHeader(request); } @Override - public void sendRequestEntity(final HttpRequest request) throws HttpException, IOException { + public void sendRequestEntity(final ClassicHttpRequest request) throws HttpException, IOException { getValidConnection().sendRequestEntity(request); } @Override - public HttpResponse receiveResponseHeader() throws HttpException, IOException { + public ClassicHttpResponse receiveResponseHeader() throws HttpException, IOException { return getValidConnection().receiveResponseHeader(); } @Override - public void receiveResponseEntity(final HttpResponse response) throws HttpException, IOException { + public void receiveResponseEntity(final ClassicHttpResponse response) throws HttpException, IOException { getValidConnection().receiveResponseEntity(response); } @@ -229,6 +256,10 @@ class CPoolProxy implements ManagedHttpClientConnection, HttpContext { } } + @Override + public void setProtocolVersion(final ProtocolVersion version) { + } + @Override public String toString() { final StringBuilder sb = new StringBuilder("CPoolProxy{"); @@ -242,27 +273,11 @@ class CPoolProxy implements ManagedHttpClientConnection, HttpContext { return sb.toString(); } - public static HttpClientConnection newProxy(final CPoolEntry poolEntry) { - return new CPoolProxy(poolEntry); - } - - private static CPoolProxy getProxy(final HttpClientConnection conn) { + static CPoolProxy getProxy(final HttpClientConnection conn) { if (!CPoolProxy.class.isInstance(conn)) { throw new IllegalStateException("Unexpected connection proxy class: " + conn.getClass()); } return CPoolProxy.class.cast(conn); } - public static CPoolEntry getPoolEntry(final HttpClientConnection proxy) { - final CPoolEntry entry = getProxy(proxy).getPoolEntry(); - if (entry == null) { - throw new ConnectionShutdownException(); - } - return entry; - } - - public static CPoolEntry detach(final HttpClientConnection conn) { - return getProxy(conn).detach(); - } - } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/ConnectionShutdownException.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/ConnectionShutdownException.java index f5116e426..0c85ce01d 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/ConnectionShutdownException.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/ConnectionShutdownException.java @@ -27,15 +27,12 @@ package org.apache.hc.client5.http.impl.io; -import org.apache.hc.core5.annotation.Immutable; - /** * Signals that the connection has been shut down or released back to the * the connection pool * * @since 4.1 */ -@Immutable public class ConnectionShutdownException extends IllegalStateException { private static final long serialVersionUID = 5868657401162844497L; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/DefaultHttpClientConnectionOperator.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/DefaultHttpClientConnectionOperator.java index e92dfdae2..4609eb289 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/DefaultHttpClientConnectionOperator.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/DefaultHttpClientConnectionOperator.java @@ -46,7 +46,8 @@ import org.apache.hc.client5.http.io.ManagedHttpClientConnection; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.socket.ConnectionSocketFactory; import org.apache.hc.client5.http.socket.LayeredConnectionSocketFactory; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.config.Lookup; import org.apache.hc.core5.http.config.SocketConfig; @@ -62,7 +63,7 @@ import org.apache.logging.log4j.Logger; * * @since 4.4 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE_CONDITIONAL) public class DefaultHttpClientConnectionOperator implements HttpClientConnectionOperator { static final String SOCKET_FACTORY_REGISTRY = "http.socket-factory-registry"; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/DefaultHttpResponseParserFactory.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/DefaultHttpResponseParserFactory.java index c76dde04c..6859d28e3 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/DefaultHttpResponseParserFactory.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/DefaultHttpResponseParserFactory.java @@ -27,11 +27,12 @@ package org.apache.hc.client5.http.impl.io; -import org.apache.hc.core5.annotation.Immutable; -import org.apache.hc.core5.http.HttpResponse; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpResponseFactory; -import org.apache.hc.core5.http.config.MessageConstraints; -import org.apache.hc.core5.http.impl.DefaultHttpResponseFactory; +import org.apache.hc.core5.http.config.H1Config; +import org.apache.hc.core5.http.impl.io.DefaultClassicHttpResponseFactory; import org.apache.hc.core5.http.io.HttpMessageParser; import org.apache.hc.core5.http.io.HttpMessageParserFactory; import org.apache.hc.core5.http.message.BasicLineParser; @@ -42,23 +43,23 @@ import org.apache.hc.core5.http.message.LineParser; * * @since 4.3 */ -@Immutable -public class DefaultHttpResponseParserFactory implements HttpMessageParserFactory { +@Contract(threading = ThreadingBehavior.IMMUTABLE) +public class DefaultHttpResponseParserFactory implements HttpMessageParserFactory { public static final DefaultHttpResponseParserFactory INSTANCE = new DefaultHttpResponseParserFactory(); private final LineParser lineParser; - private final HttpResponseFactory responseFactory; + private final HttpResponseFactory responseFactory; public DefaultHttpResponseParserFactory( final LineParser lineParser, - final HttpResponseFactory responseFactory) { + final HttpResponseFactory responseFactory) { super(); this.lineParser = lineParser != null ? lineParser : BasicLineParser.INSTANCE; - this.responseFactory = responseFactory != null ? responseFactory : DefaultHttpResponseFactory.INSTANCE; + this.responseFactory = responseFactory != null ? responseFactory : DefaultClassicHttpResponseFactory.INSTANCE; } - public DefaultHttpResponseParserFactory(final HttpResponseFactory responseFactory) { + public DefaultHttpResponseParserFactory(final HttpResponseFactory responseFactory) { this(null, responseFactory); } @@ -67,8 +68,8 @@ public class DefaultHttpResponseParserFactory implements HttpMessageParserFactor } @Override - public HttpMessageParser create(final MessageConstraints constraints) { - return new LenientHttpResponseParser(this.lineParser, this.responseFactory, constraints); + public HttpMessageParser create(final H1Config h1Config) { + return new LenientHttpResponseParser(this.lineParser, this.responseFactory, h1Config); } } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/DefaultManagedHttpClientConnection.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/DefaultManagedHttpClientConnection.java index 25c7890c7..de1ee5d7f 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/DefaultManagedHttpClientConnection.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/DefaultManagedHttpClientConnection.java @@ -34,18 +34,18 @@ import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicReference; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocket; import org.apache.hc.client5.http.io.ManagedHttpClientConnection; -import org.apache.hc.core5.annotation.NotThreadSafe; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.ContentLengthStrategy; -import org.apache.hc.core5.http.HttpRequest; -import org.apache.hc.core5.http.HttpResponse; -import org.apache.hc.core5.http.config.MessageConstraints; +import org.apache.hc.core5.http.ProtocolVersion; +import org.apache.hc.core5.http.config.H1Config; import org.apache.hc.core5.http.impl.io.DefaultBHttpClientConnection; +import org.apache.hc.core5.http.impl.io.SocketHolder; import org.apache.hc.core5.http.io.HttpMessageParserFactory; import org.apache.hc.core5.http.io.HttpMessageWriterFactory; import org.apache.hc.core5.http.protocol.HttpContext; @@ -54,39 +54,34 @@ import org.apache.hc.core5.http.protocol.HttpContext; * Default {@link ManagedHttpClientConnection} implementation. * @since 4.3 */ -@NotThreadSafe public class DefaultManagedHttpClientConnection extends DefaultBHttpClientConnection - implements ManagedHttpClientConnection, HttpContext { + implements ManagedHttpClientConnection, HttpContext { private final String id; private final Map attributes; - private final AtomicReference socketHolder; private volatile boolean shutdown; public DefaultManagedHttpClientConnection( final String id, final int buffersize, - final int fragmentSizeHint, final CharsetDecoder chardecoder, final CharsetEncoder charencoder, - final MessageConstraints constraints, + final H1Config h1Config, final ContentLengthStrategy incomingContentStrategy, final ContentLengthStrategy outgoingContentStrategy, - final HttpMessageWriterFactory requestWriterFactory, - final HttpMessageParserFactory responseParserFactory) { - super(buffersize, fragmentSizeHint, chardecoder, charencoder, - constraints, incomingContentStrategy, outgoingContentStrategy, + final HttpMessageWriterFactory requestWriterFactory, + final HttpMessageParserFactory responseParserFactory) { + super(buffersize, chardecoder, charencoder, h1Config, incomingContentStrategy, outgoingContentStrategy, requestWriterFactory, responseParserFactory); this.id = id; this.attributes = new ConcurrentHashMap<>(); - this.socketHolder = new AtomicReference<>(null); } public DefaultManagedHttpClientConnection( final String id, final int buffersize) { - this(id, buffersize, buffersize, null, null, null, null, null, null, null); + this(id, buffersize, null, null, null, null, null, null, null); } @Override @@ -101,13 +96,39 @@ public class DefaultManagedHttpClientConnection extends DefaultBHttpClientConnec } @Override - public Object getAttribute(final String id) { - return this.attributes.get(id); + public void bind(final SocketHolder socketHolder) throws IOException { + if (this.shutdown) { + final Socket socket = socketHolder.getSocket(); + socket.close(); // allow this to throw... + // ...but if it doesn't, explicitly throw one ourselves. + throw new InterruptedIOException("Connection already shutdown"); + } + super.bind(socketHolder); } @Override - public Object removeAttribute(final String id) { - return this.attributes.remove(id); + public Socket getSocket() { + final SocketHolder socketHolder = getSocketHolder(); + return socketHolder != null ? socketHolder.getSocket() : null; + } + + @Override + public SSLSession getSSLSession() { + final Socket socket = getSocket(); + if (socket instanceof SSLSocket) { + return ((SSLSocket) socket).getSession(); + } else { + return null; + } + } + + @Override + public void setProtocolVersion(final ProtocolVersion version) { + } + + @Override + public Object getAttribute(final String id) { + return this.attributes.get(id); } @Override @@ -116,30 +137,8 @@ public class DefaultManagedHttpClientConnection extends DefaultBHttpClientConnec } @Override - public void bind(final Socket socket) throws IOException { - if (this.shutdown) { - socket.close(); // allow this to throw... - // ...but if it doesn't, explicitly throw one ourselves. - throw new InterruptedIOException("Connection already shutdown"); - } - if (!this.socketHolder.compareAndSet(socket, socket)) { - super.bind(socket); - } - } - - @Override - public Socket getSocket() { - return this.socketHolder.get(); - } - - @Override - public SSLSession getSSLSession() { - final Socket socket = this.socketHolder.get(); - if (socket instanceof SSLSocket) { - return ((SSLSocket) socket).getSession(); - } else { - return null; - } + public Object removeAttribute(final String id) { + return this.attributes.remove(id); } } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/LenientHttpResponseParser.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/LenientHttpResponseParser.java index 11efed64c..b7b0e503e 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/LenientHttpResponseParser.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/LenientHttpResponseParser.java @@ -29,11 +29,10 @@ package org.apache.hc.client5.http.impl.io; import java.io.IOException; -import org.apache.hc.core5.annotation.NotThreadSafe; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpException; -import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.HttpResponseFactory; -import org.apache.hc.core5.http.config.MessageConstraints; +import org.apache.hc.core5.http.config.H1Config; import org.apache.hc.core5.http.impl.io.DefaultHttpResponseParser; import org.apache.hc.core5.http.message.LineParser; import org.apache.hc.core5.util.CharArrayBuffer; @@ -46,7 +45,6 @@ import org.apache.logging.log4j.Logger; * * @since 4.2 */ -@NotThreadSafe public class LenientHttpResponseParser extends DefaultHttpResponseParser { private final Logger log = LogManager.getLogger(getClass()); @@ -57,31 +55,32 @@ public class LenientHttpResponseParser extends DefaultHttpResponseParser { * @param lineParser the line parser. If {@code null} * {@link org.apache.hc.core5.http.message.BasicLineParser#INSTANCE} will be used. * @param responseFactory HTTP response factory. If {@code null} - * {@link org.apache.hc.core5.http.impl.DefaultHttpResponseFactory#INSTANCE} will be used. - * @param constraints the message constraints. If {@code null} - * {@link MessageConstraints#DEFAULT} will be used. + * {@link org.apache.hc.core5.http.impl.io.DefaultClassicHttpResponseFactory#INSTANCE} + * will be used. + * @param h1Config HTTP/1.1 parameters. If {@code null}. {@link H1Config#DEFAULT} will be used. + * * @since 4.3 */ public LenientHttpResponseParser( final LineParser lineParser, - final HttpResponseFactory responseFactory, - final MessageConstraints constraints) { - super(lineParser, responseFactory, constraints); + final HttpResponseFactory responseFactory, + final H1Config h1Config) { + super(lineParser, responseFactory, h1Config); } /** * Creates new instance of DefaultHttpResponseParser. * - * @param constraints the message constraints. If {@code null} - * {@link MessageConstraints#DEFAULT} will be used. + * @param h1Config HTTP/1.1 parameters. If {@code null}. {@link H1Config#DEFAULT} will be used. + * * @since 4.3 */ - public LenientHttpResponseParser(final MessageConstraints constraints) { - this(null, null, constraints); + public LenientHttpResponseParser(final H1Config h1Config) { + this(null, null, h1Config); } @Override - protected HttpResponse createMessage(final CharArrayBuffer buffer) throws IOException { + protected ClassicHttpResponse createMessage(final CharArrayBuffer buffer) throws IOException { try { return super.createMessage(buffer); } catch (final HttpException ex) { diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/LoggingInputStream.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/LoggingInputStream.java index 38edd0e84..ab6587827 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/LoggingInputStream.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/LoggingInputStream.java @@ -30,14 +30,11 @@ package org.apache.hc.client5.http.impl.io; import java.io.IOException; import java.io.InputStream; -import org.apache.hc.core5.annotation.NotThreadSafe; - /** * Internal class. * * @since 4.3 */ -@NotThreadSafe class LoggingInputStream extends InputStream { private final InputStream in; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/LoggingManagedHttpClientConnection.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/LoggingManagedHttpClientConnection.java index 5d82e033a..f5333edd4 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/LoggingManagedHttpClientConnection.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/LoggingManagedHttpClientConnection.java @@ -28,23 +28,22 @@ package org.apache.hc.client5.http.impl.io; import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; import java.net.Socket; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; -import org.apache.hc.core5.annotation.NotThreadSafe; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.ContentLengthStrategy; import org.apache.hc.core5.http.Header; -import org.apache.hc.core5.http.HttpRequest; -import org.apache.hc.core5.http.HttpResponse; -import org.apache.hc.core5.http.config.MessageConstraints; +import org.apache.hc.core5.http.config.H1Config; +import org.apache.hc.core5.http.impl.io.SocketHolder; import org.apache.hc.core5.http.io.HttpMessageParserFactory; import org.apache.hc.core5.http.io.HttpMessageWriterFactory; +import org.apache.hc.core5.http.message.RequestLine; +import org.apache.hc.core5.http.message.StatusLine; import org.apache.logging.log4j.Logger; -@NotThreadSafe class LoggingManagedHttpClientConnection extends DefaultManagedHttpClientConnection { private final Logger log; @@ -57,16 +56,14 @@ class LoggingManagedHttpClientConnection extends DefaultManagedHttpClientConnect final Logger headerlog, final Logger wirelog, final int buffersize, - final int fragmentSizeHint, final CharsetDecoder chardecoder, final CharsetEncoder charencoder, - final MessageConstraints constraints, + final H1Config h1Config, final ContentLengthStrategy incomingContentStrategy, final ContentLengthStrategy outgoingContentStrategy, - final HttpMessageWriterFactory requestWriterFactory, - final HttpMessageParserFactory responseParserFactory) { - super(id, buffersize, fragmentSizeHint, chardecoder, charencoder, - constraints, incomingContentStrategy, outgoingContentStrategy, + final HttpMessageWriterFactory requestWriterFactory, + final HttpMessageParserFactory responseParserFactory) { + super(id, buffersize, chardecoder, charencoder, h1Config, incomingContentStrategy, outgoingContentStrategy, requestWriterFactory, responseParserFactory); this.log = log; this.headerlog = headerlog; @@ -101,27 +98,14 @@ class LoggingManagedHttpClientConnection extends DefaultManagedHttpClientConnect } @Override - protected InputStream getSocketInputStream(final Socket socket) throws IOException { - InputStream in = super.getSocketInputStream(socket); - if (this.wire.enabled()) { - in = new LoggingInputStream(in, this.wire); - } - return in; + public void bind(final Socket socket) throws IOException { + super.bind(this.wire.enabled() ? new LoggingSocketHolder(socket, this.wire) : new SocketHolder(socket)); } @Override - protected OutputStream getSocketOutputStream(final Socket socket) throws IOException { - OutputStream out = super.getSocketOutputStream(socket); - if (this.wire.enabled()) { - out = new LoggingOutputStream(out, this.wire); - } - return out; - } - - @Override - protected void onResponseReceived(final HttpResponse response) { + protected void onResponseReceived(final ClassicHttpResponse response) { if (response != null && this.headerlog.isDebugEnabled()) { - this.headerlog.debug(getId() + " << " + response.getStatusLine().toString()); + this.headerlog.debug(getId() + " << " + new StatusLine(response)); final Header[] headers = response.getAllHeaders(); for (final Header header : headers) { this.headerlog.debug(getId() + " << " + header.toString()); @@ -130,9 +114,9 @@ class LoggingManagedHttpClientConnection extends DefaultManagedHttpClientConnect } @Override - protected void onRequestSubmitted(final HttpRequest request) { + protected void onRequestSubmitted(final ClassicHttpRequest request) { if (request != null && this.headerlog.isDebugEnabled()) { - this.headerlog.debug(getId() + " >> " + request.getRequestLine().toString()); + this.headerlog.debug(getId() + " >> " + new RequestLine(request)); final Header[] headers = request.getAllHeaders(); for (final Header header : headers) { this.headerlog.debug(getId() + " >> " + header.toString()); diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/LoggingOutputStream.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/LoggingOutputStream.java index 26f0cfb69..6f1655cec 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/LoggingOutputStream.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/LoggingOutputStream.java @@ -30,14 +30,11 @@ package org.apache.hc.client5.http.impl.io; import java.io.IOException; import java.io.OutputStream; -import org.apache.hc.core5.annotation.NotThreadSafe; - /** * Internal class. * * @since 4.3 */ -@NotThreadSafe class LoggingOutputStream extends OutputStream { private final OutputStream out; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/sync/ResponseHandler.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/LoggingSocketHolder.java similarity index 62% rename from httpclient5/src/main/java/org/apache/hc/client5/http/sync/ResponseHandler.java rename to httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/LoggingSocketHolder.java index 9007ab091..b62b1a049 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/sync/ResponseHandler.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/LoggingSocketHolder.java @@ -24,30 +24,32 @@ * . * */ -package org.apache.hc.client5.http.sync; + +package org.apache.hc.client5.http.impl.io; import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.Socket; -import org.apache.hc.core5.http.HttpResponse; +import org.apache.hc.core5.http.impl.io.SocketHolder; -/** - * Handler that encapsulates the process of generating a response object - * from a {@link HttpResponse}. - * - * - * @since 4.0 - */ -public interface ResponseHandler { +class LoggingSocketHolder extends SocketHolder { - /** - * Processes an {@link HttpResponse} and returns some value - * corresponding to that response. - * - * @param response The response to process - * @return A value determined by the response - * - * @throws IOException in case of a problem or the connection was aborted - */ - T handleResponse(HttpResponse response) throws IOException; + private final Wire wire; + LoggingSocketHolder(final Socket socket, final Wire wire) { + super(socket); + this.wire = wire; + } + + @Override + protected InputStream getInputStream(final Socket socket) throws IOException { + return new LoggingInputStream(super.getInputStream(socket), wire); + } + + @Override + protected OutputStream getOutputStream(final Socket socket) throws IOException { + return new LoggingOutputStream(super.getOutputStream(socket), wire); + } } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/ManagedHttpClientConnectionFactory.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/ManagedHttpClientConnectionFactory.java index b0f13d0c2..6bf6dc34d 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/ManagedHttpClientConnectionFactory.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/ManagedHttpClientConnectionFactory.java @@ -36,11 +36,13 @@ import java.util.concurrent.atomic.AtomicLong; import org.apache.hc.client5.http.HttpConnectionFactory; import org.apache.hc.client5.http.HttpRoute; import org.apache.hc.client5.http.io.ManagedHttpClientConnection; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.ContentLengthStrategy; -import org.apache.hc.core5.http.HttpRequest; -import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.config.ConnectionConfig; +import org.apache.hc.core5.http.config.H1Config; import org.apache.hc.core5.http.impl.DefaultContentLengthStrategy; import org.apache.hc.core5.http.impl.io.DefaultHttpRequestWriterFactory; import org.apache.hc.core5.http.io.HttpMessageParserFactory; @@ -52,20 +54,20 @@ import org.apache.logging.log4j.Logger; * Factory for {@link ManagedHttpClientConnection} instances. * @since 4.3 */ -@Immutable -public class ManagedHttpClientConnectionFactory - implements HttpConnectionFactory { +@Contract(threading = ThreadingBehavior.IMMUTABLE) +public class ManagedHttpClientConnectionFactory implements HttpConnectionFactory { private static final AtomicLong COUNTER = new AtomicLong(); public static final ManagedHttpClientConnectionFactory INSTANCE = new ManagedHttpClientConnectionFactory(); private final Logger log = LogManager.getLogger(DefaultManagedHttpClientConnection.class); - private final Logger headerlog = LogManager.getLogger("org.apache.http.headers"); - private final Logger wirelog = LogManager.getLogger("org.apache.http.wire"); + private final Logger headerlog = LogManager.getLogger("org.apache.hc.client5.http.headers"); + private final Logger wirelog = LogManager.getLogger("org.apache.hc.client5.http.wire"); - private final HttpMessageWriterFactory requestWriterFactory; - private final HttpMessageParserFactory responseParserFactory; + private final H1Config h1Config; + private final HttpMessageWriterFactory requestWriterFactory; + private final HttpMessageParserFactory responseParserFactory; private final ContentLengthStrategy incomingContentStrategy; private final ContentLengthStrategy outgoingContentStrategy; @@ -73,11 +75,13 @@ public class ManagedHttpClientConnectionFactory * @since 4.4 */ public ManagedHttpClientConnectionFactory( - final HttpMessageWriterFactory requestWriterFactory, - final HttpMessageParserFactory responseParserFactory, + final H1Config h1Config, + final HttpMessageWriterFactory requestWriterFactory, + final HttpMessageParserFactory responseParserFactory, final ContentLengthStrategy incomingContentStrategy, final ContentLengthStrategy outgoingContentStrategy) { super(); + this.h1Config = h1Config != null ? h1Config : H1Config.DEFAULT; this.requestWriterFactory = requestWriterFactory != null ? requestWriterFactory : DefaultHttpRequestWriterFactory.INSTANCE; this.responseParserFactory = responseParserFactory != null ? responseParserFactory : @@ -89,14 +93,16 @@ public class ManagedHttpClientConnectionFactory } public ManagedHttpClientConnectionFactory( - final HttpMessageWriterFactory requestWriterFactory, - final HttpMessageParserFactory responseParserFactory) { - this(requestWriterFactory, responseParserFactory, null, null); + final H1Config h1Config, + final HttpMessageWriterFactory requestWriterFactory, + final HttpMessageParserFactory responseParserFactory) { + this(h1Config, requestWriterFactory, responseParserFactory, null, null); } public ManagedHttpClientConnectionFactory( - final HttpMessageParserFactory responseParserFactory) { - this(null, responseParserFactory); + final H1Config h1Config, + final HttpMessageParserFactory responseParserFactory) { + this(h1Config, null, responseParserFactory); } public ManagedHttpClientConnectionFactory() { @@ -128,10 +134,9 @@ public class ManagedHttpClientConnectionFactory headerlog, wirelog, cconfig.getBufferSize(), - cconfig.getFragmentSizeHint(), chardecoder, charencoder, - cconfig.getMessageConstraints(), + h1Config, incomingContentStrategy, outgoingContentStrategy, requestWriterFactory, diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/PoolingHttpClientConnectionManager.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/PoolingHttpClientConnectionManager.java index 2cac4d4bc..99e189d3b 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/PoolingHttpClientConnectionManager.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/PoolingHttpClientConnectionManager.java @@ -50,7 +50,9 @@ import org.apache.hc.client5.http.io.ManagedHttpClientConnection; import org.apache.hc.client5.http.socket.ConnectionSocketFactory; import org.apache.hc.client5.http.socket.PlainConnectionSocketFactory; import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory; -import org.apache.hc.core5.annotation.ThreadSafe; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; +import org.apache.hc.core5.function.Callback; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.config.ConnectionConfig; import org.apache.hc.core5.http.config.Lookup; @@ -60,11 +62,11 @@ import org.apache.hc.core5.http.config.SocketConfig; import org.apache.hc.core5.http.io.HttpClientConnection; import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.pool.ConnPoolControl; -import org.apache.hc.core5.pool.PoolEntryCallback; +import org.apache.hc.core5.pool.ConnPoolPolicy; +import org.apache.hc.core5.pool.PoolEntry; import org.apache.hc.core5.pool.PoolStats; -import org.apache.hc.core5.pool.io.ConnFactory; +import org.apache.hc.core5.pool.StrictConnPool; import org.apache.hc.core5.util.Args; -import org.apache.hc.core5.util.Asserts; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -100,7 +102,7 @@ import org.apache.logging.log4j.Logger; * * @since 4.3 */ -@ThreadSafe +@Contract(threading = ThreadingBehavior.SAFE_CONDITIONAL) public class PoolingHttpClientConnectionManager implements HttpClientConnectionManager, ConnPoolControl, Closeable { @@ -110,10 +112,13 @@ public class PoolingHttpClientConnectionManager public static final int DEFAULT_MAX_CONNECTIONS_PER_ROUTE = 5; private final ConfigData configData; - private final CPool pool; + private final StrictConnPool pool; + private final HttpConnectionFactory connFactory; private final HttpClientConnectionOperator connectionOperator; private final AtomicBoolean isShutDown; + private volatile int validateAfterInactivity; + private static Registry getDefaultRegistry() { return RegistryBuilder.create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) @@ -175,17 +180,15 @@ public class PoolingHttpClientConnectionManager * @since 4.4 */ public PoolingHttpClientConnectionManager( - final HttpClientConnectionOperator httpClientConnectionOperator, - final HttpConnectionFactory connFactory, - final long timeToLive, final TimeUnit tunit) { + final HttpClientConnectionOperator httpClientConnectionOperator, + final HttpConnectionFactory connFactory, + final long timeToLive, final TimeUnit tunit) { super(); + this.connectionOperator = Args.notNull(httpClientConnectionOperator, "Connection operator"); + this.connFactory = connFactory != null ? connFactory : ManagedHttpClientConnectionFactory.INSTANCE; this.configData = new ConfigData(); - this.pool = new CPool(new InternalConnectionFactory( - this.configData, connFactory), - DEFAULT_MAX_CONNECTIONS_PER_ROUTE, DEFAULT_MAX_TOTAL_CONNECTIONS, - timeToLive, tunit); - this.pool.setValidateAfterInactivity(2000); - this.connectionOperator = Args.notNull(httpClientConnectionOperator, "HttpClientConnectionOperator"); + this.pool = new StrictConnPool<>( + DEFAULT_MAX_CONNECTIONS_PER_ROUTE, DEFAULT_MAX_TOTAL_CONNECTIONS, timeToLive, tunit, ConnPoolPolicy.LIFO, null); this.isShutDown = new AtomicBoolean(false); } @@ -193,15 +196,16 @@ public class PoolingHttpClientConnectionManager * Visible for test. */ PoolingHttpClientConnectionManager( - final CPool pool, + final StrictConnPool pool, final Lookup socketFactoryRegistry, final SchemePortResolver schemePortResolver, final DnsResolver dnsResolver) { super(); - this.configData = new ConfigData(); - this.pool = pool; this.connectionOperator = new DefaultHttpClientConnectionOperator( socketFactoryRegistry, schemePortResolver, dnsResolver); + this.connFactory = ManagedHttpClientConnectionFactory.INSTANCE; + this.configData = new ConfigData(); + this.pool = pool; this.isShutDown = new AtomicBoolean(false); } @@ -240,9 +244,10 @@ public class PoolingHttpClientConnectionManager return buf.toString(); } - private String format(final CPoolEntry entry) { + private String format(final PoolEntry entry) { final StringBuilder buf = new StringBuilder(); - buf.append("[id: ").append(entry.getId()).append("]"); + final ManagedHttpClientConnection conn = entry.getConnection(); + buf.append("[id: ").append(conn != null ? conn.getId() : "unknown").append("]"); buf.append("[route: ").append(entry.getRoute()).append("]"); final Object state = entry.getState(); if (state != null) { @@ -259,7 +264,7 @@ public class PoolingHttpClientConnectionManager if (this.log.isDebugEnabled()) { this.log.debug("Connection request: " + format(route, state) + formatStats(route)); } - final Future future = this.pool.lease(route, state, null); + final Future> future = this.pool.lease(route, state, null); return new ConnectionRequest() { @Override @@ -279,46 +284,81 @@ public class PoolingHttpClientConnectionManager } protected HttpClientConnection leaseConnection( - final Future future, + final Future> future, final long timeout, final TimeUnit tunit) throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException { - final CPoolEntry entry; + final PoolEntry entry; try { entry = future.get(timeout, tunit); if (entry == null || future.isCancelled()) { throw new InterruptedException(); } - Asserts.check(entry.getConnection() != null, "Pool entry with no connection"); - if (this.log.isDebugEnabled()) { - this.log.debug("Connection leased: " + format(entry) + formatStats(entry.getRoute())); - } - return CPoolProxy.newProxy(entry); } catch (final TimeoutException ex) { + future.cancel(true); throw new ConnectionPoolTimeoutException("Timeout waiting for connection from pool"); } + if (this.validateAfterInactivity > 0) { + final ManagedHttpClientConnection connection = entry.getConnection(); + if (connection != null + && entry.getUpdated() + this.validateAfterInactivity <= System.currentTimeMillis()) { + boolean stale; + try { + stale = connection.isStale(); + } catch (IOException ignore) { + stale = true; + } + if (stale) { + entry.discardConnection(); + } + } + } + final HttpRoute route = entry.getRoute(); + final CPoolProxy poolProxy = new CPoolProxy(entry); + if (entry.hasConnection()) { + poolProxy.markRouteComplete(); + } else { + ConnectionConfig config = null; + if (route.getProxyHost() != null) { + config = this.configData.getConnectionConfig(route.getProxyHost()); + } + if (config == null) { + config = this.configData.getConnectionConfig(route.getTargetHost()); + } + if (config == null) { + config = this.configData.getDefaultConnectionConfig(); + } + if (config == null) { + config = ConnectionConfig.DEFAULT; + } + entry.assignConnection(this.connFactory.create(route, config)); + } + if (this.log.isDebugEnabled()) { + this.log.debug("Connection leased: " + format(entry) + formatStats(route)); + } + return poolProxy; } @Override public void releaseConnection( final HttpClientConnection managedConn, final Object state, - final long keepalive, final TimeUnit tunit) { + final long keepAlive, final TimeUnit timeUnit) { Args.notNull(managedConn, "Managed connection"); synchronized (managedConn) { - final CPoolEntry entry = CPoolProxy.detach(managedConn); - if (entry == null) { + final CPoolProxy poolProxy = CPoolProxy.getProxy(managedConn); + if (poolProxy.isDetached()) { return; } - final ManagedHttpClientConnection conn = entry.getConnection(); + final PoolEntry entry = poolProxy.detach(); try { + final ManagedHttpClientConnection conn = entry.getConnection(); if (conn.isOpen()) { - final TimeUnit effectiveUnit = tunit != null ? tunit : TimeUnit.MILLISECONDS; - entry.setState(state); - entry.updateExpiry(keepalive, effectiveUnit); + final TimeUnit effectiveUnit = timeUnit != null ? timeUnit : TimeUnit.MILLISECONDS; + entry.updateConnection(keepAlive, effectiveUnit, state); if (this.log.isDebugEnabled()) { final String s; - if (keepalive > 0) { - s = "for " + (double) effectiveUnit.toMillis(keepalive) / 1000 + " seconds"; + if (keepAlive > 0) { + s = "for " + (double) effectiveUnit.toMillis(keepAlive) / 1000 + " seconds"; } else { s = "indefinitely"; } @@ -326,7 +366,8 @@ public class PoolingHttpClientConnectionManager } } } finally { - this.pool.release(entry, conn.isOpen() && entry.isRouteComplete()); + final ManagedHttpClientConnection conn = entry.getConnection(); + this.pool.release(entry, conn.isOpen() && poolProxy.isRouteComplete()); if (this.log.isDebugEnabled()) { this.log.debug("Connection released: " + format(entry) + formatStats(entry.getRoute())); } @@ -344,8 +385,8 @@ public class PoolingHttpClientConnectionManager Args.notNull(route, "HTTP route"); final ManagedHttpClientConnection conn; synchronized (managedConn) { - final CPoolEntry entry = CPoolProxy.getPoolEntry(managedConn); - conn = entry.getConnection(); + final CPoolProxy poolProxy = CPoolProxy.getProxy(managedConn); + conn = poolProxy.getConnection(); } final HttpHost host; if (route.getProxyHost() != null) { @@ -374,8 +415,8 @@ public class PoolingHttpClientConnectionManager Args.notNull(route, "HTTP route"); final ManagedHttpClientConnection conn; synchronized (managedConn) { - final CPoolEntry entry = CPoolProxy.getPoolEntry(managedConn); - conn = entry.getConnection(); + final CPoolProxy poolProxy = CPoolProxy.getProxy(managedConn); + conn = poolProxy.getConnection(); } this.connectionOperator.upgrade(conn, route.getTargetHost(), context); } @@ -388,8 +429,8 @@ public class PoolingHttpClientConnectionManager Args.notNull(managedConn, "Managed Connection"); Args.notNull(route, "HTTP route"); synchronized (managedConn) { - final CPoolEntry entry = CPoolProxy.getPoolEntry(managedConn); - entry.markRouteComplete(); + final CPoolProxy poolProxy = CPoolProxy.getProxy(managedConn); + poolProxy.markRouteComplete(); } } @@ -397,17 +438,13 @@ public class PoolingHttpClientConnectionManager public void shutdown() { if (this.isShutDown.compareAndSet(false, true)) { this.log.debug("Connection manager is shutting down"); - try { - this.pool.shutdown(); - } catch (final IOException ex) { - this.log.debug("I/O exception shutting down connection manager", ex); - } + this.pool.shutdown(); this.log.debug("Connection manager shut down"); } } @Override - public void closeIdleConnections(final long idleTimeout, final TimeUnit tunit) { + public void closeIdle(final long idleTimeout, final TimeUnit tunit) { if (this.log.isDebugEnabled()) { this.log.debug("Closing connections idle longer than " + idleTimeout + " " + tunit); } @@ -415,16 +452,16 @@ public class PoolingHttpClientConnectionManager } @Override - public void closeExpiredConnections() { + public void closeExpired() { this.log.debug("Closing expired connections"); this.pool.closeExpired(); } - protected void enumAvailable(final PoolEntryCallback callback) { + protected void enumAvailable(final Callback> callback) { this.pool.enumAvailable(callback); } - protected void enumLeased(final PoolEntryCallback callback) { + protected void enumLeased(final Callback> callback) { this.pool.enumLeased(callback); } @@ -513,7 +550,7 @@ public class PoolingHttpClientConnectionManager * @since 4.4 */ public int getValidateAfterInactivity() { - return pool.getValidateAfterInactivity(); + return validateAfterInactivity; } /** @@ -528,7 +565,7 @@ public class PoolingHttpClientConnectionManager * @since 4.4 */ public void setValidateAfterInactivity(final int ms) { - pool.setValidateAfterInactivity(ms); + validateAfterInactivity = ms; } static class ConfigData { @@ -578,38 +615,4 @@ public class PoolingHttpClientConnectionManager } - static class InternalConnectionFactory implements ConnFactory { - - private final ConfigData configData; - private final HttpConnectionFactory connFactory; - - InternalConnectionFactory( - final ConfigData configData, - final HttpConnectionFactory connFactory) { - super(); - this.configData = configData != null ? configData : new ConfigData(); - this.connFactory = connFactory != null ? connFactory : - ManagedHttpClientConnectionFactory.INSTANCE; - } - - @Override - public ManagedHttpClientConnection create(final HttpRoute route) throws IOException { - ConnectionConfig config = null; - if (route.getProxyHost() != null) { - config = this.configData.getConnectionConfig(route.getProxyHost()); - } - if (config == null) { - config = this.configData.getConnectionConfig(route.getTargetHost()); - } - if (config == null) { - config = this.configData.getDefaultConnectionConfig(); - } - if (config == null) { - config = ConnectionConfig.DEFAULT; - } - return this.connFactory.create(route, config); - } - - } - } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/Wire.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/Wire.java index 8384fa2a0..e03cc2c32 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/Wire.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/Wire.java @@ -30,7 +30,8 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.util.Args; import org.apache.logging.log4j.Logger; @@ -39,7 +40,7 @@ import org.apache.logging.log4j.Logger; * * @since 4.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) class Wire { private final Logger log; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/protocol/DefaultAuthenticationStrategy.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/protocol/DefaultAuthenticationStrategy.java index 896a3782f..7fda71c40 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/protocol/DefaultAuthenticationStrategy.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/protocol/DefaultAuthenticationStrategy.java @@ -43,7 +43,8 @@ import org.apache.hc.client5.http.config.AuthSchemes; import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.protocol.AuthenticationStrategy; import org.apache.hc.client5.http.protocol.HttpClientContext; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.config.Lookup; import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.util.Args; @@ -55,7 +56,7 @@ import org.apache.logging.log4j.Logger; * * @since 5.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class DefaultAuthenticationStrategy implements AuthenticationStrategy { private final Logger log = LogManager.getLogger(getClass()); diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/protocol/DefaultRedirectStrategy.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/protocol/DefaultRedirectStrategy.java index a51357cae..e7b4bb470 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/protocol/DefaultRedirectStrategy.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/protocol/DefaultRedirectStrategy.java @@ -41,20 +41,20 @@ import org.apache.hc.client5.http.protocol.CircularRedirectException; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.protocol.RedirectLocations; import org.apache.hc.client5.http.protocol.RedirectStrategy; -import org.apache.hc.client5.http.utils.URIBuilder; import org.apache.hc.client5.http.utils.URIUtils; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; +import org.apache.hc.core5.http.ClassicHttpRequest; 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.HttpResponse; import org.apache.hc.core5.http.HttpStatus; import org.apache.hc.core5.http.ProtocolException; import org.apache.hc.core5.http.protocol.HttpContext; +import org.apache.hc.core5.net.URIBuilder; import org.apache.hc.core5.util.Args; -import org.apache.hc.core5.util.Asserts; import org.apache.hc.core5.util.TextUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -68,8 +68,8 @@ import org.apache.logging.log4j.Logger; * * @since 4.1 */ -@Immutable -public class DefaultRedirectStrategy implements RedirectStrategy { +@Contract(threading = ThreadingBehavior.IMMUTABLE) +public class DefaultRedirectStrategy implements RedirectStrategy { private final Logger log = LogManager.getLogger(getClass()); @@ -100,7 +100,7 @@ public class DefaultRedirectStrategy implements RedirectStrategy { if (!response.containsHeader(HttpHeaders.LOCATION)) { return false; } - final int statusCode = response.getStatusLine().getStatusCode(); + final int statusCode = response.getCode(); switch (statusCode) { case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_MOVED_TEMPORARILY: @@ -138,11 +138,7 @@ public class DefaultRedirectStrategy implements RedirectStrategy { try { if (!uri.isAbsolute()) { // Resolve location URI - final HttpHost target = clientContext.getTargetHost(); - Asserts.notNull(target, "Target host"); - final URI requestURI = new URI(request.getRequestLine().getUri()); - final URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, false); - uri = URIUtils.resolve(absoluteRequestURI, uri); + uri = URIUtils.resolve(request.getUri(), uri); } } catch (final URISyntaxException ex) { throw new ProtocolException(ex.getMessage(), ex); @@ -185,18 +181,20 @@ public class DefaultRedirectStrategy implements RedirectStrategy { @Override public HttpUriRequest getRedirect( - final HttpRequest request, + final ClassicHttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException { final URI uri = getLocationURI(request, response, context); - final int statusCode = response.getStatusLine().getStatusCode(); + final int statusCode = response.getCode(); switch (statusCode) { case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_MOVED_TEMPORARILY: case HttpStatus.SC_SEE_OTHER: - final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ROOT); + final String method = request.getMethod().toUpperCase(Locale.ROOT); if (!this.safeMethods.containsKey(method)) { - return new HttpGet(uri); + final HttpGet httpGet = new HttpGet(uri); + httpGet.setHeaders(request.getAllHeaders()); + return httpGet; } case HttpStatus.SC_TEMPORARY_REDIRECT: default: diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/protocol/DefaultUserTokenHandler.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/protocol/DefaultUserTokenHandler.java index 621f239b4..d9f9ac47e 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/protocol/DefaultUserTokenHandler.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/protocol/DefaultUserTokenHandler.java @@ -36,7 +36,8 @@ import org.apache.hc.client5.http.auth.AuthScheme; import org.apache.hc.client5.http.io.ManagedHttpClientConnection; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.protocol.UserTokenHandler; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.HttpConnection; import org.apache.hc.core5.http.protocol.HttpContext; @@ -54,7 +55,7 @@ import org.apache.hc.core5.http.protocol.HttpContext; * * @since 4.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class DefaultUserTokenHandler implements UserTokenHandler { public static final DefaultUserTokenHandler INSTANCE = new DefaultUserTokenHandler(); diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/routing/BasicRouteDirector.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/routing/BasicRouteDirector.java index 5d1fcd842..99bf10451 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/routing/BasicRouteDirector.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/routing/BasicRouteDirector.java @@ -29,7 +29,8 @@ package org.apache.hc.client5.http.impl.routing; import org.apache.hc.client5.http.RouteInfo; import org.apache.hc.client5.http.routing.HttpRouteDirector; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.util.Args; /** @@ -37,7 +38,7 @@ import org.apache.hc.core5.util.Args; * * @since 4.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class BasicRouteDirector implements HttpRouteDirector { /** diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/routing/DefaultProxyRoutePlanner.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/routing/DefaultProxyRoutePlanner.java index d061fc1f1..0dd09e55b 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/routing/DefaultProxyRoutePlanner.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/routing/DefaultProxyRoutePlanner.java @@ -28,7 +28,8 @@ package org.apache.hc.client5.http.impl.routing; import org.apache.hc.client5.http.SchemePortResolver; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpRequest; @@ -41,7 +42,7 @@ import org.apache.hc.core5.util.Args; * * @since 4.3 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE_CONDITIONAL) public class DefaultProxyRoutePlanner extends DefaultRoutePlanner { private final HttpHost proxy; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/routing/DefaultRoutePlanner.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/routing/DefaultRoutePlanner.java index 124640a4f..3b917e1d6 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/routing/DefaultRoutePlanner.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/routing/DefaultRoutePlanner.java @@ -36,7 +36,8 @@ import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.impl.DefaultSchemePortResolver; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.routing.HttpRoutePlanner; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpRequest; @@ -50,7 +51,7 @@ import org.apache.hc.core5.util.Args; * * @since 4.3 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE_CONDITIONAL) public class DefaultRoutePlanner implements HttpRoutePlanner { private final SchemePortResolver schemePortResolver; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/routing/SystemDefaultRoutePlanner.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/routing/SystemDefaultRoutePlanner.java index 7f921fd38..6b02b7fad 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/routing/SystemDefaultRoutePlanner.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/routing/SystemDefaultRoutePlanner.java @@ -35,7 +35,8 @@ import java.net.URISyntaxException; import java.util.List; import org.apache.hc.client5.http.SchemePortResolver; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpRequest; @@ -49,7 +50,7 @@ import org.apache.hc.core5.http.protocol.HttpContext; * * @since 4.3 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE_CONDITIONAL) public class SystemDefaultRoutePlanner extends DefaultRoutePlanner { private final ProxySelector proxySelector; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/AbstractResponseHandler.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/AbstractResponseHandler.java index 7b10c79d8..00ba5831d 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/AbstractResponseHandler.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/AbstractResponseHandler.java @@ -30,12 +30,13 @@ package org.apache.hc.client5.http.impl.sync; import java.io.IOException; import org.apache.hc.client5.http.protocol.HttpResponseException; -import org.apache.hc.client5.http.sync.ResponseHandler; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.HttpResponse; -import org.apache.hc.core5.http.StatusLine; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.io.ResponseHandler; +import org.apache.hc.core5.http.io.entity.EntityUtils; /** * A generic {@link ResponseHandler} that works with the response entity @@ -43,14 +44,14 @@ import org.apache.hc.core5.http.entity.EntityUtils; * body is consumed and an {@link HttpResponseException} is thrown. *

* If this is used with - * {@link org.apache.hc.client5.http.sync.HttpClient#execute( - * org.apache.hc.client5.http.methods.HttpUriRequest, ResponseHandler)}, + * {@link org.apache.hc.client5.http.sync.HttpClient#execute(org.apache.hc.core5.http.ClassicHttpRequest, + * ResponseHandler)}, * HttpClient may handle redirects (3xx responses) internally. *

* * @since 4.4 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public abstract class AbstractResponseHandler implements ResponseHandler { /** @@ -60,14 +61,11 @@ public abstract class AbstractResponseHandler implements ResponseHandler { * status code), throws an {@link HttpResponseException}. */ @Override - public T handleResponse(final HttpResponse response) - throws IOException { - final StatusLine statusLine = response.getStatusLine(); + public T handleResponse(final ClassicHttpResponse response) throws IOException { final HttpEntity entity = response.getEntity(); - if (statusLine.getStatusCode() >= 300) { + if (response.getCode() >= HttpStatus.SC_REDIRECTION) { EntityUtils.consume(entity); - throw new HttpResponseException(statusLine.getStatusCode(), - statusLine.getReasonPhrase()); + throw new HttpResponseException(response.getCode(), response.getReasonPhrase()); } return entity == null ? null : handleEntity(entity); } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/BackoffStrategyExec.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/BackoffStrategyExec.java index 6b7ad88ab..8d2af1298 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/BackoffStrategyExec.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/BackoffStrategyExec.java @@ -31,20 +31,21 @@ import java.io.IOException; import java.lang.reflect.UndeclaredThrowableException; import org.apache.hc.client5.http.HttpRoute; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpExecutionAware; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.sync.BackoffManager; import org.apache.hc.client5.http.sync.ConnectionBackoffStrategy; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.util.Args; /** * @since 4.3 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class BackoffStrategyExec implements ClientExecChain { private final ClientExecChain requestExecutor; @@ -65,17 +66,17 @@ public class BackoffStrategyExec implements ClientExecChain { } @Override - public CloseableHttpResponse execute( - final HttpRoute route, - final HttpRequestWrapper request, + public ClassicHttpResponse execute( + final RoutedHttpRequest request, final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException { - Args.notNull(route, "HTTP route"); Args.notNull(request, "HTTP request"); Args.notNull(context, "HTTP context"); - CloseableHttpResponse out = null; + final HttpRoute route = request.getRoute(); + + ClassicHttpResponse out = null; try { - out = this.requestExecutor.execute(route, request, context, execAware); + out = this.requestExecutor.execute(request, context, execAware); } catch (final Exception ex) { if (out != null) { out.close(); diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/BasicCredentialsProvider.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/BasicCredentialsProvider.java index 08625671d..9466be841 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/BasicCredentialsProvider.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/BasicCredentialsProvider.java @@ -32,7 +32,8 @@ import java.util.concurrent.ConcurrentHashMap; import org.apache.hc.client5.http.auth.AuthScope; import org.apache.hc.client5.http.auth.Credentials; import org.apache.hc.client5.http.auth.CredentialsStore; -import org.apache.hc.core5.annotation.ThreadSafe; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.util.Args; @@ -41,7 +42,7 @@ import org.apache.hc.core5.util.Args; * * @since 4.0 */ -@ThreadSafe +@Contract(threading = ThreadingBehavior.SAFE) public class BasicCredentialsProvider implements CredentialsStore { private final ConcurrentHashMap credMap; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/ClientExecChain.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/ClientExecChain.java index 5f286085f..146b23b66 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/ClientExecChain.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/ClientExecChain.java @@ -29,11 +29,10 @@ package org.apache.hc.client5.http.impl.sync; import java.io.IOException; -import org.apache.hc.client5.http.HttpRoute; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpExecutionAware; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.HttpClientContext; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpException; /** @@ -43,7 +42,7 @@ import org.apache.hc.core5.http.HttpException; *

* Important: please note it is required for decorators that implement post execution aspects * or response post-processing of any sort to release resources associated with the response - * by calling {@link CloseableHttpResponse#close()} methods in case of an I/O, protocol or + * by calling {@link ClassicHttpResponse#close()} methods in case of an I/O, protocol or * runtime exception, or in case the response is not propagated to the caller. *

* @@ -55,7 +54,6 @@ public interface ClientExecChain { * Executes th request either by transmitting it to the target server or * by passing it onto the next executor in the request execution chain. * - * @param route connection route. * @param request current request. * @param clientContext current HTTP context. * @param execAware receiver of notifications of blocking I/O operations. @@ -66,9 +64,8 @@ public interface ClientExecChain { * @throws HttpException in case of an HTTP protocol error * (usually this type of exceptions are non-recoverable). */ - CloseableHttpResponse execute( - HttpRoute route, - HttpRequestWrapper request, + ClassicHttpResponse execute( + RoutedHttpRequest request, HttpClientContext clientContext, HttpExecutionAware execAware) throws IOException, HttpException; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/CloseableHttpClient.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/CloseableHttpClient.java index d0d344365..c26187fbe 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/CloseableHttpClient.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/CloseableHttpClient.java @@ -30,18 +30,19 @@ package org.apache.hc.client5.http.impl.sync; import java.io.Closeable; import java.io.IOException; import java.net.URI; +import java.net.URISyntaxException; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; -import org.apache.hc.client5.http.methods.HttpUriRequest; import org.apache.hc.client5.http.protocol.ClientProtocolException; import org.apache.hc.client5.http.sync.HttpClient; -import org.apache.hc.client5.http.sync.ResponseHandler; import org.apache.hc.client5.http.utils.URIUtils; -import org.apache.hc.core5.annotation.ThreadSafe; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; +import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.HttpEntity; +import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpHost; -import org.apache.hc.core5.http.HttpRequest; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.io.ResponseHandler; +import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.util.Args; import org.apache.logging.log4j.LogManager; @@ -52,13 +53,13 @@ import org.apache.logging.log4j.Logger; * * @since 4.3 */ -@ThreadSafe +@Contract(threading = ThreadingBehavior.SAFE) public abstract class CloseableHttpClient implements HttpClient, Closeable { private final Logger log = LogManager.getLogger(getClass()); - protected abstract CloseableHttpResponse doExecute(HttpHost target, HttpRequest request, - HttpContext context) throws IOException; + protected abstract CloseableHttpResponse doExecute(HttpHost target, ClassicHttpRequest request, + HttpContext context) throws IOException; /** * {@inheritDoc} @@ -66,7 +67,7 @@ public abstract class CloseableHttpClient implements HttpClient, Closeable { @Override public CloseableHttpResponse execute( final HttpHost target, - final HttpRequest request, + final ClassicHttpRequest request, final HttpContext context) throws IOException { return doExecute(target, request, context); } @@ -76,19 +77,22 @@ public abstract class CloseableHttpClient implements HttpClient, Closeable { */ @Override public CloseableHttpResponse execute( - final HttpUriRequest request, + final ClassicHttpRequest request, final HttpContext context) throws IOException { Args.notNull(request, "HTTP request"); return doExecute(determineTarget(request), request, context); } - private static HttpHost determineTarget(final HttpUriRequest request) throws ClientProtocolException { + private static HttpHost determineTarget(final ClassicHttpRequest request) throws ClientProtocolException { // A null target may be acceptable if there is a default target. // Otherwise, the null target is detected in the director. HttpHost target = null; - - final URI requestURI = request.getURI(); - if (requestURI.isAbsolute()) { + URI requestURI = null; + try { + requestURI = request.getUri(); + } catch (URISyntaxException ignore) { + } + if (requestURI != null && requestURI.isAbsolute()) { target = URIUtils.extractHost(requestURI); if (target == null) { throw new ClientProtocolException("URI does not specify a valid host name: " @@ -103,7 +107,7 @@ public abstract class CloseableHttpClient implements HttpClient, Closeable { */ @Override public CloseableHttpResponse execute( - final HttpUriRequest request) throws IOException { + final ClassicHttpRequest request) throws IOException { return execute(request, (HttpContext) null); } @@ -113,7 +117,7 @@ public abstract class CloseableHttpClient implements HttpClient, Closeable { @Override public CloseableHttpResponse execute( final HttpHost target, - final HttpRequest request) throws IOException { + final ClassicHttpRequest request) throws IOException { return doExecute(target, request, null); } @@ -133,7 +137,7 @@ public abstract class CloseableHttpClient implements HttpClient, Closeable { * @throws ClientProtocolException in case of an http protocol error */ @Override - public T execute(final HttpUriRequest request, + public T execute(final ClassicHttpRequest request, final ResponseHandler responseHandler) throws IOException { return execute(request, responseHandler, null); } @@ -156,7 +160,7 @@ public abstract class CloseableHttpClient implements HttpClient, Closeable { * @throws ClientProtocolException in case of an http protocol error */ @Override - public T execute(final HttpUriRequest request, + public T execute(final ClassicHttpRequest request, final ResponseHandler responseHandler, final HttpContext context) throws IOException { final HttpHost target = determineTarget(request); @@ -183,7 +187,7 @@ public abstract class CloseableHttpClient implements HttpClient, Closeable { * @throws ClientProtocolException in case of an http protocol error */ @Override - public T execute(final HttpHost target, final HttpRequest request, + public T execute(final HttpHost target, final ClassicHttpRequest request, final ResponseHandler responseHandler) throws IOException { return execute(target, request, responseHandler, null); } @@ -210,7 +214,7 @@ public abstract class CloseableHttpClient implements HttpClient, Closeable { * @throws ClientProtocolException in case of an http protocol error */ @Override - public T execute(final HttpHost target, final HttpRequest request, + public T execute(final HttpHost target, final ClassicHttpRequest request, final ResponseHandler responseHandler, final HttpContext context) throws IOException { Args.notNull(responseHandler, "Response handler"); @@ -220,7 +224,7 @@ public abstract class CloseableHttpClient implements HttpClient, Closeable { final HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); return result; - } catch (final ClientProtocolException t) { + } catch (final HttpException t) { // Try to salvage the underlying connection in case of a protocol exception final HttpEntity entity = response.getEntity(); try { @@ -230,7 +234,7 @@ public abstract class CloseableHttpClient implements HttpClient, Closeable { // important and will be thrown to the caller. this.log.warn("Error consuming content after an exception.", t2); } - throw t; + throw new ClientProtocolException(t); } } } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/HttpResponseProxy.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/CloseableHttpResponse.java similarity index 54% rename from httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/HttpResponseProxy.java rename to httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/CloseableHttpResponse.java index 3a05c6234..11df4c0da 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/HttpResponseProxy.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/CloseableHttpResponse.java @@ -27,184 +27,188 @@ package org.apache.hc.client5.http.impl.sync; +import java.io.Closeable; import java.io.IOException; import java.util.Iterator; import java.util.Locale; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; -import org.apache.hc.core5.annotation.NotThreadSafe; +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.HttpResponse; +import org.apache.hc.core5.http.ProtocolException; import org.apache.hc.core5.http.ProtocolVersion; -import org.apache.hc.core5.http.StatusLine; +import org.apache.hc.core5.util.Args; /** - * A proxy class for {@link org.apache.hc.core5.http.HttpResponse} that can be used to release client connection - * associated with the original response. + * Backward compatibility with HttpClient 4.x. * * @since 4.3 */ -@NotThreadSafe -class HttpResponseProxy implements CloseableHttpResponse { +public final class CloseableHttpResponse implements ClassicHttpResponse { - private final HttpResponse original; - private final ConnectionHolder connHolder; + private final ClassicHttpResponse response; + private final Closeable closeable; - public HttpResponseProxy(final HttpResponse original, final ConnectionHolder connHolder) { - this.original = original; - this.connHolder = connHolder; - ResponseEntityProxy.enchance(original, connHolder); - } - - @Override - public void close() throws IOException { - if (this.connHolder != null) { - this.connHolder.close(); + public static CloseableHttpResponse adapt(final ClassicHttpResponse response) { + if (response == null) { + return null; + } + if (response instanceof CloseableHttpResponse) { + return (CloseableHttpResponse) response; + } else { + return new CloseableHttpResponse(response, null); } } - @Override - public StatusLine getStatusLine() { - return original.getStatusLine(); + public CloseableHttpResponse(final ClassicHttpResponse response, final Closeable closeable) { + this.response = Args.notNull(response, "Response"); + this.closeable = closeable; } @Override public int getCode() { - return original.getCode(); - } - - @Override - public void setStatusLine(final StatusLine statusline) { - original.setStatusLine(statusline); - } - - @Override - public void setStatusLine(final ProtocolVersion ver, final int code) { - original.setStatusLine(ver, code); - } - - @Override - public void setStatusLine(final ProtocolVersion ver, final int code, final String reason) { - original.setStatusLine(ver, code, reason); - } - - @Override - public void setStatusCode(final int code) throws IllegalStateException { - original.setStatusCode(code); - } - - @Override - public void setReasonPhrase(final String reason) throws IllegalStateException { - original.setReasonPhrase(reason); + return response.getCode(); } @Override public HttpEntity getEntity() { - return original.getEntity(); - } - - @Override - public void setEntity(final HttpEntity entity) { - original.setEntity(entity); - } - - @Override - public Locale getLocale() { - return original.getLocale(); - } - - @Override - public void setLocale(final Locale loc) { - original.setLocale(loc); - } - - @Override - public ProtocolVersion getProtocolVersion() { - return original.getProtocolVersion(); - } - - @Override - public int containsHeaders(final String name) { - return original.containsHeaders(name); + return response.getEntity(); } @Override public boolean containsHeader(final String name) { - return original.containsHeader(name); + return response.containsHeader(name); + } + + @Override + public void setVersion(final ProtocolVersion version) { + response.setVersion(version); + } + + @Override + public void setCode(final int code) { + response.setCode(code); + } + + @Override + public String getReasonPhrase() { + return response.getReasonPhrase(); + } + + @Override + public int containsHeaders(final String name) { + return response.containsHeaders(name); + } + + @Override + public void setEntity(final HttpEntity entity) { + response.setEntity(entity); + } + + @Override + public ProtocolVersion getVersion() { + return response.getVersion(); + } + + @Override + public void setReasonPhrase(final String reason) { + response.setReasonPhrase(reason); } @Override public Header[] getHeaders(final String name) { - return original.getHeaders(name); - } - - @Override - public Header getFirstHeader(final String name) { - return original.getFirstHeader(name); - } - - @Override - public Header getLastHeader(final String name) { - return original.getLastHeader(name); - } - - @Override - public Header[] getAllHeaders() { - return original.getAllHeaders(); + return response.getHeaders(name); } @Override public void addHeader(final Header header) { - original.addHeader(header); + response.addHeader(header); + } + + @Override + public Locale getLocale() { + return response.getLocale(); } @Override public void addHeader(final String name, final Object value) { - original.addHeader(name, value); + response.addHeader(name, value); + } + + @Override + public void setLocale(final Locale loc) { + response.setLocale(loc); + } + + @Override + public Header getSingleHeader(final String name) throws ProtocolException { + return response.getSingleHeader(name); } @Override public void setHeader(final Header header) { - original.setHeader(header); + response.setHeader(header); + } + + @Override + public Header getFirstHeader(final String name) { + return response.getFirstHeader(name); } @Override public void setHeader(final String name, final Object value) { - original.setHeader(name, value); + response.setHeader(name, value); } @Override - public void setHeaders(final Header[] headers) { - original.setHeaders(headers); + public void setHeaders(final Header... headers) { + response.setHeaders(headers); } @Override public void removeHeader(final Header header) { - original.removeHeader(header); + response.removeHeader(header); } @Override public void removeHeaders(final String name) { - original.removeHeaders(name); + response.removeHeaders(name); + } + + @Override + public Header getLastHeader(final String name) { + return response.getLastHeader(name); + } + + @Override + public Header[] getAllHeaders() { + return response.getAllHeaders(); } @Override public Iterator
headerIterator() { - return original.headerIterator(); + return response.headerIterator(); } @Override public Iterator
headerIterator(final String name) { - return original.headerIterator(name); + return response.headerIterator(name); + } + + @Override + public void close() throws IOException { + try { + response.close(); + } finally { + if (closeable != null) { + closeable.close(); + } + } } @Override public String toString() { - final StringBuilder sb = new StringBuilder("HttpResponseProxy{"); - sb.append(original); - sb.append('}'); - return sb.toString(); + return response.toString(); } } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/ConnectionHolder.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/ConnectionHolder.java index 060192215..5ed70db43 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/ConnectionHolder.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/ConnectionHolder.java @@ -34,7 +34,8 @@ import java.util.concurrent.atomic.AtomicBoolean; import org.apache.hc.client5.http.io.ConnectionReleaseTrigger; import org.apache.hc.client5.http.io.HttpClientConnectionManager; -import org.apache.hc.core5.annotation.ThreadSafe; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.concurrent.Cancellable; import org.apache.hc.core5.http.io.HttpClientConnection; import org.apache.logging.log4j.Logger; @@ -44,7 +45,7 @@ import org.apache.logging.log4j.Logger; * * @since 4.3 */ -@ThreadSafe +@Contract(threading = ThreadingBehavior.SAFE_CONDITIONAL) class ConnectionHolder implements ConnectionReleaseTrigger, Cancellable, Closeable { private final Logger log; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/DefaultBackoffStrategy.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/DefaultBackoffStrategy.java index 294aeee2f..a968cd752 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/DefaultBackoffStrategy.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/DefaultBackoffStrategy.java @@ -50,7 +50,7 @@ public class DefaultBackoffStrategy implements ConnectionBackoffStrategy { @Override public boolean shouldBackoff(final HttpResponse resp) { - return (resp.getStatusLine().getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE); + return (resp.getCode() == HttpStatus.SC_SERVICE_UNAVAILABLE); } } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/DefaultHttpRequestRetryHandler.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/DefaultHttpRequestRetryHandler.java index a5a8762a2..4e7d61753 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/DefaultHttpRequestRetryHandler.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/DefaultHttpRequestRetryHandler.java @@ -43,7 +43,8 @@ import javax.net.ssl.SSLException; import org.apache.hc.client5.http.methods.HttpUriRequest; import org.apache.hc.client5.http.sync.HttpRequestRetryHandler; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.util.Args; @@ -53,7 +54,7 @@ import org.apache.hc.core5.util.Args; * * @since 4.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class DefaultHttpRequestRetryHandler implements HttpRequestRetryHandler { public static final DefaultHttpRequestRetryHandler INSTANCE = new DefaultHttpRequestRetryHandler(); @@ -174,7 +175,7 @@ public class DefaultHttpRequestRetryHandler implements HttpRequestRetryHandler { * @since 4.2 */ protected boolean handleAsIdempotent(final HttpRequest request) { - final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ROOT); + final String method = request.getMethod().toUpperCase(Locale.ROOT); final Boolean b = this.idempotentMethods.get(method); return b != null && b.booleanValue(); } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/DefaultServiceUnavailableRetryStrategy.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/DefaultServiceUnavailableRetryStrategy.java index 274ff1d07..13d4e5b28 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/DefaultServiceUnavailableRetryStrategy.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/DefaultServiceUnavailableRetryStrategy.java @@ -31,7 +31,8 @@ import java.util.Date; import org.apache.hc.client5.http.sync.ServiceUnavailableRetryStrategy; import org.apache.hc.client5.http.utils.DateUtils; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpHeaders; import org.apache.hc.core5.http.HttpResponse; @@ -46,7 +47,7 @@ import org.apache.hc.core5.util.Args; * * @since 4.2 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class DefaultServiceUnavailableRetryStrategy implements ServiceUnavailableRetryStrategy { /** @@ -75,8 +76,7 @@ public class DefaultServiceUnavailableRetryStrategy implements ServiceUnavailabl @Override public boolean retryRequest(final HttpResponse response, final int executionCount, final HttpContext context) { - return executionCount <= maxRetries && - response.getStatusLine().getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE; + return executionCount <= maxRetries && response.getCode() == HttpStatus.SC_SERVICE_UNAVAILABLE; } @Override diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/FutureRequestExecutionService.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/FutureRequestExecutionService.java index 361d0d724..c03e61566 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/FutureRequestExecutionService.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/FutureRequestExecutionService.java @@ -33,16 +33,17 @@ import java.util.concurrent.atomic.AtomicBoolean; import org.apache.hc.client5.http.methods.HttpUriRequest; import org.apache.hc.client5.http.sync.HttpClient; -import org.apache.hc.client5.http.sync.ResponseHandler; -import org.apache.hc.core5.annotation.ThreadSafe; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.concurrent.FutureCallback; +import org.apache.hc.core5.http.io.ResponseHandler; import org.apache.hc.core5.http.protocol.HttpContext; /** * HttpAsyncClientWithFuture wraps calls to execute with a {@link HttpRequestFutureTask} * and schedules them using the provided executor service. Scheduled calls may be cancelled. */ -@ThreadSafe +@Contract(threading = ThreadingBehavior.SAFE_CONDITIONAL) public class FutureRequestExecutionService implements Closeable { private final HttpClient httpclient; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/HttpClientBuilder.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/HttpClientBuilder.java index 6e847ce2d..91707a3c5 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/HttpClientBuilder.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/HttpClientBuilder.java @@ -93,7 +93,6 @@ import org.apache.hc.client5.http.sync.BackoffManager; import org.apache.hc.client5.http.sync.ConnectionBackoffStrategy; import org.apache.hc.client5.http.sync.HttpRequestRetryHandler; import org.apache.hc.client5.http.sync.ServiceUnavailableRetryStrategy; -import org.apache.hc.core5.annotation.NotThreadSafe; import org.apache.hc.core5.http.ConnectionReuseStrategy; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpHost; @@ -107,10 +106,10 @@ import org.apache.hc.core5.http.config.RegistryBuilder; import org.apache.hc.core5.http.config.SocketConfig; import org.apache.hc.core5.http.impl.DefaultConnectionReuseStrategy; import org.apache.hc.core5.http.impl.io.HttpRequestExecutor; +import org.apache.hc.core5.http.protocol.DefaultHttpProcessor; import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.http.protocol.HttpProcessor; import org.apache.hc.core5.http.protocol.HttpProcessorBuilder; -import org.apache.hc.core5.http.protocol.ImmutableHttpProcessor; import org.apache.hc.core5.http.protocol.RequestContent; import org.apache.hc.core5.http.protocol.RequestTargetHost; import org.apache.hc.core5.http.protocol.RequestUserAgent; @@ -155,7 +154,6 @@ import org.apache.hc.core5.util.VersionInfo; * * @since 4.3 */ -@NotThreadSafe public class HttpClientBuilder { private HttpRequestExecutor requestExec; @@ -786,7 +784,7 @@ public class HttpClientBuilder { * inside an EJB container. * * @see #setConnectionManagerShared(boolean) - * @see HttpClientConnectionManager#closeExpiredConnections() + * @see HttpClientConnectionManager#closeExpired() * * @since 4.4 */ @@ -809,7 +807,7 @@ public class HttpClientBuilder { * inside an EJB container. * * @see #setConnectionManagerShared(boolean) - * @see HttpClientConnectionManager#closeExpiredConnections() + * @see HttpClientConnectionManager#closeExpired() * * @param maxIdleTime maximum time persistent connections can stay idle while kept alive * in the connection pool. Connections whose inactivity period exceeds this value will @@ -1011,7 +1009,7 @@ public class HttpClientBuilder { userAgentCopy = System.getProperty("http.agent"); } if (userAgentCopy == null) { - userAgentCopy = VersionInfo.getUserAgent("Apache-HttpClient", + userAgentCopy = VersionInfo.getSoftwareInfo("Apache-HttpClient", "org.apache.hc.client5", getClass()); } } @@ -1021,7 +1019,7 @@ public class HttpClientBuilder { connManagerCopy, reuseStrategyCopy, keepAliveStrategyCopy, - new ImmutableHttpProcessor(new RequestTargetHost(), new RequestUserAgent(userAgentCopy)), + new DefaultHttpProcessor(new RequestTargetHost(), new RequestUserAgent(userAgentCopy)), targetAuthStrategyCopy, proxyAuthStrategyCopy, userTokenHandlerCopy); diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/HttpClients.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/HttpClients.java index 76927e24d..20ee88d9c 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/HttpClients.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/HttpClients.java @@ -29,13 +29,11 @@ package org.apache.hc.client5.http.impl.sync; import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager; import org.apache.hc.client5.http.io.HttpClientConnectionManager; -import org.apache.hc.core5.annotation.Immutable; /** * Factory methods for {@link CloseableHttpClient} instances. * @since 4.3 */ -@Immutable public class HttpClients { private HttpClients() { diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/HttpRequestFutureTask.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/HttpRequestFutureTask.java index b6a523d9f..7edb3ae7e 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/HttpRequestFutureTask.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/HttpRequestFutureTask.java @@ -112,7 +112,7 @@ public class HttpRequestFutureTask extends FutureTask { @Override public String toString() { - return request.getRequestLine().getUri(); + return request.toString(); } } \ No newline at end of file diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/HttpRequestTaskCallable.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/HttpRequestTaskCallable.java index c9078b734..563851df3 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/HttpRequestTaskCallable.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/HttpRequestTaskCallable.java @@ -31,8 +31,8 @@ import java.util.concurrent.atomic.AtomicBoolean; import org.apache.hc.client5.http.methods.HttpUriRequest; import org.apache.hc.client5.http.sync.HttpClient; -import org.apache.hc.client5.http.sync.ResponseHandler; import org.apache.hc.core5.concurrent.FutureCallback; +import org.apache.hc.core5.http.io.ResponseHandler; import org.apache.hc.core5.http.protocol.HttpContext; class HttpRequestTaskCallable implements Callable { @@ -107,7 +107,7 @@ class HttpRequestTaskCallable implements Callable { metrics.getActiveConnections().decrementAndGet(); } } else { - throw new IllegalStateException("call has been cancelled for request " + request.getURI()); + throw new IllegalStateException("call has been cancelled"); } } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/IdleConnectionEvictor.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/IdleConnectionEvictor.java index 15ece8a62..4f3bd5b89 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/IdleConnectionEvictor.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/IdleConnectionEvictor.java @@ -64,9 +64,9 @@ public final class IdleConnectionEvictor { try { while (!Thread.currentThread().isInterrupted()) { Thread.sleep(sleepTimeMs); - connectionManager.closeExpiredConnections(); + connectionManager.closeExpired(); if (maxIdleTimeMs > 0) { - connectionManager.closeIdleConnections(maxIdleTimeMs, TimeUnit.MILLISECONDS); + connectionManager.closeIdle(maxIdleTimeMs, TimeUnit.MILLISECONDS); } } } catch (final Exception ex) { diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/InternalHttpClient.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/InternalHttpClient.java index 44e8c7f34..d6f628a99 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/InternalHttpClient.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/InternalHttpClient.java @@ -38,20 +38,23 @@ import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.cookie.CookieSpecProvider; import org.apache.hc.client5.http.cookie.CookieStore; import org.apache.hc.client5.http.io.HttpClientConnectionManager; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; import org.apache.hc.client5.http.methods.Configurable; import org.apache.hc.client5.http.methods.HttpExecutionAware; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.ClientProtocolException; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.routing.HttpRoutePlanner; -import org.apache.hc.core5.annotation.ThreadSafe; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.config.Lookup; import org.apache.hc.core5.http.protocol.BasicHttpContext; import org.apache.hc.core5.http.protocol.HttpContext; +import org.apache.hc.core5.net.URIAuthority; import org.apache.hc.core5.util.Args; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -61,7 +64,7 @@ import org.apache.logging.log4j.Logger; * * @since 4.3 */ -@ThreadSafe +@Contract(threading = ThreadingBehavior.SAFE_CONDITIONAL) class InternalHttpClient extends CloseableHttpClient implements Configurable { private final Logger log = LogManager.getLogger(getClass()); @@ -129,7 +132,7 @@ class InternalHttpClient extends CloseableHttpClient implements Configurable { @Override protected CloseableHttpResponse doExecute( final HttpHost target, - final HttpRequest request, + final ClassicHttpRequest request, final HttpContext context) throws IOException { Args.notNull(request, "HTTP request"); HttpExecutionAware execAware = null; @@ -137,7 +140,12 @@ class InternalHttpClient extends CloseableHttpClient implements Configurable { execAware = (HttpExecutionAware) request; } try { - final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(request, target); + if (request.getScheme() == null) { + request.setScheme(target.getSchemeName()); + } + if (request.getAuthority() == null) { + request.setAuthority(new URIAuthority(target)); + } final HttpClientContext localcontext = HttpClientContext.adapt( context != null ? context : new BasicHttpContext()); RequestConfig config = null; @@ -148,8 +156,10 @@ class InternalHttpClient extends CloseableHttpClient implements Configurable { localcontext.setRequestConfig(config); } setupContext(localcontext); - final HttpRoute route = determineRoute(target, wrapper, localcontext); - return this.execChain.execute(route, wrapper, localcontext, execAware); + final HttpRoute route = determineRoute(target, request, localcontext); + final ClassicHttpResponse response = this.execChain.execute( + RoutedHttpRequest.adapt(request, route), localcontext, execAware); + return CloseableHttpResponse.adapt(response); } catch (final HttpException httpException) { throw new ClientProtocolException(httpException); } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/MainClientExec.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/MainClientExec.java index d50ab03b7..b2bef708e 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/MainClientExec.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/MainClientExec.java @@ -43,15 +43,17 @@ import org.apache.hc.client5.http.impl.io.ConnectionShutdownException; import org.apache.hc.client5.http.impl.routing.BasicRouteDirector; import org.apache.hc.client5.http.io.ConnectionRequest; import org.apache.hc.client5.http.io.HttpClientConnectionManager; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpExecutionAware; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.AuthenticationStrategy; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.protocol.NonRepeatableRequestException; import org.apache.hc.client5.http.protocol.UserTokenHandler; import org.apache.hc.client5.http.routing.HttpRouteDirector; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.ConnectionReuseStrategy; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.HttpException; @@ -59,14 +61,18 @@ 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.HttpResponse; -import org.apache.hc.core5.http.entity.BufferedHttpEntity; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.HttpVersion; import org.apache.hc.core5.http.impl.io.HttpRequestExecutor; import org.apache.hc.core5.http.io.HttpClientConnection; -import org.apache.hc.core5.http.message.BasicHttpRequest; +import org.apache.hc.core5.http.io.entity.BufferedHttpEntity; +import org.apache.hc.core5.http.io.entity.EntityUtils; +import org.apache.hc.core5.http.message.BasicClassicHttpRequest; +import org.apache.hc.core5.http.message.RequestLine; +import org.apache.hc.core5.http.message.StatusLine; +import org.apache.hc.core5.http.protocol.DefaultHttpProcessor; import org.apache.hc.core5.http.protocol.HttpCoreContext; import org.apache.hc.core5.http.protocol.HttpProcessor; -import org.apache.hc.core5.http.protocol.ImmutableHttpProcessor; import org.apache.hc.core5.http.protocol.RequestTargetHost; import org.apache.hc.core5.util.Args; import org.apache.logging.log4j.LogManager; @@ -82,7 +88,7 @@ import org.apache.logging.log4j.Logger; * * @since 4.3 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE_CONDITIONAL) public class MainClientExec implements ClientExecChain { private final Logger log = LogManager.getLogger(getClass()); @@ -139,19 +145,18 @@ public class MainClientExec implements ClientExecChain { final AuthenticationStrategy proxyAuthStrategy, final UserTokenHandler userTokenHandler) { this(requestExecutor, connManager, reuseStrategy, keepAliveStrategy, - new ImmutableHttpProcessor(new RequestTargetHost()), + new DefaultHttpProcessor(new RequestTargetHost()), targetAuthStrategy, proxyAuthStrategy, userTokenHandler); } @Override - public CloseableHttpResponse execute( - final HttpRoute route, - final HttpRequestWrapper request, + public ClassicHttpResponse execute( + final RoutedHttpRequest request, final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException { - Args.notNull(route, "HTTP route"); Args.notNull(request, "HTTP request"); Args.notNull(context, "HTTP context"); + final HttpRoute route = request.getRoute(); RequestEntityProxy.enhance(request); @@ -196,7 +201,7 @@ public class MainClientExec implements ClientExecChain { final AuthExchange proxyAuthExchange = route.getProxyHost() != null ? context.getAuthExchange(route.getProxyHost()) : new AuthExchange(); - HttpResponse response; + ClassicHttpResponse response; for (int execCount = 1;; execCount++) { if (execCount > 1 && !RequestEntityProxy.isRepeatable(request)) { @@ -230,7 +235,7 @@ public class MainClientExec implements ClientExecChain { } if (this.log.isDebugEnabled()) { - this.log.debug("Executing request " + request.getRequestLine()); + this.log.debug("Executing request " + new RequestLine(request)); } if (!request.containsHeader(HttpHeaders.AUTHORIZATION)) { @@ -275,7 +280,7 @@ public class MainClientExec implements ClientExecChain { } if (needAuthentication( - targetAuthExchange, proxyAuthExchange, route, response, context)) { + targetAuthExchange, proxyAuthExchange, route, request, response, context)) { // Make sure the response body is fully consumed, if present final HttpEntity entity = response.getEntity(); if (connHolder.isReusable()) { @@ -321,9 +326,10 @@ public class MainClientExec implements ClientExecChain { if (entity == null || !entity.isStreaming()) { // connection not needed and (assumed to be) in re-usable state connHolder.releaseConnection(); - return new HttpResponseProxy(response, null); + return new CloseableHttpResponse(response, null); } else { - return new HttpResponseProxy(response, connHolder); + ResponseEntityProxy.enchance(response, connHolder); + return new CloseableHttpResponse(response, connHolder); } } catch (final ConnectionShutdownException ex) { final InterruptedIOException ioex = new InterruptedIOException( @@ -427,10 +433,11 @@ public class MainClientExec implements ClientExecChain { final HttpHost target = route.getTargetHost(); final HttpHost proxy = route.getProxyHost(); final AuthExchange proxyAuthExchange = context.getAuthExchange(proxy); - HttpResponse response = null; + ClassicHttpResponse response = null; final String authority = target.toHostString(); - final HttpRequest connect = new BasicHttpRequest("CONNECT", authority, request.getProtocolVersion()); + final ClassicHttpRequest connect = new BasicClassicHttpRequest("CONNECT", authority); + connect.setVersion(HttpVersion.HTTP_1_1); this.requestExecutor.preProcess(connect, this.proxyHttpProcessor, context); @@ -448,10 +455,9 @@ public class MainClientExec implements ClientExecChain { response = this.requestExecutor.execute(connect, managedConn, context); - final int status = response.getStatusLine().getStatusCode(); - if (status < 200) { - throw new HttpException("Unexpected response to CONNECT request: " + - response.getStatusLine()); + final int status = response.getCode(); + if (status < HttpStatus.SC_SUCCESS) { + throw new HttpException("Unexpected response to CONNECT request: " + new StatusLine(response)); } if (config.isAuthenticationEnabled()) { @@ -474,9 +480,8 @@ public class MainClientExec implements ClientExecChain { } } - final int status = response.getStatusLine().getStatusCode(); - - if (status > 299) { + final int status = response.getCode(); + if (status >= HttpStatus.SC_REDIRECTION) { // Buffer response content final HttpEntity entity = response.getEntity(); @@ -486,7 +491,7 @@ public class MainClientExec implements ClientExecChain { managedConn.close(); throw new TunnelRefusedException("CONNECT refused by proxy: " + - response.getStatusLine(), response); + new StatusLine(response), response); } // How to decide on security of the tunnelled connection? @@ -522,14 +527,12 @@ public class MainClientExec implements ClientExecChain { final AuthExchange targetAuthExchange, final AuthExchange proxyAuthExchange, final HttpRoute route, + final RoutedHttpRequest request, final HttpResponse response, final HttpClientContext context) { final RequestConfig config = context.getRequestConfig(); if (config.isAuthenticationEnabled()) { - HttpHost target = context.getTargetHost(); - if (target == null) { - target = route.getTargetHost(); - } + HttpHost target = request.getTargetHost(); if (target.getPort() < 0) { target = new HttpHost( target.getHostName(), diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/MinimalClientExec.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/MinimalClientExec.java index c43e8a659..05f485f02 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/MinimalClientExec.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/MinimalClientExec.java @@ -29,8 +29,6 @@ package org.apache.hc.client5.http.impl.sync; import java.io.IOException; import java.io.InterruptedIOException; -import java.net.URI; -import java.net.URISyntaxException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; @@ -40,26 +38,21 @@ import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.impl.io.ConnectionShutdownException; import org.apache.hc.client5.http.io.ConnectionRequest; import org.apache.hc.client5.http.io.HttpClientConnectionManager; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpExecutionAware; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; -import org.apache.hc.client5.http.methods.HttpUriRequest; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.protocol.RequestClientConnControl; -import org.apache.hc.client5.http.utils.URIUtils; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.ConnectionReuseStrategy; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.HttpException; -import org.apache.hc.core5.http.HttpHost; -import org.apache.hc.core5.http.HttpRequest; -import org.apache.hc.core5.http.HttpResponse; -import org.apache.hc.core5.http.ProtocolException; import org.apache.hc.core5.http.impl.io.HttpRequestExecutor; import org.apache.hc.core5.http.io.HttpClientConnection; +import org.apache.hc.core5.http.protocol.DefaultHttpProcessor; import org.apache.hc.core5.http.protocol.HttpCoreContext; import org.apache.hc.core5.http.protocol.HttpProcessor; -import org.apache.hc.core5.http.protocol.ImmutableHttpProcessor; import org.apache.hc.core5.http.protocol.RequestContent; import org.apache.hc.core5.http.protocol.RequestTargetHost; import org.apache.hc.core5.http.protocol.RequestUserAgent; @@ -77,7 +70,7 @@ import org.apache.logging.log4j.Logger; * * @since 4.3 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class MinimalClientExec implements ClientExecChain { private final Logger log = LogManager.getLogger(getClass()); @@ -97,11 +90,11 @@ public class MinimalClientExec implements ClientExecChain { Args.notNull(connManager, "Client connection manager"); Args.notNull(reuseStrategy, "Connection reuse strategy"); Args.notNull(keepAliveStrategy, "Connection keep alive strategy"); - this.httpProcessor = new ImmutableHttpProcessor( + this.httpProcessor = new DefaultHttpProcessor( new RequestContent(), new RequestTargetHost(), new RequestClientConnControl(), - new RequestUserAgent(VersionInfo.getUserAgent( + new RequestUserAgent(VersionInfo.getSoftwareInfo( "Apache-HttpClient", "org.apache.hc.client5", getClass()))); this.requestExecutor = requestExecutor; this.connManager = connManager; @@ -109,37 +102,15 @@ public class MinimalClientExec implements ClientExecChain { this.keepAliveStrategy = keepAliveStrategy; } - static void rewriteRequestURI( - final HttpRequestWrapper request, - final HttpRoute route) throws ProtocolException { - try { - URI uri = request.getURI(); - if (uri != null) { - // Make sure the request URI is relative - if (uri.isAbsolute()) { - uri = URIUtils.rewriteURI(uri, null, true); - } else { - uri = URIUtils.rewriteURI(uri); - } - request.setURI(uri); - } - } catch (final URISyntaxException ex) { - throw new ProtocolException("Invalid URI: " + request.getRequestLine().getUri(), ex); - } - } - @Override - public CloseableHttpResponse execute( - final HttpRoute route, - final HttpRequestWrapper request, + public ClassicHttpResponse execute( + final RoutedHttpRequest request, final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException { - Args.notNull(route, "HTTP route"); Args.notNull(request, "HTTP request"); Args.notNull(context, "HTTP context"); - rewriteRequestURI(request, route); - + final HttpRoute route = request.getRoute(); final ConnectionRequest connRequest = connManager.requestConnection(route, null); if (execAware != null) { if (execAware.isAborted()) { @@ -166,14 +137,14 @@ public class MinimalClientExec implements ClientExecChain { throw new RequestAbortedException("Request execution failed", cause); } - final ConnectionHolder releaseTrigger = new ConnectionHolder(log, connManager, managedConn); + final ConnectionHolder connHolder = new ConnectionHolder(log, connManager, managedConn); try { if (execAware != null) { if (execAware.isAborted()) { - releaseTrigger.close(); + connHolder.close(); throw new RequestAbortedException("Request aborted"); } - execAware.setCancellable(releaseTrigger); + execAware.setCancellable(connHolder); } if (!managedConn.isOpen()) { @@ -190,52 +161,41 @@ public class MinimalClientExec implements ClientExecChain { managedConn.setSocketTimeout(timeout); } - HttpHost target = null; - final HttpRequest original = request.getOriginal(); - if (original instanceof HttpUriRequest) { - final URI uri = ((HttpUriRequest) original).getURI(); - if (uri.isAbsolute()) { - target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); - } - } - if (target == null) { - target = route.getTargetHost(); - } - - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target); context.setAttribute(HttpCoreContext.HTTP_REQUEST, request); context.setAttribute(HttpCoreContext.HTTP_CONNECTION, managedConn); context.setAttribute(HttpClientContext.HTTP_ROUTE, route); - httpProcessor.process(request, context); - final HttpResponse response = requestExecutor.execute(request, managedConn, context); - httpProcessor.process(response, context); + httpProcessor.process(request, request.getEntity(), context); + final ClassicHttpResponse response = requestExecutor.execute(request, managedConn, context); + httpProcessor.process(response, response.getEntity(), context); // The connection is in or can be brought to a re-usable state. if (reuseStrategy.keepAlive(request, response, context)) { // Set the idle duration of this connection final long duration = keepAliveStrategy.getKeepAliveDuration(response, context); - releaseTrigger.setValidFor(duration, TimeUnit.MILLISECONDS); - releaseTrigger.markReusable(); + connHolder.setValidFor(duration, TimeUnit.MILLISECONDS); + connHolder.markReusable(); } else { - releaseTrigger.markNonReusable(); + connHolder.markNonReusable(); } // check for entity, release connection if possible final HttpEntity entity = response.getEntity(); if (entity == null || !entity.isStreaming()) { // connection not needed and (assumed to be) in re-usable state - releaseTrigger.releaseConnection(); - return new HttpResponseProxy(response, null); + connHolder.releaseConnection(); + return new CloseableHttpResponse(response, null); + } else { + ResponseEntityProxy.enchance(response, connHolder); + return new CloseableHttpResponse(response, connHolder); } - return new HttpResponseProxy(response, releaseTrigger); } catch (final ConnectionShutdownException ex) { final InterruptedIOException ioex = new InterruptedIOException( "Connection has been shut down"); ioex.initCause(ex); throw ioex; } catch (final HttpException | RuntimeException | IOException ex) { - releaseTrigger.abortConnection(); + connHolder.abortConnection(); throw ex; } } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/MinimalHttpClient.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/MinimalHttpClient.java index 252bccc4d..37c976f88 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/MinimalHttpClient.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/MinimalHttpClient.java @@ -33,20 +33,22 @@ import org.apache.hc.client5.http.HttpRoute; import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.impl.DefaultConnectionKeepAliveStrategy; import org.apache.hc.client5.http.io.HttpClientConnectionManager; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; import org.apache.hc.client5.http.methods.Configurable; import org.apache.hc.client5.http.methods.HttpExecutionAware; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.ClientProtocolException; import org.apache.hc.client5.http.protocol.HttpClientContext; -import org.apache.hc.core5.annotation.ThreadSafe; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpHost; -import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.impl.DefaultConnectionReuseStrategy; import org.apache.hc.core5.http.impl.io.HttpRequestExecutor; import org.apache.hc.core5.http.protocol.BasicHttpContext; import org.apache.hc.core5.http.protocol.HttpContext; +import org.apache.hc.core5.net.URIAuthority; import org.apache.hc.core5.util.Args; /** @@ -54,7 +56,7 @@ import org.apache.hc.core5.util.Args; * * @since 4.3 */ -@ThreadSafe +@Contract(threading = ThreadingBehavior.SAFE) class MinimalHttpClient extends CloseableHttpClient { private final HttpClientConnectionManager connManager; @@ -74,7 +76,7 @@ class MinimalHttpClient extends CloseableHttpClient { @Override protected CloseableHttpResponse doExecute( final HttpHost target, - final HttpRequest request, + final ClassicHttpRequest request, final HttpContext context) throws IOException { Args.notNull(target, "Target host"); Args.notNull(request, "HTTP request"); @@ -83,10 +85,14 @@ class MinimalHttpClient extends CloseableHttpClient { execAware = (HttpExecutionAware) request; } try { - final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(request, target); + if (request.getScheme() == null) { + request.setScheme(target.getSchemeName()); + } + if (request.getAuthority() == null) { + request.setAuthority(new URIAuthority(target)); + } final HttpClientContext localcontext = HttpClientContext.adapt( - context != null ? context : new BasicHttpContext()); - final HttpRoute route = new HttpRoute(target); + context != null ? context : new BasicHttpContext()); RequestConfig config = null; if (request instanceof Configurable) { config = ((Configurable) request).getConfig(); @@ -94,7 +100,10 @@ class MinimalHttpClient extends CloseableHttpClient { if (config != null) { localcontext.setRequestConfig(config); } - return this.requestExecutor.execute(route, wrapper, localcontext, execAware); + final HttpRoute route = new HttpRoute(target); + final ClassicHttpResponse response = this.requestExecutor.execute( + RoutedHttpRequest.adapt(request, route), localcontext, execAware); + return CloseableHttpResponse.adapt(response); } catch (final HttpException httpException) { throw new ClientProtocolException(httpException); } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/NoopUserTokenHandler.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/NoopUserTokenHandler.java index 34986b655..e2acc84be 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/NoopUserTokenHandler.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/NoopUserTokenHandler.java @@ -28,7 +28,8 @@ package org.apache.hc.client5.http.impl.sync; import org.apache.hc.client5.http.HttpRoute; import org.apache.hc.client5.http.protocol.UserTokenHandler; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.protocol.HttpContext; /** @@ -36,7 +37,7 @@ import org.apache.hc.core5.http.protocol.HttpContext; * * @since 4.3 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class NoopUserTokenHandler implements UserTokenHandler { public static final NoopUserTokenHandler INSTANCE = new NoopUserTokenHandler(); diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/ProtocolExec.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/ProtocolExec.java index 6a2f8b92e..119bdd54c 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/ProtocolExec.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/ProtocolExec.java @@ -28,30 +28,24 @@ package org.apache.hc.client5.http.impl.sync; import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; import org.apache.hc.client5.http.HttpRoute; import org.apache.hc.client5.http.auth.AuthScope; import org.apache.hc.client5.http.auth.CredentialsProvider; import org.apache.hc.client5.http.auth.CredentialsStore; import org.apache.hc.client5.http.auth.UsernamePasswordCredentials; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; +import org.apache.hc.client5.http.config.AuthSchemes; import org.apache.hc.client5.http.methods.HttpExecutionAware; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; -import org.apache.hc.client5.http.methods.HttpUriRequest; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.HttpClientContext; -import org.apache.hc.client5.http.utils.URIUtils; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpException; -import org.apache.hc.core5.http.HttpHost; -import org.apache.hc.core5.http.HttpRequest; -import org.apache.hc.core5.http.ProtocolException; import org.apache.hc.core5.http.protocol.HttpCoreContext; import org.apache.hc.core5.http.protocol.HttpProcessor; +import org.apache.hc.core5.net.URIAuthority; import org.apache.hc.core5.util.Args; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; /** * Request executor in the request execution chain that is responsible @@ -67,11 +61,9 @@ import org.apache.logging.log4j.Logger; * * @since 4.3 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class ProtocolExec implements ClientExecChain { - private final Logger log = LogManager.getLogger(getClass()); - private final ClientExecChain requestExecutor; private final HttpProcessor httpProcessor; @@ -82,65 +74,18 @@ public class ProtocolExec implements ClientExecChain { this.httpProcessor = httpProcessor; } - void rewriteRequestURI( - final HttpRequestWrapper request, - final HttpRoute route) throws ProtocolException { - final URI uri = request.getURI(); - if (uri != null) { - try { - request.setURI(URIUtils.rewriteURIForRoute(uri, route)); - } catch (final URISyntaxException ex) { - throw new ProtocolException("Invalid URI: " + uri, ex); - } - } - } - @Override - public CloseableHttpResponse execute( - final HttpRoute route, - final HttpRequestWrapper request, + public ClassicHttpResponse execute( + final RoutedHttpRequest request, final HttpClientContext context, - final HttpExecutionAware execAware) throws IOException, - HttpException { - Args.notNull(route, "HTTP route"); + final HttpExecutionAware execAware) throws IOException, HttpException { Args.notNull(request, "HTTP request"); Args.notNull(context, "HTTP context"); - final HttpRequest original = request.getOriginal(); - URI uri = null; - if (original instanceof HttpUriRequest) { - uri = ((HttpUriRequest) original).getURI(); - } else { - final String uriString = original.getRequestLine().getUri(); - try { - uri = URI.create(uriString); - } catch (final IllegalArgumentException ex) { - if (this.log.isDebugEnabled()) { - this.log.debug("Unable to parse '" + uriString + "' as a valid URI; " + - "request URI and Host header may be inconsistent", ex); - } - } - - } - request.setURI(uri); - - // Re-write request URI if needed - rewriteRequestURI(request, route); - - HttpHost target = null; - if (uri != null && uri.isAbsolute() && uri.getHost() != null) { - target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); - } - if (target == null) { - target = request.getTarget(); - } - if (target == null) { - target = route.getTargetHost(); - } - - // Get user info from the URI - if (uri != null) { - final String userinfo = uri.getUserInfo(); + final HttpRoute route = request.getRoute(); + final URIAuthority authority = request.getAuthority(); + if (authority != null) { + final String userinfo = authority.getUserInfo(); if (userinfo != null) { final CredentialsProvider credsProvider = context.getCredentialsProvider(); if (credsProvider instanceof CredentialsStore) { @@ -155,25 +100,23 @@ public class ProtocolExec implements ClientExecChain { password = null; } ((CredentialsStore) credsProvider).setCredentials( - new AuthScope(target), + new AuthScope(authority.getHostName(), authority.getPort(), null, AuthSchemes.BASIC), new UsernamePasswordCredentials(userName, password)); } } } // Run request protocol interceptors - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target); context.setAttribute(HttpClientContext.HTTP_ROUTE, route); context.setAttribute(HttpCoreContext.HTTP_REQUEST, request); - this.httpProcessor.process(request, context); + this.httpProcessor.process(request, request.getEntity(), context); - final CloseableHttpResponse response = this.requestExecutor.execute(route, request, - context, execAware); + final ClassicHttpResponse response = this.requestExecutor.execute(request, context, execAware); try { // Run response protocol interceptors context.setAttribute(HttpCoreContext.HTTP_RESPONSE, response); - this.httpProcessor.process(response, context); + this.httpProcessor.process(response, response.getEntity(), context); return response; } catch (final RuntimeException | HttpException | IOException ex) { response.close(); diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/ProxyClient.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/ProxyClient.java index 00c568dee..c01dd0170 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/ProxyClient.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/ProxyClient.java @@ -54,27 +54,26 @@ import org.apache.hc.client5.http.io.ManagedHttpClientConnection; import org.apache.hc.client5.http.protocol.AuthenticationStrategy; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.protocol.RequestClientConnControl; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.ConnectionReuseStrategy; import org.apache.hc.core5.http.HttpEntity; 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.HttpResponse; -import org.apache.hc.core5.http.HttpVersion; import org.apache.hc.core5.http.config.ConnectionConfig; import org.apache.hc.core5.http.config.Lookup; import org.apache.hc.core5.http.config.RegistryBuilder; -import org.apache.hc.core5.http.entity.BufferedHttpEntity; -import org.apache.hc.core5.http.entity.EntityUtils; import org.apache.hc.core5.http.impl.DefaultConnectionReuseStrategy; import org.apache.hc.core5.http.impl.io.HttpRequestExecutor; -import org.apache.hc.core5.http.message.BasicHttpRequest; +import org.apache.hc.core5.http.io.entity.BufferedHttpEntity; +import org.apache.hc.core5.http.io.entity.EntityUtils; +import org.apache.hc.core5.http.message.BasicClassicHttpRequest; import org.apache.hc.core5.http.protocol.BasicHttpContext; +import org.apache.hc.core5.http.protocol.DefaultHttpProcessor; import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.http.protocol.HttpCoreContext; import org.apache.hc.core5.http.protocol.HttpProcessor; -import org.apache.hc.core5.http.protocol.ImmutableHttpProcessor; import org.apache.hc.core5.http.protocol.RequestTargetHost; import org.apache.hc.core5.http.protocol.RequestUserAgent; import org.apache.hc.core5.util.Args; @@ -106,7 +105,7 @@ public class ProxyClient { this.connFactory = connFactory != null ? connFactory : ManagedHttpClientConnectionFactory.INSTANCE; this.connectionConfig = connectionConfig != null ? connectionConfig : ConnectionConfig.DEFAULT; this.requestConfig = requestConfig != null ? requestConfig : RequestConfig.DEFAULT; - this.httpProcessor = new ImmutableHttpProcessor( + this.httpProcessor = new DefaultHttpProcessor( new RequestTargetHost(), new RequestClientConnControl(), new RequestUserAgent()); this.requestExec = new HttpRequestExecutor(); this.proxyAuthStrategy = new DefaultAuthenticationStrategy(); @@ -152,16 +151,14 @@ public class ProxyClient { final ManagedHttpClientConnection conn = this.connFactory.create( route, this.connectionConfig); final HttpContext context = new BasicHttpContext(); - HttpResponse response; + ClassicHttpResponse response; - final HttpRequest connect = new BasicHttpRequest( - "CONNECT", host.toHostString(), HttpVersion.HTTP_1_1); + final ClassicHttpRequest connect = new BasicClassicHttpRequest("CONNECT", host.toHostString()); final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(proxy), credentials); // Populate the execution context - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target); context.setAttribute(HttpCoreContext.HTTP_CONNECTION, conn); context.setAttribute(HttpCoreContext.HTTP_REQUEST, connect); context.setAttribute(HttpClientContext.HTTP_ROUTE, route); @@ -181,10 +178,9 @@ public class ProxyClient { response = this.requestExec.execute(connect, conn, context); - final int status = response.getStatusLine().getStatusCode(); + final int status = response.getCode(); if (status < 200) { - throw new HttpException("Unexpected response to CONNECT request: " + - response.getStatusLine()); + throw new HttpException("Unexpected response to CONNECT request: " + response); } if (this.authenticator.isChallenged(proxy, ChallengeType.PROXY, response, this.proxyAuthExchange, context)) { if (this.authenticator.prepareAuthResponse(proxy, ChallengeType.PROXY, response, @@ -207,7 +203,7 @@ public class ProxyClient { } } - final int status = response.getStatusLine().getStatusCode(); + final int status = response.getCode(); if (status > 299) { @@ -218,8 +214,7 @@ public class ProxyClient { } conn.close(); - throw new TunnelRefusedException("CONNECT refused by proxy: " + - response.getStatusLine(), response); + throw new TunnelRefusedException("CONNECT refused by proxy: " + response, response); } return conn.getSocket(); } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/RedirectExec.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/RedirectExec.java index 73213d769..b64f60e6b 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/RedirectExec.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/RedirectExec.java @@ -29,26 +29,28 @@ package org.apache.hc.client5.http.impl.sync; import java.io.IOException; import java.net.URI; +import java.net.URISyntaxException; import java.util.List; import org.apache.hc.client5.http.HttpRoute; import org.apache.hc.client5.http.auth.AuthExchange; import org.apache.hc.client5.http.auth.AuthScheme; import org.apache.hc.client5.http.config.RequestConfig; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpExecutionAware; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.protocol.RedirectException; import org.apache.hc.client5.http.protocol.RedirectStrategy; import org.apache.hc.client5.http.routing.HttpRoutePlanner; import org.apache.hc.client5.http.utils.URIUtils; -import org.apache.hc.core5.annotation.ThreadSafe; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpHost; -import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.ProtocolException; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.util.Args; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -64,7 +66,7 @@ import org.apache.logging.log4j.Logger; * * @since 4.3 */ -@ThreadSafe +@Contract(threading = ThreadingBehavior.SAFE_CONDITIONAL) public class RedirectExec implements ClientExecChain { private final Logger log = LogManager.getLogger(getClass()); @@ -87,12 +89,10 @@ public class RedirectExec implements ClientExecChain { } @Override - public CloseableHttpResponse execute( - final HttpRoute route, - final HttpRequestWrapper request, + public ClassicHttpResponse execute( + final RoutedHttpRequest request, final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException { - Args.notNull(route, "HTTP route"); Args.notNull(request, "HTTP request"); Args.notNull(context, "HTTP context"); @@ -103,11 +103,10 @@ public class RedirectExec implements ClientExecChain { final RequestConfig config = context.getRequestConfig(); final int maxRedirects = config.getMaxRedirects() > 0 ? config.getMaxRedirects() : 50; - HttpRoute currentRoute = route; - HttpRequestWrapper currentRequest = request; + HttpRoute currentRoute = request.getRoute(); + RoutedHttpRequest currentRequest = request; for (int redirectCount = 0;;) { - final CloseableHttpResponse response = requestExecutor.execute( - currentRoute, currentRequest, context, execAware); + final ClassicHttpResponse response = requestExecutor.execute(currentRequest, context, execAware); try { if (config.isRedirectsEnabled() && this.redirectStrategy.isRedirected(currentRequest.getOriginal(), response, context)) { @@ -117,20 +116,19 @@ public class RedirectExec implements ClientExecChain { } redirectCount++; - final HttpRequest redirect = this.redirectStrategy.getRedirect( + final ClassicHttpRequest redirect = this.redirectStrategy.getRedirect( currentRequest.getOriginal(), response, context); - if (!redirect.headerIterator().hasNext()) { - final HttpRequest original = request.getOriginal(); - redirect.setHeaders(original.getAllHeaders()); + final URI redirectUri; + try { + redirectUri = redirect.getUri(); + } catch (URISyntaxException ex) { + // Should not happen + throw new ProtocolException(ex.getMessage(), ex); } - currentRequest = HttpRequestWrapper.wrap(redirect, currentRequest.getTarget()); - RequestEntityProxy.enhance(currentRequest); - - final URI uri = currentRequest.getURI(); - final HttpHost newTarget = URIUtils.extractHost(uri); + final HttpHost newTarget = URIUtils.extractHost(redirectUri); if (newTarget == null) { throw new ProtocolException("Redirect URI does not specify a valid host name: " + - uri); + redirectUri); } // Reset virtual host and auth states if redirecting to another host @@ -148,10 +146,13 @@ public class RedirectExec implements ClientExecChain { } } - currentRoute = this.routePlanner.determineRoute(newTarget, currentRequest, context); + currentRoute = this.routePlanner.determineRoute(newTarget, redirect, context); if (this.log.isDebugEnabled()) { - this.log.debug("Redirecting to '" + uri + "' via " + currentRoute); + this.log.debug("Redirecting to '" + redirectUri + "' via " + currentRoute); } + currentRequest = RoutedHttpRequest.adapt(redirect, currentRoute); + RequestEntityProxy.enhance(currentRequest); + EntityUtils.consume(response.getEntity()); response.close(); } else { diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/RequestAbortedException.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/RequestAbortedException.java index b29f82b59..4cca93a7b 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/RequestAbortedException.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/RequestAbortedException.java @@ -29,14 +29,11 @@ package org.apache.hc.client5.http.impl.sync; import java.io.InterruptedIOException; -import org.apache.hc.core5.annotation.Immutable; - /** * Signals that the request has been aborted. * * @since 4.3 */ -@Immutable public class RequestAbortedException extends InterruptedIOException { private static final long serialVersionUID = 4973849966012490112L; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/RequestEntityProxy.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/RequestEntityProxy.java index 7d43df7bc..7c0b50390 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/RequestEntityProxy.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/RequestEntityProxy.java @@ -29,22 +29,22 @@ package org.apache.hc.client5.http.impl.sync; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.util.List; import java.util.Set; -import org.apache.hc.core5.annotation.NotThreadSafe; +import org.apache.hc.core5.function.Supplier; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.HttpRequest; -import org.apache.hc.core5.http.TrailerSupplier; /** * A Proxy class for {@link org.apache.hc.core5.http.HttpEntity} enclosed in a request message. * * @since 4.3 */ -@NotThreadSafe class RequestEntityProxy implements HttpEntity { - static void enhance(final HttpRequest request) { + static void enhance(final ClassicHttpRequest request) { final HttpEntity entity = request.getEntity(); if (entity != null && !entity.isRepeatable() && !isEnhanced(entity)) { request.setEntity(new RequestEntityProxy(entity)); @@ -55,7 +55,7 @@ class RequestEntityProxy implements HttpEntity { return entity instanceof RequestEntityProxy; } - static boolean isRepeatable(final HttpRequest request) { + static boolean isRepeatable(final ClassicHttpRequest request) { final HttpEntity entity = request.getEntity(); if (entity != null) { if (isEnhanced(entity)) { @@ -127,7 +127,7 @@ class RequestEntityProxy implements HttpEntity { } @Override - public TrailerSupplier getTrailers() { + public Supplier> getTrailers() { return original.getTrailers(); } @@ -136,6 +136,11 @@ class RequestEntityProxy implements HttpEntity { return original.getTrailerNames(); } + @Override + public void close() throws IOException { + original.close(); + } + @Override public String toString() { final StringBuilder sb = new StringBuilder("RequestEntityProxy{"); diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/ResponseEntityProxy.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/ResponseEntityProxy.java index 27845165d..c4cb714a5 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/ResponseEntityProxy.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/ResponseEntityProxy.java @@ -32,24 +32,22 @@ import java.io.InputStream; import java.io.OutputStream; import java.net.SocketException; -import org.apache.hc.client5.http.io.EofSensorInputStream; -import org.apache.hc.client5.http.io.EofSensorWatcher; -import org.apache.hc.core5.annotation.NotThreadSafe; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.HttpResponse; -import org.apache.hc.core5.http.entity.HttpEntityWrapper; +import org.apache.hc.core5.http.io.EofSensorInputStream; +import org.apache.hc.core5.http.io.EofSensorWatcher; +import org.apache.hc.core5.http.io.entity.HttpEntityWrapper; /** * A wrapper class for {@link HttpEntity} enclosed in a response message. * * @since 4.3 */ -@NotThreadSafe class ResponseEntityProxy extends HttpEntityWrapper implements EofSensorWatcher { private final ConnectionHolder connHolder; - public static void enchance(final HttpResponse response, final ConnectionHolder connHolder) { + public static void enchance(final ClassicHttpResponse response, final ConnectionHolder connHolder) { final HttpEntity entity = response.getEntity(); if (entity != null && entity.isStreaming() && connHolder != null) { response.setEntity(new ResponseEntityProxy(entity, connHolder)); diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/RetryExec.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/RetryExec.java index f66df524d..d5da58860 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/RetryExec.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/RetryExec.java @@ -30,13 +30,14 @@ package org.apache.hc.client5.http.impl.sync; import java.io.IOException; import org.apache.hc.client5.http.HttpRoute; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpExecutionAware; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.protocol.NonRepeatableRequestException; import org.apache.hc.client5.http.sync.HttpRequestRetryHandler; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; +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.NoHttpResponseException; @@ -56,7 +57,7 @@ import org.apache.logging.log4j.Logger; * * @since 4.3 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE_CONDITIONAL) public class RetryExec implements ClientExecChain { private final Logger log = LogManager.getLogger(getClass()); @@ -74,19 +75,18 @@ public class RetryExec implements ClientExecChain { } @Override - public CloseableHttpResponse execute( - final HttpRoute route, - final HttpRequestWrapper request, + public ClassicHttpResponse execute( + final RoutedHttpRequest request, final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException { - Args.notNull(route, "HTTP route"); Args.notNull(request, "HTTP request"); Args.notNull(context, "HTTP context"); final Header[] origheaders = request.getAllHeaders(); for (int execCount = 1;; execCount++) { try { - return this.requestExecutor.execute(route, request, context, execAware); + return this.requestExecutor.execute(request, context, execAware); } catch (final IOException ex) { + final HttpRoute route = request.getRoute(); if (execAware != null && execAware.isAborted()) { this.log.debug("Request has been aborted"); throw ex; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/ServiceUnavailableRetryExec.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/ServiceUnavailableRetryExec.java index 45c694056..c0eca4145 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/ServiceUnavailableRetryExec.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/ServiceUnavailableRetryExec.java @@ -30,13 +30,13 @@ package org.apache.hc.client5.http.impl.sync; import java.io.IOException; import java.io.InterruptedIOException; -import org.apache.hc.client5.http.HttpRoute; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpExecutionAware; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.sync.ServiceUnavailableRetryStrategy; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; +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.util.Args; @@ -55,7 +55,7 @@ import org.apache.logging.log4j.Logger; * * @since 4.3 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE_CONDITIONAL) public class ServiceUnavailableRetryExec implements ClientExecChain { private final Logger log = LogManager.getLogger(getClass()); @@ -74,15 +74,13 @@ public class ServiceUnavailableRetryExec implements ClientExecChain { } @Override - public CloseableHttpResponse execute( - final HttpRoute route, - final HttpRequestWrapper request, + public ClassicHttpResponse execute( + final RoutedHttpRequest request, final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException { final Header[] origheaders = request.getAllHeaders(); for (int c = 1;; c++) { - final CloseableHttpResponse response = this.requestExecutor.execute( - route, request, context, execAware); + final ClassicHttpResponse response = this.requestExecutor.execute(request, context, execAware); try { if (this.retryStrategy.retryRequest(response, c, context)) { response.close(); diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/TunnelRefusedException.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/TunnelRefusedException.java index 3a2b42049..a187f76c4 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/TunnelRefusedException.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/sync/TunnelRefusedException.java @@ -27,28 +27,26 @@ package org.apache.hc.client5.http.impl.sync; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpException; -import org.apache.hc.core5.http.HttpResponse; /** * Signals that the tunnel request was rejected by the proxy host. * * @since 4.0 */ -@Immutable public class TunnelRefusedException extends HttpException { private static final long serialVersionUID = -8646722842745617323L; - private final HttpResponse response; + private final ClassicHttpResponse response; - public TunnelRefusedException(final String message, final HttpResponse response) { + public TunnelRefusedException(final String message, final ClassicHttpResponse response) { super(message); this.response = response; } - public HttpResponse getResponse() { + public ClassicHttpResponse getResponse() { return this.response; } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/io/ConnectionReleaseTrigger.java b/httpclient5/src/main/java/org/apache/hc/client5/http/io/ConnectionReleaseTrigger.java index b5bcf9883..c2df1dbe3 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/io/ConnectionReleaseTrigger.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/io/ConnectionReleaseTrigger.java @@ -30,8 +30,9 @@ import java.io.IOException; /** * Interface for releasing a connection. This can be implemented by various - * "trigger" objects which are associated with a connection, for example - * a {@link EofSensorInputStream} or the {@link ManagedHttpClientConnection} itself. + * "trigger" objects which are associated with a leased connection, for example + * a {@link org.apache.hc.core5.http.io.EofSensorInputStream} + * or the {@link ManagedHttpClientConnection} itself. *

* The methods in this interface can safely be called multiple times. * The first invocation releases the connection, subsequent calls diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/io/EofSensorInputStream.java b/httpclient5/src/main/java/org/apache/hc/client5/http/io/EofSensorInputStream.java deleted file mode 100644 index 66aa1a2cd..000000000 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/io/EofSensorInputStream.java +++ /dev/null @@ -1,295 +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 - * . - * - */ -package org.apache.hc.client5.http.io; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.hc.core5.annotation.NotThreadSafe; -import org.apache.hc.core5.util.Args; - -/** - * A stream wrapper that triggers actions on {@link #close close()} and EOF. - * Primarily used to auto-release an underlying managed connection when the response - * body is consumed or no longer needed. - * - * @see EofSensorWatcher - * - * @since 4.0 - */ -// don't use FilterInputStream as the base class, we'd have to -// override markSupported(), mark(), and reset() to disable them -@NotThreadSafe -public class EofSensorInputStream extends InputStream implements ConnectionReleaseTrigger { - - /** - * The wrapped input stream, while accessible. - * The value changes to {@code null} when the wrapped stream - * becomes inaccessible. - */ - protected InputStream wrappedStream; - - /** - * Indicates whether this stream itself is closed. - * If it isn't, but {@link #wrappedStream wrappedStream} - * is {@code null}, we're running in EOF mode. - * All read operations will indicate EOF without accessing - * the underlying stream. After closing this stream, read - * operations will trigger an {@link IOException IOException}. - * - * @see #isReadAllowed isReadAllowed - */ - private boolean selfClosed; - - /** The watcher to be notified, if any. */ - private final EofSensorWatcher eofWatcher; - - /** - * Creates a new EOF sensor. - * If no watcher is passed, the underlying stream will simply be - * closed when EOF is detected or {@link #close close} is called. - * Otherwise, the watcher decides whether the underlying stream - * should be closed before detaching from it. - * - * @param in the wrapped stream - * @param watcher the watcher for events, or {@code null} for - * auto-close behavior without notification - */ - public EofSensorInputStream(final InputStream in, - final EofSensorWatcher watcher) { - Args.notNull(in, "Wrapped stream"); - wrappedStream = in; - selfClosed = false; - eofWatcher = watcher; - } - - boolean isSelfClosed() { - return selfClosed; - } - - InputStream getWrappedStream() { - return wrappedStream; - } - - /** - * Checks whether the underlying stream can be read from. - * - * @return {@code true} if the underlying stream is accessible, - * {@code false} if this stream is in EOF mode and - * detached from the underlying stream - * - * @throws IOException if this stream is already closed - */ - protected boolean isReadAllowed() throws IOException { - if (selfClosed) { - throw new IOException("Attempted read on closed stream."); - } - return (wrappedStream != null); - } - - @Override - public int read() throws IOException { - int l = -1; - - if (isReadAllowed()) { - try { - l = wrappedStream.read(); - checkEOF(l); - } catch (final IOException ex) { - checkAbort(); - throw ex; - } - } - - return l; - } - - @Override - public int read(final byte[] b, final int off, final int len) throws IOException { - int l = -1; - - if (isReadAllowed()) { - try { - l = wrappedStream.read(b, off, len); - checkEOF(l); - } catch (final IOException ex) { - checkAbort(); - throw ex; - } - } - - return l; - } - - @Override - public int read(final byte[] b) throws IOException { - return read(b, 0, b.length); - } - - @Override - public int available() throws IOException { - int a = 0; // not -1 - - if (isReadAllowed()) { - try { - a = wrappedStream.available(); - // no checkEOF() here, available() can't trigger EOF - } catch (final IOException ex) { - checkAbort(); - throw ex; - } - } - - return a; - } - - @Override - public void close() throws IOException { - // tolerate multiple calls to close() - selfClosed = true; - checkClose(); - } - - /** - * Detects EOF and notifies the watcher. - * This method should only be called while the underlying stream is - * still accessible. Use {@link #isReadAllowed isReadAllowed} to - * check that condition. - *

- * If EOF is detected, the watcher will be notified and this stream - * is detached from the underlying stream. This prevents multiple - * notifications from this stream. - *

- * - * @param eof the result of the calling read operation. - * A negative value indicates that EOF is reached. - * - * @throws IOException - * in case of an IO problem on closing the underlying stream - */ - protected void checkEOF(final int eof) throws IOException { - - final InputStream toCheckStream = wrappedStream; - if ((toCheckStream != null) && (eof < 0)) { - try { - boolean scws = true; // should close wrapped stream? - if (eofWatcher != null) { - scws = eofWatcher.eofDetected(toCheckStream); - } - if (scws) { - toCheckStream.close(); - } - } finally { - wrappedStream = null; - } - } - } - - /** - * Detects stream close and notifies the watcher. - * There's not much to detect since this is called by {@link #close close}. - * The watcher will only be notified if this stream is closed - * for the first time and before EOF has been detected. - * This stream will be detached from the underlying stream to prevent - * multiple notifications to the watcher. - * - * @throws IOException - * in case of an IO problem on closing the underlying stream - */ - protected void checkClose() throws IOException { - - final InputStream toCloseStream = wrappedStream; - if (toCloseStream != null) { - try { - boolean scws = true; // should close wrapped stream? - if (eofWatcher != null) { - scws = eofWatcher.streamClosed(toCloseStream); - } - if (scws) { - toCloseStream.close(); - } - } finally { - wrappedStream = null; - } - } - } - - /** - * Detects stream abort and notifies the watcher. - * There's not much to detect since this is called by - * {@link #abortConnection abortConnection}. - * The watcher will only be notified if this stream is aborted - * for the first time and before EOF has been detected or the - * stream has been {@link #close closed} gracefully. - * This stream will be detached from the underlying stream to prevent - * multiple notifications to the watcher. - * - * @throws IOException - * in case of an IO problem on closing the underlying stream - */ - protected void checkAbort() throws IOException { - - final InputStream toAbortStream = wrappedStream; - if (toAbortStream != null) { - try { - boolean scws = true; // should close wrapped stream? - if (eofWatcher != null) { - scws = eofWatcher.streamAbort(toAbortStream); - } - if (scws) { - toAbortStream.close(); - } - } finally { - wrappedStream = null; - } - } - } - - /** - * Same as {@link #close close()}. - */ - @Override - public void releaseConnection() throws IOException { - close(); - } - - /** - * Aborts this stream. - * This is a special version of {@link #close close()} which prevents - * re-use of the underlying connection, if any. Calling this method - * indicates that there should be no attempt to read until the end of - * the stream. - */ - @Override - public void abortConnection() throws IOException { - // tolerate multiple calls - selfClosed = true; - checkAbort(); - } - -} - diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/io/EofSensorWatcher.java b/httpclient5/src/main/java/org/apache/hc/client5/http/io/EofSensorWatcher.java deleted file mode 100644 index d29099e41..000000000 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/io/EofSensorWatcher.java +++ /dev/null @@ -1,96 +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 - * . - * - */ -package org.apache.hc.client5.http.io; - -import java.io.IOException; -import java.io.InputStream; - -/** - * A watcher for {@link EofSensorInputStream}. Each stream will notify its - * watcher at most once. - * - * @since 4.0 - */ -public interface EofSensorWatcher { - - /** - * Indicates that EOF is detected. - * - * @param wrapped the underlying stream which has reached EOF - * - * @return {@code true} if {@code wrapped} should be closed, - * {@code false} if it should be left alone - * - * @throws IOException - * in case of an IO problem, for example if the watcher itself - * closes the underlying stream. The caller will leave the - * wrapped stream alone, as if {@code false} was returned. - */ - boolean eofDetected(InputStream wrapped) - throws IOException; - - /** - * Indicates that the {@link EofSensorInputStream stream} is closed. - * This method will be called only if EOF was not detected - * before closing. Otherwise, {@link #eofDetected eofDetected} is called. - * - * @param wrapped the underlying stream which has not reached EOF - * - * @return {@code true} if {@code wrapped} should be closed, - * {@code false} if it should be left alone - * - * @throws IOException - * in case of an IO problem, for example if the watcher itself - * closes the underlying stream. The caller will leave the - * wrapped stream alone, as if {@code false} was returned. - */ - boolean streamClosed(InputStream wrapped) - throws IOException; - - /** - * Indicates that the {@link EofSensorInputStream stream} is aborted. - * This method will be called only if EOF was not detected - * before aborting. Otherwise, {@link #eofDetected eofDetected} is called. - *

- * This method will also be invoked when an input operation causes an - * IOException to be thrown to make sure the input stream gets shut down. - *

- * - * @param wrapped the underlying stream which has not reached EOF - * - * @return {@code true} if {@code wrapped} should be closed, - * {@code false} if it should be left alone - * - * @throws IOException - * in case of an IO problem, for example if the watcher itself - * closes the underlying stream. The caller will leave the - * wrapped stream alone, as if {@code false} was returned. - */ - boolean streamAbort(InputStream wrapped) - throws IOException; - -} diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/io/HttpClientConnectionManager.java b/httpclient5/src/main/java/org/apache/hc/client5/http/io/HttpClientConnectionManager.java index ec669f0d9..2f07966c6 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/io/HttpClientConnectionManager.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/io/HttpClientConnectionManager.java @@ -85,7 +85,7 @@ public interface HttpClientConnectionManager { * @param validDuration the duration of time this connection is valid for reuse. * @param timeUnit the time unit. * - * @see #closeExpiredConnections() + * @see #closeExpired() */ void releaseConnection( HttpClientConnection conn, Object newState, long validDuration, TimeUnit timeUnit); @@ -151,9 +151,9 @@ public interface HttpClientConnectionManager { * @param idletime the idle time of connections to be closed * @param tunit the unit for the {@code idletime} * - * @see #closeExpiredConnections() + * @see #closeExpired() */ - void closeIdleConnections(long idletime, TimeUnit tunit); + void closeIdle(long idletime, TimeUnit tunit); /** * Closes all expired connections in the pool. @@ -164,7 +164,7 @@ public interface HttpClientConnectionManager { * Times will be checked with milliseconds precision. *

*/ - void closeExpiredConnections(); + void closeExpired(); /** * Shuts down this connection manager and releases allocated resources. diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/methods/CloseableHttpResponse.java b/httpclient5/src/main/java/org/apache/hc/client5/http/methods/CloseableHttpResponse.java deleted file mode 100644 index 3fb7806b6..000000000 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/methods/CloseableHttpResponse.java +++ /dev/null @@ -1,40 +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 - * . - * - */ - -package org.apache.hc.client5.http.methods; - -import java.io.Closeable; - -import org.apache.hc.core5.http.HttpResponse; - -/** - * Extended version of the {@link HttpResponse} interface that also extends {@link Closeable}. - * - * @since 4.3 - */ -public interface CloseableHttpResponse extends HttpResponse, Closeable { -} diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpDelete.java b/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpDelete.java index a33d2b342..3ed31e7bd 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpDelete.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpDelete.java @@ -29,8 +29,6 @@ package org.apache.hc.client5.http.methods; import java.net.URI; -import org.apache.hc.core5.annotation.NotThreadSafe; - /** * HTTP DELETE method *

@@ -46,33 +44,22 @@ import org.apache.hc.core5.annotation.NotThreadSafe; * * @since 4.0 */ -@NotThreadSafe // HttpRequestBase is @NotThreadSafe -public class HttpDelete extends HttpRequestBase { +public class HttpDelete extends HttpUriRequestBase { private static final long serialVersionUID = 1L; + public final static String METHOD_NAME = "DELETE"; - public HttpDelete() { - super(); - } - public HttpDelete(final URI uri) { - super(); - setURI(uri); + super(METHOD_NAME, uri); } /** * @throws IllegalArgumentException if the uri is invalid. */ public HttpDelete(final String uri) { - super(); - setURI(URI.create(uri)); - } - - @Override - public String getMethod() { - return METHOD_NAME; + this(URI.create(uri)); } } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpGet.java b/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpGet.java index d6fa7887c..9bcc59120 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpGet.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpGet.java @@ -29,8 +29,6 @@ package org.apache.hc.client5.http.methods; import java.net.URI; -import org.apache.hc.core5.annotation.NotThreadSafe; - /** * HTTP GET method. *

@@ -47,32 +45,21 @@ import org.apache.hc.core5.annotation.NotThreadSafe; * * @since 4.0 */ -@NotThreadSafe -public class HttpGet extends HttpRequestBase { +public class HttpGet extends HttpUriRequestBase { private static final long serialVersionUID = 1L; + public final static String METHOD_NAME = "GET"; - public HttpGet() { - super(); - } - public HttpGet(final URI uri) { - super(); - setURI(uri); + super(METHOD_NAME, uri); } /** * @throws IllegalArgumentException if the uri is invalid. */ public HttpGet(final String uri) { - super(); - setURI(URI.create(uri)); - } - - @Override - public String getMethod() { - return METHOD_NAME; + this(URI.create(uri)); } } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpHead.java b/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpHead.java index c9c537650..442d76dd8 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpHead.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpHead.java @@ -29,8 +29,6 @@ package org.apache.hc.client5.http.methods; import java.net.URI; -import org.apache.hc.core5.annotation.NotThreadSafe; - /** * HTTP HEAD method. *

@@ -50,32 +48,21 @@ import org.apache.hc.core5.annotation.NotThreadSafe; * * @since 4.0 */ -@NotThreadSafe -public class HttpHead extends HttpRequestBase { +public class HttpHead extends HttpUriRequestBase { private static final long serialVersionUID = 1L; + public final static String METHOD_NAME = "HEAD"; - public HttpHead() { - super(); - } - public HttpHead(final URI uri) { - super(); - setURI(uri); + super(METHOD_NAME, uri); } /** * @throws IllegalArgumentException if the uri is invalid. */ public HttpHead(final String uri) { - super(); - setURI(URI.create(uri)); - } - - @Override - public String getMethod() { - return METHOD_NAME; + this(URI.create(uri)); } } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpOptions.java b/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpOptions.java index b98d1d61e..71df7a11f 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpOptions.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpOptions.java @@ -32,8 +32,7 @@ import java.util.HashSet; import java.util.Iterator; import java.util.Set; -import org.apache.hc.core5.annotation.NotThreadSafe; -import org.apache.hc.core5.http.Header; +import org.apache.hc.core5.http.message.MessageSupport; import org.apache.hc.core5.http.HeaderElement; import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.util.Args; @@ -55,27 +54,21 @@ import org.apache.hc.core5.util.Args; * * @since 4.0 */ -@NotThreadSafe -public class HttpOptions extends HttpRequestBase { +public class HttpOptions extends HttpUriRequestBase { private static final long serialVersionUID = 1L; + public final static String METHOD_NAME = "OPTIONS"; - public HttpOptions() { - super(); - } - public HttpOptions(final URI uri) { - super(); - setURI(uri); + super(METHOD_NAME, uri); } /** * @throws IllegalArgumentException if the uri is invalid. */ public HttpOptions(final String uri) { - super(); - setURI(URI.create(uri)); + this(URI.create(uri)); } @Override @@ -86,14 +79,11 @@ public class HttpOptions extends HttpRequestBase { public Set getAllowedMethods(final HttpResponse response) { Args.notNull(response, "HTTP response"); - final Iterator

it = response.headerIterator("Allow"); + final Iterator it = MessageSupport.iterate(response, "Allow"); final Set methods = new HashSet<>(); while (it.hasNext()) { - final Header header = it.next(); - final HeaderElement[] elements = header.getElements(); - for (final HeaderElement element : elements) { - methods.add(element.getName()); - } + final HeaderElement element = it.next(); + methods.add(element.getName()); } return methods; } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpPatch.java b/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpPatch.java index 27eb1d763..811b0d84c 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpPatch.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpPatch.java @@ -29,8 +29,6 @@ package org.apache.hc.client5.http.methods; import java.net.URI; -import org.apache.hc.core5.annotation.NotThreadSafe; - /** * HTTP PATCH method. *

@@ -50,29 +48,18 @@ import org.apache.hc.core5.annotation.NotThreadSafe; * * @since 4.2 */ -@NotThreadSafe -public class HttpPatch extends HttpRequestBase { +public class HttpPatch extends HttpUriRequestBase { private static final long serialVersionUID = 1L; + public final static String METHOD_NAME = "PATCH"; - public HttpPatch() { - super(); - } - public HttpPatch(final URI uri) { - super(); - setURI(uri); + super(METHOD_NAME, uri); } public HttpPatch(final String uri) { - super(); - setURI(URI.create(uri)); - } - - @Override - public String getMethod() { - return METHOD_NAME; + this(URI.create(uri)); } } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpPost.java b/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpPost.java index b1f48bf77..c8cd216c1 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpPost.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpPost.java @@ -29,8 +29,6 @@ package org.apache.hc.client5.http.methods; import java.net.URI; -import org.apache.hc.core5.annotation.NotThreadSafe; - /** * HTTP POST method. *

@@ -54,32 +52,21 @@ import org.apache.hc.core5.annotation.NotThreadSafe; * * @since 4.0 */ -@NotThreadSafe -public class HttpPost extends HttpRequestBase { +public class HttpPost extends HttpUriRequestBase { private static final long serialVersionUID = 1L; + public final static String METHOD_NAME = "POST"; - public HttpPost() { - super(); - } - public HttpPost(final URI uri) { - super(); - setURI(uri); + super(METHOD_NAME, uri); } /** * @throws IllegalArgumentException if the uri is invalid. */ public HttpPost(final String uri) { - super(); - setURI(URI.create(uri)); - } - - @Override - public String getMethod() { - return METHOD_NAME; + this(URI.create(uri)); } } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpPut.java b/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpPut.java index de1dd41bf..793a2011a 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpPut.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpPut.java @@ -29,8 +29,6 @@ package org.apache.hc.client5.http.methods; import java.net.URI; -import org.apache.hc.core5.annotation.NotThreadSafe; - /** * HTTP PUT method. *

@@ -46,32 +44,20 @@ import org.apache.hc.core5.annotation.NotThreadSafe; * * @since 4.0 */ -@NotThreadSafe -public class HttpPut extends HttpRequestBase { +public class HttpPut extends HttpUriRequestBase { private static final long serialVersionUID = 1L; public final static String METHOD_NAME = "PUT"; - public HttpPut() { - super(); - } - public HttpPut(final URI uri) { - super(); - setURI(uri); + super(METHOD_NAME, uri); } /** * @throws IllegalArgumentException if the uri is invalid. */ public HttpPut(final String uri) { - super(); - setURI(URI.create(uri)); - } - - @Override - public String getMethod() { - return METHOD_NAME; + this(URI.create(uri)); } } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpRequestBase.java b/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpRequestBase.java deleted file mode 100644 index edd258bbf..000000000 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpRequestBase.java +++ /dev/null @@ -1,129 +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 - * . - * - */ - -package org.apache.hc.client5.http.methods; - -import java.net.URI; - -import org.apache.hc.client5.http.config.RequestConfig; -import org.apache.hc.core5.annotation.NotThreadSafe; -import org.apache.hc.core5.http.HttpVersion; -import org.apache.hc.core5.http.ProtocolVersion; -import org.apache.hc.core5.http.RequestLine; -import org.apache.hc.core5.http.message.BasicRequestLine; - -/** - * Base implementation of {@link HttpUriRequest}. - * - * @since 4.0 - */ -@NotThreadSafe -public abstract class HttpRequestBase extends AbstractExecutionAwareRequest - implements HttpUriRequest, Configurable { - - private static final long serialVersionUID = 1L; - private ProtocolVersion version; - private URI uri; - private RequestConfig config; - - @Override - public abstract String getMethod(); - - /** - * @since 4.3 - */ - public void setProtocolVersion(final ProtocolVersion version) { - this.version = version; - } - - @Override - public ProtocolVersion getProtocolVersion() { - return version != null ? version : HttpVersion.HTTP_1_1; - } - - /** - * Returns the original request URI. - *

- * Please note URI remains unchanged in the course of request execution and - * is not updated if the request is redirected to another location. - */ - @Override - public URI getURI() { - return this.uri; - } - - @Override - public RequestLine getRequestLine() { - final String method = getMethod(); - final ProtocolVersion ver = this.version != null ? this.version : HttpVersion.HTTP_1_1; - final URI uriCopy = getURI(); // avoids possible window where URI could be changed - String uritext = null; - if (uriCopy != null) { - uritext = uriCopy.toASCIIString(); - } - if (uritext == null || uritext.isEmpty()) { - uritext = "/"; - } - return new BasicRequestLine(method, uritext, ver); - } - - - @Override - public RequestConfig getConfig() { - return config; - } - - public void setConfig(final RequestConfig config) { - this.config = config; - } - - public void setURI(final URI uri) { - this.uri = uri; - } - - /** - * @since 4.2 - */ - public void started() { - } - - /** - * A convenience method to simplify migration from HttpClient 3.1 API. This method is - * equivalent to {@link #reset()}. - * - * @since 4.2 - */ - public void releaseConnection() { - reset(); - } - - @Override - public String toString() { - return getMethod() + " " + getURI() + " " + getProtocolVersion(); - } - -} diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpRequestWrapper.java b/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpRequestWrapper.java deleted file mode 100644 index 636c0c68b..000000000 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpRequestWrapper.java +++ /dev/null @@ -1,163 +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 - * . - * - */ - -package org.apache.hc.client5.http.methods; - -import java.net.URI; - -import org.apache.hc.core5.annotation.NotThreadSafe; -import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.HttpHost; -import org.apache.hc.core5.http.HttpRequest; -import org.apache.hc.core5.http.ProtocolVersion; -import org.apache.hc.core5.http.RequestLine; -import org.apache.hc.core5.http.message.AbstractHttpMessage; -import org.apache.hc.core5.http.message.BasicRequestLine; -import org.apache.hc.core5.util.Args; - -/** - * A wrapper class for {@link HttpRequest} that can be used to change properties of the current - * request without modifying the original object. - * - * @since 4.3 - */ -@NotThreadSafe -public class HttpRequestWrapper extends AbstractHttpMessage implements HttpUriRequest { - - private static final long serialVersionUID = 1L; - private final HttpRequest original; - private final HttpHost target; - private final String method; - private RequestLine requestLine; - private ProtocolVersion version; - private URI uri; - private HttpEntity entity; - - private HttpRequestWrapper(final HttpRequest request, final HttpHost target) { - super(); - this.original = Args.notNull(request, "HTTP request"); - this.target = target; - this.version = this.original.getRequestLine().getProtocolVersion(); - this.method = this.original.getRequestLine().getMethod(); - if (request instanceof HttpUriRequest) { - this.uri = ((HttpUriRequest) request).getURI(); - } else { - this.uri = null; - } - setHeaders(request.getAllHeaders()); - this.entity = request.getEntity(); - } - - @Override - public ProtocolVersion getProtocolVersion() { - return this.version != null ? this.version : this.original.getProtocolVersion(); - } - - public void setProtocolVersion(final ProtocolVersion version) { - this.version = version; - this.requestLine = null; - } - - @Override - public URI getURI() { - return this.uri; - } - - public void setURI(final URI uri) { - this.uri = uri; - this.requestLine = null; - } - - @Override - public String getMethod() { - return method; - } - - @Override - public void abort() throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isAborted() { - return false; - } - - @Override - public RequestLine getRequestLine() { - if (this.requestLine == null) { - String requestUri; - if (this.uri != null) { - requestUri = this.uri.toASCIIString(); - } else { - requestUri = this.original.getRequestLine().getUri(); - } - if (requestUri == null || requestUri.isEmpty()) { - requestUri = "/"; - } - this.requestLine = new BasicRequestLine(this.method, requestUri, getProtocolVersion()); - } - return this.requestLine; - } - - @Override - public HttpEntity getEntity() { - return this.entity; - } - - @Override - public void setEntity(final HttpEntity entity) { - this.entity = entity; - } - - public HttpRequest getOriginal() { - return this.original; - } - - /** - * @since 4.4 - */ - public HttpHost getTarget() { - return target; - } - - @Override - public String toString() { - return getRequestLine() + " " + super.toString(); - } - - /** - * Creates a mutable wrapper of the original request. - * - * @param request original request - * @return mutable request wrappering the original one - */ - public static HttpRequestWrapper wrap(final HttpRequest request, final HttpHost target) { - return new HttpRequestWrapper(request, target); - } - -} diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpTrace.java b/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpTrace.java index dc6302516..181eeab14 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpTrace.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpTrace.java @@ -29,8 +29,6 @@ package org.apache.hc.client5.http.methods; import java.net.URI; -import org.apache.hc.core5.annotation.NotThreadSafe; - /** * HTTP TRACE method. *

@@ -49,32 +47,21 @@ import org.apache.hc.core5.annotation.NotThreadSafe; * * @since 4.0 */ -@NotThreadSafe -public class HttpTrace extends HttpRequestBase { +public class HttpTrace extends HttpUriRequestBase { private static final long serialVersionUID = 1L; + public final static String METHOD_NAME = "TRACE"; - public HttpTrace() { - super(); - } - public HttpTrace(final URI uri) { - super(); - setURI(uri); + super(METHOD_NAME, uri); } /** * @throws IllegalArgumentException if the uri is invalid. */ public HttpTrace(final String uri) { - super(); - setURI(URI.create(uri)); - } - - @Override - public String getMethod() { - return METHOD_NAME; + this(URI.create(uri)); } } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpUriRequest.java b/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpUriRequest.java index ed64ccc3a..01c39be16 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpUriRequest.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpUriRequest.java @@ -27,44 +27,16 @@ package org.apache.hc.client5.http.methods; -import java.net.URI; - -import org.apache.hc.core5.http.HttpRequest; +import org.apache.hc.core5.http.ClassicHttpRequest; /** - * Extended version of the {@link HttpRequest} interface that provides + * Extended version of the {@link ClassicHttpRequest} interface that provides * convenience methods to access request properties such as request URI * and method type. * * @since 4.0 */ -public interface HttpUriRequest extends HttpRequest { - - /** - * Returns the HTTP method this request uses, such as {@code GET}, - * {@code PUT}, {@code POST}, or other. - */ - String getMethod(); - - /** - * Returns the URI this request uses, such as - * {@code http://example.org/path/to/file}. - *

- * Note that the URI may be absolute URI (as above) or may be a relative URI. - *

- *

- * Implementations are encouraged to return - * the URI that was initially requested. - *

- *

- * To find the final URI after any redirects have been processed, - * please see the section entitled - * HTTP execution context - * in the - * HttpClient Tutorial - *

- */ - URI getURI(); +public interface HttpUriRequest extends ClassicHttpRequest { /** * Aborts execution of the request. diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/methods/AbstractExecutionAwareRequest.java b/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpUriRequestBase.java similarity index 75% rename from httpclient5/src/main/java/org/apache/hc/client5/http/methods/AbstractExecutionAwareRequest.java rename to httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpUriRequestBase.java index ae9eea8d4..c6542f94f 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/methods/AbstractExecutionAwareRequest.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/methods/HttpUriRequestBase.java @@ -26,25 +26,30 @@ */ package org.apache.hc.client5.http.methods; +import java.net.URI; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.core5.concurrent.Cancellable; -import org.apache.hc.core5.http.HttpRequest; -import org.apache.hc.core5.http.message.AbstractHttpMessage; +import org.apache.hc.core5.http.message.BasicClassicHttpRequest; -public abstract class AbstractExecutionAwareRequest extends AbstractHttpMessage implements HttpExecutionAware, HttpRequest { +public class HttpUriRequestBase extends BasicClassicHttpRequest + implements HttpUriRequest, HttpExecutionAware, Configurable { private static final long serialVersionUID = 1L; + + private RequestConfig requestConfig; private final AtomicBoolean aborted; private final AtomicReference cancellableRef; - protected AbstractExecutionAwareRequest() { - super(); + public HttpUriRequestBase(final String method, final URI requestUri) { + super(method, requestUri); this.aborted = new AtomicBoolean(false); this.cancellableRef = new AtomicReference<>(null); } + @Override public void abort() { if (this.aborted.compareAndSet(false, true)) { final Cancellable cancellable = this.cancellableRef.getAndSet(null); @@ -69,13 +74,6 @@ public abstract class AbstractExecutionAwareRequest extends AbstractHttpMessage } } - /** - * @since 4.2 - */ - public void completed() { - this.cancellableRef.set(null); - } - /** * Resets internal state of the request making it reusable. * @@ -89,4 +87,20 @@ public abstract class AbstractExecutionAwareRequest extends AbstractHttpMessage this.aborted.set(false); } + public void setConfig(final RequestConfig requestConfig) { + this.requestConfig = requestConfig; + } + + @Override + public RequestConfig getConfig() { + return requestConfig; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder(); + sb.append(getMethod()).append(" ").append(getRequestUri()); + return sb.toString(); + } + } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/methods/RequestBuilder.java b/httpclient5/src/main/java/org/apache/hc/client5/http/methods/RequestBuilder.java index 96600e945..a35eaafc5 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/methods/RequestBuilder.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/methods/RequestBuilder.java @@ -39,19 +39,18 @@ import java.util.List; import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.entity.UrlEncodedFormEntity; -import org.apache.hc.client5.http.utils.URIBuilder; -import org.apache.hc.client5.http.utils.URLEncodedUtils; -import org.apache.hc.core5.annotation.NotThreadSafe; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.HttpVersion; import org.apache.hc.core5.http.NameValuePair; import org.apache.hc.core5.http.ProtocolVersion; -import org.apache.hc.core5.http.entity.ContentType; +import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.http.message.BasicHeader; import org.apache.hc.core5.http.message.BasicNameValuePair; import org.apache.hc.core5.http.message.HeaderGroup; +import org.apache.hc.core5.net.URIBuilder; import org.apache.hc.core5.util.Args; /** @@ -66,7 +65,6 @@ import org.apache.hc.core5.util.Args; * * @since 4.3 */ -@NotThreadSafe public class RequestBuilder { private String method; @@ -252,17 +250,17 @@ public class RequestBuilder { return new RequestBuilder(HttpOptions.METHOD_NAME, uri); } - public static RequestBuilder copy(final HttpRequest request) { + public static RequestBuilder copy(final ClassicHttpRequest request) { Args.notNull(request, "HTTP request"); return new RequestBuilder().doCopy(request); } - private RequestBuilder doCopy(final HttpRequest request) { + private RequestBuilder doCopy(final ClassicHttpRequest request) { if (request == null) { return this; } - method = request.getRequestLine().getMethod(); - version = request.getRequestLine().getProtocolVersion(); + method = request.getMethod(); + version = request.getVersion(); if (headergroup == null) { headergroup = new HeaderGroup(); @@ -274,11 +272,11 @@ public class RequestBuilder { entity = null; final HttpEntity originalEntity = request.getEntity(); - final ContentType contentType = ContentType.get(originalEntity); + final ContentType contentType = EntityUtils.getContentType(originalEntity); if (contentType != null && contentType.getMimeType().equals(ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) { try { - final List formParams = URLEncodedUtils.parse(originalEntity); + final List formParams = EntityUtils.parse(originalEntity); if (!formParams.isEmpty()) { parameters = formParams; } @@ -288,13 +286,10 @@ public class RequestBuilder { entity = originalEntity; } - final URI originalUri; - if (request instanceof HttpUriRequest) { - uri = ((HttpUriRequest) request).getURI(); - } else { - uri = URI.create(request.getRequestLine().getUri()); + try { + uri = request.getUri(); + } catch (URISyntaxException ignore) { } - if (request instanceof Configurable) { config = ((Configurable) request).getConfig(); } else { @@ -454,7 +449,6 @@ public class RequestBuilder { } public HttpUriRequest build() { - final HttpRequestBase result; URI uriNotNull = this.uri != null ? this.uri : URI.create("/"); HttpEntity entityCopy = this.entity; if (parameters != null && !parameters.isEmpty()) { @@ -472,9 +466,8 @@ public class RequestBuilder { } } } - result = new InternalRequest(method); - result.setProtocolVersion(this.version != null ? this.version : HttpVersion.HTTP_1_1); - result.setURI(uriNotNull); + final HttpUriRequestBase result = new HttpUriRequestBase(method, uriNotNull); + result.setVersion(this.version != null ? this.version : HttpVersion.HTTP_1_1); if (this.headergroup != null) { result.setHeaders(this.headergroup.getAllHeaders()); } @@ -483,21 +476,4 @@ public class RequestBuilder { return result; } - static class InternalRequest extends HttpRequestBase { - - private static final long serialVersionUID = 1L; - private final String method; - - InternalRequest(final String method) { - super(); - this.method = method; - } - - @Override - public String getMethod() { - return this.method; - } - - } - } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/methods/RoutedHttpRequest.java b/httpclient5/src/main/java/org/apache/hc/client5/http/methods/RoutedHttpRequest.java new file mode 100644 index 000000000..9cdf5ac6b --- /dev/null +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/methods/RoutedHttpRequest.java @@ -0,0 +1,192 @@ +/* + * ==================================================================== + * 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 + * . + * + */ + +package org.apache.hc.client5.http.methods; + +import java.net.URI; +import java.net.URISyntaxException; + +import org.apache.hc.client5.http.HttpRoute; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.HttpEntity; +import org.apache.hc.core5.http.HttpHost; +import org.apache.hc.core5.http.HttpVersion; +import org.apache.hc.core5.http.ProtocolVersion; +import org.apache.hc.core5.http.message.BasicHeader; +import org.apache.hc.core5.http.message.HeaderGroup; +import org.apache.hc.core5.net.URIAuthority; +import org.apache.hc.core5.util.Args; + +/** + * A wrapper class for {@link ClassicHttpRequest} that can be used to change properties of the current + * request without modifying the original object. + * + * @since 4.3 + */ +public class RoutedHttpRequest extends HeaderGroup implements ClassicHttpRequest { + + private static final long serialVersionUID = 1L; + + private final ClassicHttpRequest original; + private final HttpRoute route; + private final String method; + + private ProtocolVersion version; + private String scheme; + private URIAuthority authority; + private String path; + private HttpEntity entity; + private URI uri; + + private RoutedHttpRequest(final ClassicHttpRequest request, final HttpRoute route) { + super(); + this.original = Args.notNull(request, "HTTP request"); + this.route = Args.notNull(route, "HTTP route"); + this.method = request.getMethod(); + this.scheme = request.getScheme(); + this.authority = request.getAuthority(); + this.path = request.getPath(); + this.version = request.getVersion() != null ? request.getVersion() : HttpVersion.DEFAULT; + setHeaders(request.getAllHeaders()); + setEntity(request.getEntity()); + } + + public ClassicHttpRequest getOriginal() { + return this.original; + } + + public HttpRoute getRoute() { + return this.route; + } + + @Override + public String getMethod() { + return method; + } + + @Override + public void setVersion(final ProtocolVersion version) { + this.version = version; + } + + @Override + public ProtocolVersion getVersion() { + return version; + } + + @Override + public String getScheme() { + return scheme; + } + + @Override + public void setScheme(final String scheme) { + this.scheme = scheme; + this.uri = null; + } + + @Override + public URIAuthority getAuthority() { + return authority; + } + + @Override + public void setAuthority(final URIAuthority authority) { + this.authority = authority; + this.uri = null; + } + + @Override + public String getPath() { + return path; + } + + @Override + public void setPath(final String path) { + this.path = path; + this.uri = null; + } + + @Override + public void addHeader(final String name, final Object value) { + addHeader(new BasicHeader(name, value)); + } + + @Override + public void setHeader(final String name, final Object value) { + setHeader(new BasicHeader(name, value)); + } + + @Override + public HttpEntity getEntity() { + return entity; + } + + @Override + public void setEntity(final HttpEntity entity) { + this.entity = entity; + } + + private String getRequestUriString() { + final StringBuilder buf = new StringBuilder(); + if (this.authority != null) { + buf.append(this.scheme != null ? this.scheme : "http").append("://"); + buf.append(this.authority.getHostName()); + if (this.authority.getPort() >= 0) { + buf.append(":").append(this.authority.getPort()); + } + } + buf.append(this.path != null ? this.path : "/"); + return buf.toString(); + } + + @Override + public String getRequestUri() { + if (route.getProxyHost() != null && !route.isTunnelled()) { + return getRequestUriString(); + } else { + return this.path; + } + } + + @Override + public URI getUri() throws URISyntaxException { + if (this.uri == null) { + this.uri = new URI(getRequestUriString()); + } + return this.uri; + } + + public HttpHost getTargetHost() { + return this.authority != null ? new HttpHost(this.authority, this.scheme) : this.route.getTargetHost(); + } + + public static RoutedHttpRequest adapt(final ClassicHttpRequest request, final HttpRoute route) { + return new RoutedHttpRequest(request, route); + } + +} diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/CircularRedirectException.java b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/CircularRedirectException.java index 56f0b8c3a..e864a8192 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/CircularRedirectException.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/CircularRedirectException.java @@ -26,15 +26,12 @@ */ package org.apache.hc.client5.http.protocol; -import org.apache.hc.core5.annotation.Immutable; - /** * Signals a circular redirect * * * @since 4.0 */ -@Immutable public class CircularRedirectException extends RedirectException { private static final long serialVersionUID = 6830063487001091803L; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/ClientProtocolException.java b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/ClientProtocolException.java index 047bf723e..860c3df72 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/ClientProtocolException.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/ClientProtocolException.java @@ -28,14 +28,11 @@ package org.apache.hc.client5.http.protocol; import java.io.IOException; -import org.apache.hc.core5.annotation.Immutable; - /** * Signals an error in the HTTP protocol. * * @since 4.0 */ -@Immutable public class ClientProtocolException extends IOException { private static final long serialVersionUID = -5596590843227115865L; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/HttpClientContext.java b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/HttpClientContext.java index 4381f5031..e717a9048 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/HttpClientContext.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/HttpClientContext.java @@ -44,12 +44,12 @@ import org.apache.hc.client5.http.cookie.CookieOrigin; import org.apache.hc.client5.http.cookie.CookieSpec; import org.apache.hc.client5.http.cookie.CookieSpecProvider; import org.apache.hc.client5.http.cookie.CookieStore; -import org.apache.hc.core5.annotation.NotThreadSafe; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.config.Lookup; import org.apache.hc.core5.http.protocol.BasicHttpContext; import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.http.protocol.HttpCoreContext; +import org.apache.hc.core5.util.Args; /** * Adaptor class that provides convenience type safe setters and getters @@ -58,7 +58,6 @@ import org.apache.hc.core5.http.protocol.HttpCoreContext; * * @since 4.3 */ -@NotThreadSafe public class HttpClientContext extends HttpCoreContext { /** @@ -134,11 +133,11 @@ public class HttpClientContext extends HttpCoreContext { public static final String REQUEST_CONFIG = "http.request-config"; public static HttpClientContext adapt(final HttpContext context) { + Args.notNull(context, "HTTP context"); if (context instanceof HttpClientContext) { return (HttpClientContext) context; - } else { - return new HttpClientContext(context); } + return new HttpClientContext(context); } public static HttpClientContext create() { diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/HttpResponseException.java b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/HttpResponseException.java index 4aa655776..831fb29a6 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/HttpResponseException.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/HttpResponseException.java @@ -26,14 +26,11 @@ */ package org.apache.hc.client5.http.protocol; -import org.apache.hc.core5.annotation.Immutable; - /** * Signals a non 2xx HTTP response. * * @since 4.0 */ -@Immutable public class HttpResponseException extends ClientProtocolException { private static final long serialVersionUID = -7186627969477257933L; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/NonRepeatableRequestException.java b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/NonRepeatableRequestException.java index 9bcddd0a8..7f8fc073b 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/NonRepeatableRequestException.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/NonRepeatableRequestException.java @@ -26,7 +26,6 @@ */ package org.apache.hc.client5.http.protocol; -import org.apache.hc.core5.annotation.Immutable; import org.apache.hc.core5.http.ProtocolException; /** @@ -36,7 +35,6 @@ import org.apache.hc.core5.http.ProtocolException; * * @since 4.0 */ -@Immutable public class NonRepeatableRequestException extends ProtocolException { private static final long serialVersionUID = 82685265288806048L; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RedirectException.java b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RedirectException.java index 16462eb81..8151b940d 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RedirectException.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RedirectException.java @@ -26,7 +26,6 @@ */ package org.apache.hc.client5.http.protocol; -import org.apache.hc.core5.annotation.Immutable; import org.apache.hc.core5.http.ProtocolException; /** @@ -35,7 +34,6 @@ import org.apache.hc.core5.http.ProtocolException; * * @since 4.0 */ -@Immutable public class RedirectException extends ProtocolException { private static final long serialVersionUID = 4418824536372559326L; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RedirectLocations.java b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RedirectLocations.java index 13a80039e..effcbee70 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RedirectLocations.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RedirectLocations.java @@ -35,15 +35,12 @@ import java.util.Iterator; import java.util.List; import java.util.Set; -import org.apache.hc.core5.annotation.NotThreadSafe; - /** * This class represents a collection of {@link java.net.URI}s used * as redirect locations. * * @since 4.0 */ -@NotThreadSafe // HashSet/ArrayList are not synch. public class RedirectLocations extends AbstractList { private final Set unique; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RedirectStrategy.java b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RedirectStrategy.java index ce84e7f03..283612eff 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RedirectStrategy.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RedirectStrategy.java @@ -28,6 +28,7 @@ package org.apache.hc.client5.http.protocol; import org.apache.hc.client5.http.methods.HttpUriRequest; +import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.HttpResponse; @@ -74,7 +75,7 @@ public interface RedirectStrategy { * @return redirected request */ HttpUriRequest getRedirect( - HttpRequest request, + ClassicHttpRequest request, HttpResponse response, HttpContext context) throws HttpException; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RequestAcceptEncoding.java b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RequestAcceptEncoding.java index a51478251..d40d1a97f 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RequestAcceptEncoding.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RequestAcceptEncoding.java @@ -26,12 +26,12 @@ */ package org.apache.hc.client5.http.protocol; -import java.io.IOException; import java.util.List; import org.apache.hc.client5.http.config.RequestConfig; -import org.apache.hc.core5.annotation.Immutable; -import org.apache.hc.core5.http.HttpException; +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.HttpRequest; import org.apache.hc.core5.http.HttpRequestInterceptor; import org.apache.hc.core5.http.protocol.HttpContext; @@ -45,7 +45,7 @@ import org.apache.hc.core5.http.protocol.HttpContext; * * @since 4.1 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class RequestAcceptEncoding implements HttpRequestInterceptor { private final String acceptEncoding; @@ -73,9 +73,7 @@ public class RequestAcceptEncoding implements HttpRequestInterceptor { } @Override - public void process( - final HttpRequest request, - final HttpContext context) throws HttpException, IOException { + public void process(final HttpRequest request, final EntityDetails entity, final HttpContext context) { final HttpClientContext clientContext = HttpClientContext.adapt(context); final RequestConfig requestConfig = clientContext.getRequestConfig(); diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RequestAddCookies.java b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RequestAddCookies.java index 3e46f77f0..857a4729a 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RequestAddCookies.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RequestAddCookies.java @@ -28,8 +28,6 @@ package org.apache.hc.client5.http.protocol; import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -42,15 +40,16 @@ import org.apache.hc.client5.http.cookie.CookieOrigin; import org.apache.hc.client5.http.cookie.CookieSpec; import org.apache.hc.client5.http.cookie.CookieSpecProvider; import org.apache.hc.client5.http.cookie.CookieStore; -import org.apache.hc.client5.http.methods.HttpUriRequest; -import org.apache.hc.core5.annotation.Immutable; +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.Header; import org.apache.hc.core5.http.HttpException; -import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.HttpRequestInterceptor; import org.apache.hc.core5.http.config.Lookup; import org.apache.hc.core5.http.protocol.HttpContext; +import org.apache.hc.core5.net.URIAuthority; import org.apache.hc.core5.util.Args; import org.apache.hc.core5.util.TextUtils; import org.apache.logging.log4j.LogManager; @@ -63,7 +62,7 @@ import org.apache.logging.log4j.Logger; * * @since 4.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class RequestAddCookies implements HttpRequestInterceptor { private final Logger log = LogManager.getLogger(getClass()); @@ -73,12 +72,12 @@ public class RequestAddCookies implements HttpRequestInterceptor { } @Override - public void process(final HttpRequest request, final HttpContext context) + public void process(final HttpRequest request, final EntityDetails entity, final HttpContext context) throws HttpException, IOException { Args.notNull(request, "HTTP request"); Args.notNull(context, "HTTP context"); - final String method = request.getRequestLine().getMethod(); + final String method = request.getMethod(); if (method.equalsIgnoreCase("CONNECT") || method.equalsIgnoreCase("TRACE")) { return; } @@ -99,13 +98,6 @@ public class RequestAddCookies implements HttpRequestInterceptor { return; } - // Obtain the target host, possibly virtual (required) - final HttpHost targetHost = clientContext.getTargetHost(); - if (targetHost == null) { - this.log.debug("Target host not set in the context"); - return; - } - // Obtain the route (required) final RouteInfo route = clientContext.getHttpRoute(); if (route == null) { @@ -122,27 +114,20 @@ public class RequestAddCookies implements HttpRequestInterceptor { this.log.debug("CookieSpec selected: " + policy); } - URI requestURI = null; - if (request instanceof HttpUriRequest) { - requestURI = ((HttpUriRequest) request).getURI(); - } else { - try { - requestURI = new URI(request.getRequestLine().getUri()); - } catch (final URISyntaxException ignore) { - } + final URIAuthority authority = request.getAuthority(); + String path = request.getPath(); + if (TextUtils.isEmpty(path)) { + path = "/"; } - final String path = requestURI != null ? requestURI.getPath() : null; - final String hostName = targetHost.getHostName(); - int port = targetHost.getPort(); + String hostName = authority != null ? authority.getHostName() : null; + if (hostName == null) { + hostName = route.getTargetHost().getHostName(); + } + int port = authority != null ? authority.getPort() : -1; if (port < 0) { port = route.getTargetHost().getPort(); } - - final CookieOrigin cookieOrigin = new CookieOrigin( - hostName, - port >= 0 ? port : 0, - !TextUtils.isEmpty(path) ? path : "/", - route.isSecure()); + final CookieOrigin cookieOrigin = new CookieOrigin(hostName, port, path, route.isSecure()); // Get an instance of the selected cookie policy final CookieSpecProvider provider = registry.lookup(policy); diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RequestAuthCache.java b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RequestAuthCache.java index 4761ded46..6c3e9abf0 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RequestAuthCache.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RequestAuthCache.java @@ -34,12 +34,15 @@ import org.apache.hc.client5.http.auth.AuthCache; import org.apache.hc.client5.http.auth.AuthExchange; import org.apache.hc.client5.http.auth.AuthScheme; import org.apache.hc.client5.http.auth.CredentialsProvider; -import org.apache.hc.core5.annotation.Immutable; +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.HttpHost; import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.HttpRequestInterceptor; import org.apache.hc.core5.http.protocol.HttpContext; +import org.apache.hc.core5.net.URIAuthority; import org.apache.hc.core5.util.Args; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -51,7 +54,7 @@ import org.apache.logging.log4j.Logger; * * @since 4.1 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class RequestAuthCache implements HttpRequestInterceptor { private final Logger log = LogManager.getLogger(getClass()); @@ -61,7 +64,7 @@ public class RequestAuthCache implements HttpRequestInterceptor { } @Override - public void process(final HttpRequest request, final HttpContext context) + public void process(final HttpRequest request, final EntityDetails entity, final HttpContext context) throws HttpException, IOException { Args.notNull(request, "HTTP request"); Args.notNull(context, "HTTP context"); @@ -86,19 +89,16 @@ public class RequestAuthCache implements HttpRequestInterceptor { return; } - HttpHost target = clientContext.getTargetHost(); - if (target == null) { - this.log.debug("Target host not set in the context"); - return; - } - - if (target.getPort() < 0) { + final URIAuthority authority = request.getAuthority(); + final HttpHost target; + if (authority != null) { target = new HttpHost( - target.getHostName(), - route.getTargetHost().getPort(), - target.getSchemeName()); + authority.getHostName(), + authority.getPort() >= 0 ? authority.getPort() : route.getTargetHost().getPort(), + request.getScheme()); + } else { + target = route.getTargetHost(); } - final AuthExchange targetAuthExchange = clientContext.getAuthExchange(target); if (targetAuthExchange.getState() == AuthExchange.State.UNCHALLENGED) { final AuthScheme authScheme = authCache.get(target); diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RequestClientConnControl.java b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RequestClientConnControl.java index d58d86cb3..d027eb0ef 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RequestClientConnControl.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RequestClientConnControl.java @@ -30,7 +30,9 @@ package org.apache.hc.client5.http.protocol; import java.io.IOException; import org.apache.hc.client5.http.RouteInfo; -import org.apache.hc.core5.annotation.Immutable; +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.HeaderElements; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpHeaders; @@ -48,7 +50,7 @@ import org.apache.logging.log4j.Logger; * * @since 4.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class RequestClientConnControl implements HttpRequestInterceptor { private final Logger log = LogManager.getLogger(getClass()); @@ -60,11 +62,11 @@ public class RequestClientConnControl implements HttpRequestInterceptor { } @Override - public void process(final HttpRequest request, final HttpContext context) + public void process(final HttpRequest request, final EntityDetails entity, final HttpContext context) throws HttpException, IOException { Args.notNull(request, "HTTP request"); - final String method = request.getRequestLine().getMethod(); + final String method = request.getMethod(); if (method.equalsIgnoreCase("CONNECT")) { request.setHeader(PROXY_CONN_DIRECTIVE, HeaderElements.KEEP_ALIVE); return; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RequestDefaultHeaders.java b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RequestDefaultHeaders.java index 5bfdda5ed..15ace2e9e 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RequestDefaultHeaders.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RequestDefaultHeaders.java @@ -30,7 +30,9 @@ package org.apache.hc.client5.http.protocol; import java.io.IOException; import java.util.Collection; -import org.apache.hc.core5.annotation.Immutable; +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.Header; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpRequest; @@ -43,7 +45,7 @@ import org.apache.hc.core5.util.Args; * * @since 4.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class RequestDefaultHeaders implements HttpRequestInterceptor { private final Collection defaultHeaders; @@ -61,11 +63,11 @@ public class RequestDefaultHeaders implements HttpRequestInterceptor { } @Override - public void process(final HttpRequest request, final HttpContext context) + public void process(final HttpRequest request, final EntityDetails entity, final HttpContext context) throws HttpException, IOException { Args.notNull(request, "HTTP request"); - final String method = request.getRequestLine().getMethod(); + final String method = request.getMethod(); if (method.equalsIgnoreCase("CONNECT")) { return; } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RequestExpectContinue.java b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RequestExpectContinue.java index 7208b5c84..c06fedb95 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RequestExpectContinue.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/RequestExpectContinue.java @@ -30,9 +30,10 @@ package org.apache.hc.client5.http.protocol; import java.io.IOException; import org.apache.hc.client5.http.config.RequestConfig; -import org.apache.hc.core5.annotation.Immutable; +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.HeaderElements; -import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpHeaders; import org.apache.hc.core5.http.HttpRequest; @@ -52,7 +53,7 @@ import org.apache.hc.core5.util.Args; * * @since 4.3 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class RequestExpectContinue implements HttpRequestInterceptor { public RequestExpectContinue() { @@ -60,16 +61,15 @@ public class RequestExpectContinue implements HttpRequestInterceptor { } @Override - public void process(final HttpRequest request, final HttpContext context) + public void process(final HttpRequest request, final EntityDetails entity, final HttpContext context) throws HttpException, IOException { Args.notNull(request, "HTTP request"); if (!request.containsHeader(HttpHeaders.EXPECT)) { - final ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); - final HttpEntity entity = request.getEntity(); + final ProtocolVersion version = request.getVersion() != null ? request.getVersion() : HttpVersion.HTTP_1_1; // Do not send the expect header if request body is known to be empty if (entity != null - && entity.getContentLength() != 0 && !ver.lessEquals(HttpVersion.HTTP_1_0)) { + && entity.getContentLength() != 0 && !version.lessEquals(HttpVersion.HTTP_1_0)) { final HttpClientContext clientContext = HttpClientContext.adapt(context); final RequestConfig config = clientContext.getRequestConfig(); if (config.isExpectContinueEnabled()) { diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/ResponseContentEncoding.java b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/ResponseContentEncoding.java index 67f773984..831201c24 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/ResponseContentEncoding.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/ResponseContentEncoding.java @@ -32,12 +32,12 @@ import java.util.Locale; import java.util.zip.GZIPInputStream; import org.apache.hc.client5.http.config.RequestConfig; -import org.apache.hc.client5.http.entity.DecompressingEntity; import org.apache.hc.client5.http.entity.DeflateInputStream; import org.apache.hc.client5.http.entity.InputStreamFactory; -import org.apache.hc.core5.annotation.Immutable; +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.HeaderElement; -import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.HttpResponseInterceptor; @@ -56,11 +56,9 @@ import org.apache.hc.core5.http.protocol.HttpContext; * @since 4.1 * */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class ResponseContentEncoding implements HttpResponseInterceptor { - public static final String UNCOMPRESSED = "http.client.response.uncompressed"; - private final static InputStreamFactory GZIP = new InputStreamFactory() { @Override @@ -123,8 +121,8 @@ public class ResponseContentEncoding implements HttpResponseInterceptor { @Override public void process( final HttpResponse response, + final EntityDetails entity, final HttpContext context) throws HttpException, IOException { - final HttpEntity entity = response.getEntity(); final HttpClientContext clientContext = HttpClientContext.adapt(context); final RequestConfig requestConfig = clientContext.getRequestConfig(); @@ -139,10 +137,10 @@ public class ResponseContentEncoding implements HttpResponseInterceptor { final String codecname = codec.getName().toLowerCase(Locale.ROOT); final InputStreamFactory decoderFactory = decoderRegistry.lookup(codecname); if (decoderFactory != null) { - response.setEntity(new DecompressingEntity(response.getEntity(), decoderFactory)); - response.removeHeaders("Content-Length"); - response.removeHeaders("Content-Encoding"); - response.removeHeaders("Content-MD5"); +// response.setEntity(new DecompressingEntity(response.getEntity(), decoderFactory)); +// response.removeHeaders("Content-Length"); +// response.removeHeaders("Content-Encoding"); +// response.removeHeaders("Content-MD5"); } else { if (!"identity".equals(codecname) && !ignoreUnknown) { throw new HttpException("Unsupported Content-Encoding: " + codec.getName()); diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/ResponseProcessCookies.java b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/ResponseProcessCookies.java index 886e83d13..8ec84b81e 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/ResponseProcessCookies.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/protocol/ResponseProcessCookies.java @@ -36,7 +36,9 @@ import org.apache.hc.client5.http.cookie.CookieOrigin; import org.apache.hc.client5.http.cookie.CookieSpec; import org.apache.hc.client5.http.cookie.CookieStore; import org.apache.hc.client5.http.cookie.MalformedCookieException; -import org.apache.hc.core5.annotation.Immutable; +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.Header; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpResponse; @@ -52,7 +54,7 @@ import org.apache.logging.log4j.Logger; * * @since 4.0 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class ResponseProcessCookies implements HttpResponseInterceptor { private final Logger log = LogManager.getLogger(getClass()); @@ -62,7 +64,7 @@ public class ResponseProcessCookies implements HttpResponseInterceptor { } @Override - public void process(final HttpResponse response, final HttpContext context) + public void process(final HttpResponse response, final EntityDetails entity, final HttpContext context) throws HttpException, IOException { Args.notNull(response, "HTTP request"); Args.notNull(context, "HTTP context"); diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/psl/PublicSuffixList.java b/httpclient5/src/main/java/org/apache/hc/client5/http/psl/PublicSuffixList.java index 9637a7c94..eabf67ff4 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/psl/PublicSuffixList.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/psl/PublicSuffixList.java @@ -29,7 +29,8 @@ package org.apache.hc.client5.http.psl; import java.util.Collections; import java.util.List; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.util.Args; /** @@ -41,7 +42,7 @@ import org.apache.hc.core5.util.Args; * * @since 4.4 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public final class PublicSuffixList { private final DomainType type; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/psl/PublicSuffixListParser.java b/httpclient5/src/main/java/org/apache/hc/client5/http/psl/PublicSuffixListParser.java index d216a09c2..730791a3d 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/psl/PublicSuffixListParser.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/psl/PublicSuffixListParser.java @@ -32,7 +32,8 @@ import java.io.Reader; import java.util.ArrayList; import java.util.List; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; /** * Parses the list from publicsuffix.org @@ -40,7 +41,7 @@ import org.apache.hc.core5.annotation.Immutable; * * @since 4.4 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public final class PublicSuffixListParser { public PublicSuffixListParser() { diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/psl/PublicSuffixMatcher.java b/httpclient5/src/main/java/org/apache/hc/client5/http/psl/PublicSuffixMatcher.java index 982845fb6..5c4c6a1d1 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/psl/PublicSuffixMatcher.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/psl/PublicSuffixMatcher.java @@ -33,7 +33,8 @@ import java.util.Locale; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import org.apache.hc.core5.annotation.ThreadSafe; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.util.Args; /** @@ -46,7 +47,7 @@ import org.apache.hc.core5.util.Args; * * @since 4.4 */ -@ThreadSafe +@Contract(threading = ThreadingBehavior.SAFE) public final class PublicSuffixMatcher { private final Map rules; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/psl/PublicSuffixMatcherLoader.java b/httpclient5/src/main/java/org/apache/hc/client5/http/psl/PublicSuffixMatcherLoader.java index 06ff93774..af1adcb11 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/psl/PublicSuffixMatcherLoader.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/psl/PublicSuffixMatcherLoader.java @@ -36,7 +36,8 @@ import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.List; -import org.apache.hc.core5.annotation.ThreadSafe; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.util.Args; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -46,7 +47,7 @@ import org.apache.logging.log4j.Logger; * * @since 4.4 */ -@ThreadSafe +@Contract(threading = ThreadingBehavior.SAFE) public final class PublicSuffixMatcherLoader { private static PublicSuffixMatcher load(final InputStream in) throws IOException { diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/socket/PlainConnectionSocketFactory.java b/httpclient5/src/main/java/org/apache/hc/client5/http/socket/PlainConnectionSocketFactory.java index eb5c9cb14..f723fe376 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/socket/PlainConnectionSocketFactory.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/socket/PlainConnectionSocketFactory.java @@ -31,7 +31,8 @@ import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.protocol.HttpContext; @@ -40,7 +41,7 @@ import org.apache.hc.core5.http.protocol.HttpContext; * * @since 4.3 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class PlainConnectionSocketFactory implements ConnectionSocketFactory { public static final PlainConnectionSocketFactory INSTANCE = new PlainConnectionSocketFactory(); diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/ssl/DefaultHostnameVerifier.java b/httpclient5/src/main/java/org/apache/hc/client5/http/ssl/DefaultHostnameVerifier.java index bb41f3cb6..86e6bf40d 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/ssl/DefaultHostnameVerifier.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/ssl/DefaultHostnameVerifier.java @@ -51,8 +51,9 @@ import javax.security.auth.x500.X500Principal; import org.apache.hc.client5.http.psl.DomainType; import org.apache.hc.client5.http.psl.PublicSuffixMatcher; -import org.apache.hc.client5.http.utils.InetAddressUtils; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; +import org.apache.hc.core5.net.InetAddressUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -61,7 +62,7 @@ import org.apache.logging.log4j.Logger; * * @since 4.4 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE_CONDITIONAL) public final class DefaultHostnameVerifier implements HostnameVerifier { enum TYPE { IPv4, IPv6, DNS } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/ssl/NoopHostnameVerifier.java b/httpclient5/src/main/java/org/apache/hc/client5/http/ssl/NoopHostnameVerifier.java index 6516c15be..abcd1c588 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/ssl/NoopHostnameVerifier.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/ssl/NoopHostnameVerifier.java @@ -30,7 +30,8 @@ package org.apache.hc.client5.http.ssl; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSession; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; /** * The NO_OP HostnameVerifier essentially turns hostname verification @@ -38,7 +39,7 @@ import org.apache.hc.core5.annotation.Immutable; * * @since 4.4 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public class NoopHostnameVerifier implements HostnameVerifier { public static final NoopHostnameVerifier INSTANCE = new NoopHostnameVerifier(); diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/ssl/SSLConnectionSocketFactory.java b/httpclient5/src/main/java/org/apache/hc/client5/http/ssl/SSLConnectionSocketFactory.java index ffa67ed8a..4b038147f 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/ssl/SSLConnectionSocketFactory.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/ssl/SSLConnectionSocketFactory.java @@ -49,7 +49,8 @@ import javax.security.auth.x500.X500Principal; import org.apache.hc.client5.http.psl.PublicSuffixMatcherLoader; import org.apache.hc.client5.http.socket.LayeredConnectionSocketFactory; -import org.apache.hc.core5.annotation.ThreadSafe; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.ssl.SSLContexts; @@ -133,7 +134,7 @@ import org.apache.logging.log4j.Logger; * * @since 4.3 */ -@ThreadSafe +@Contract(threading = ThreadingBehavior.SAFE) public class SSLConnectionSocketFactory implements LayeredConnectionSocketFactory { public static final String TLS = "TLS"; diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/sync/HttpClient.java b/httpclient5/src/main/java/org/apache/hc/client5/http/sync/HttpClient.java index c9b8f35cc..26fb3b119 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/sync/HttpClient.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/sync/HttpClient.java @@ -29,10 +29,11 @@ package org.apache.hc.client5.http.sync; import java.io.IOException; -import org.apache.hc.client5.http.methods.HttpUriRequest; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpHost; -import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.HttpResponse; +import org.apache.hc.core5.http.io.ResponseHandler; import org.apache.hc.core5.http.protocol.HttpContext; /** @@ -57,8 +58,7 @@ public interface HttpClient { * configuration of this client. * @throws IOException in case of a problem or the connection was aborted */ - HttpResponse execute(HttpUriRequest request) - throws IOException; + HttpResponse execute(ClassicHttpRequest request) throws IOException; /** * Executes HTTP request using the given context. @@ -74,8 +74,7 @@ public interface HttpClient { * configuration of this client. * @throws IOException in case of a problem or the connection was aborted */ - HttpResponse execute(HttpUriRequest request, HttpContext context) - throws IOException; + HttpResponse execute(ClassicHttpRequest request, HttpContext context) throws IOException; /** * Executes HTTP request using the default context. @@ -93,8 +92,7 @@ public interface HttpClient { * configuration of this client. * @throws IOException in case of a problem or the connection was aborted */ - HttpResponse execute(HttpHost target, HttpRequest request) - throws IOException; + ClassicHttpResponse execute(HttpHost target, ClassicHttpRequest request) throws IOException; /** * Executes HTTP request using the given context. @@ -114,9 +112,7 @@ public interface HttpClient { * configuration of this client. * @throws IOException in case of a problem or the connection was aborted */ - HttpResponse execute(HttpHost target, HttpRequest request, - HttpContext context) - throws IOException; + HttpResponse execute(HttpHost target, ClassicHttpRequest request, HttpContext context) throws IOException; /** * Executes HTTP request using the default context and processes the @@ -135,10 +131,7 @@ public interface HttpClient { * @return the response object as generated by the response handler. * @throws IOException in case of a problem or the connection was aborted */ - T execute( - HttpUriRequest request, - ResponseHandler responseHandler) - throws IOException; + T execute(ClassicHttpRequest request, ResponseHandler responseHandler) throws IOException; /** * Executes HTTP request using the given context and processes the @@ -159,11 +152,7 @@ public interface HttpClient { * @return the response object as generated by the response handler. * @throws IOException in case of a problem or the connection was aborted */ - T execute( - HttpUriRequest request, - ResponseHandler responseHandler, - HttpContext context) - throws IOException; + T execute(ClassicHttpRequest request, ResponseHandler responseHandler, HttpContext context) throws IOException; /** * Executes HTTP request to the target using the default context and @@ -186,11 +175,7 @@ public interface HttpClient { * @return the response object as generated by the response handler. * @throws IOException in case of a problem or the connection was aborted */ - T execute( - HttpHost target, - HttpRequest request, - ResponseHandler responseHandler) - throws IOException; + T execute(HttpHost target, ClassicHttpRequest request, ResponseHandler responseHandler) throws IOException; /** * Executes HTTP request to the target using the given context and @@ -217,9 +202,8 @@ public interface HttpClient { */ T execute( HttpHost target, - HttpRequest request, + ClassicHttpRequest request, ResponseHandler responseHandler, - HttpContext context) - throws IOException; + HttpContext context) throws IOException; } diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/utils/DateUtils.java b/httpclient5/src/main/java/org/apache/hc/client5/http/utils/DateUtils.java index f99f498e2..a9a7ab2bf 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/utils/DateUtils.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/utils/DateUtils.java @@ -37,7 +37,8 @@ import java.util.Locale; import java.util.Map; import java.util.TimeZone; -import org.apache.hc.core5.annotation.Immutable; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; import org.apache.hc.core5.util.Args; /** @@ -47,7 +48,7 @@ import org.apache.hc.core5.util.Args; * * @since 4.3 */ -@Immutable +@Contract(threading = ThreadingBehavior.IMMUTABLE) public final class DateUtils { /** diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/utils/InetAddressUtils.java b/httpclient5/src/main/java/org/apache/hc/client5/http/utils/InetAddressUtils.java deleted file mode 100644 index 8f64f3844..000000000 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/utils/InetAddressUtils.java +++ /dev/null @@ -1,124 +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 - * . - * - */ - -package org.apache.hc.client5.http.utils; - -import java.util.regex.Pattern; - -import org.apache.hc.core5.annotation.Immutable; - -/** - * A collection of utilities relating to InetAddresses. - * - * @since 4.0 - */ -@Immutable -public class InetAddressUtils { - - private InetAddressUtils() { - } - - private static final String IPV4_BASIC_PATTERN_STRING = - "(([1-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){1}" + // initial first field, 1-255 - "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){2}" + // following 2 fields, 0-255 followed by . - "([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])"; // final field, 0-255 - - private static final Pattern IPV4_PATTERN = - Pattern.compile("^" + IPV4_BASIC_PATTERN_STRING + "$"); - - private static final Pattern IPV4_MAPPED_IPV6_PATTERN = // TODO does not allow for redundant leading zeros - Pattern.compile("^::[fF]{4}:" + IPV4_BASIC_PATTERN_STRING + "$"); - - private static final Pattern IPV6_STD_PATTERN = - Pattern.compile( - "^[0-9a-fA-F]{1,4}(:[0-9a-fA-F]{1,4}){7}$"); - - private static final Pattern IPV6_HEX_COMPRESSED_PATTERN = - Pattern.compile( - "^(([0-9A-Fa-f]{1,4}(:[0-9A-Fa-f]{1,4}){0,5})?)" + // 0-6 hex fields - "::" + - "(([0-9A-Fa-f]{1,4}(:[0-9A-Fa-f]{1,4}){0,5})?)$"); // 0-6 hex fields - - /* - * The above pattern is not totally rigorous as it allows for more than 7 hex fields in total - */ - private static final char COLON_CHAR = ':'; - - // Must not have more than 7 colons (i.e. 8 fields) - private static final int MAX_COLON_COUNT = 7; - - /** - * Checks whether the parameter is a valid IPv4 address - * - * @param input the address string to check for validity - * @return true if the input parameter is a valid IPv4 address - */ - public static boolean isIPv4Address(final String input) { - return IPV4_PATTERN.matcher(input).matches(); - } - - public static boolean isIPv4MappedIPv64Address(final String input) { - return IPV4_MAPPED_IPV6_PATTERN.matcher(input).matches(); - } - - /** - * Checks whether the parameter is a valid standard (non-compressed) IPv6 address - * - * @param input the address string to check for validity - * @return true if the input parameter is a valid standard (non-compressed) IPv6 address - */ - public static boolean isIPv6StdAddress(final String input) { - return IPV6_STD_PATTERN.matcher(input).matches(); - } - - /** - * Checks whether the parameter is a valid compressed IPv6 address - * - * @param input the address string to check for validity - * @return true if the input parameter is a valid compressed IPv6 address - */ - public static boolean isIPv6HexCompressedAddress(final String input) { - int colonCount = 0; - for(int i = 0; i < input.length(); i++) { - if (input.charAt(i) == COLON_CHAR) { - colonCount++; - } - } - return colonCount <= MAX_COLON_COUNT && IPV6_HEX_COMPRESSED_PATTERN.matcher(input).matches(); - } - - /** - * Checks whether the parameter is a valid IPv6 address (including compressed). - * - * @param input the address string to check for validity - * @return true if the input parameter is a valid standard or compressed IPv6 address - */ - public static boolean isIPv6Address(final String input) { - return isIPv6StdAddress(input) || isIPv6HexCompressedAddress(input); - } - -} diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/utils/URIBuilder.java b/httpclient5/src/main/java/org/apache/hc/client5/http/utils/URIBuilder.java deleted file mode 100644 index ebc4dc643..000000000 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/utils/URIBuilder.java +++ /dev/null @@ -1,493 +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 - * . - * - */ -package org.apache.hc.client5.http.utils; - -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.apache.hc.core5.annotation.NotThreadSafe; -import org.apache.hc.core5.http.NameValuePair; -import org.apache.hc.core5.http.message.BasicNameValuePair; - -/** - * Builder for {@link URI} instances. - * - * @since 4.2 - */ -@NotThreadSafe -public class URIBuilder { - - private String scheme; - private String encodedSchemeSpecificPart; - private String encodedAuthority; - private String userInfo; - private String encodedUserInfo; - private String host; - private int port; - private String path; - private String encodedPath; - private String encodedQuery; - private List queryParams; - private String query; - private Charset charset; - private String fragment; - private String encodedFragment; - - /** - * Constructs an empty instance. - */ - public URIBuilder() { - super(); - this.port = -1; - } - - /** - * Construct an instance from the string which must be a valid URI. - * - * @param string a valid URI in string form - * @throws URISyntaxException if the input is not a valid URI - */ - public URIBuilder(final String string) throws URISyntaxException { - super(); - digestURI(new URI(string)); - } - - /** - * Construct an instance from the provided URI. - * @param uri - */ - public URIBuilder(final URI uri) { - super(); - digestURI(uri); - } - - /** - * @since 4.4 - */ - public URIBuilder setCharset(final Charset charset) { - this.charset = charset; - return this; - } - - /** - * @since 4.4 - */ - public Charset getCharset() { - return charset; - } - - private List parseQuery(final String query, final Charset charset) { - if (query != null && !query.isEmpty()) { - return URLEncodedUtils.parse(query, charset); - } - return null; - } - - /** - * Builds a {@link URI} instance. - */ - public URI build() throws URISyntaxException { - return new URI(buildString()); - } - - private String buildString() { - final StringBuilder sb = new StringBuilder(); - if (this.scheme != null) { - sb.append(this.scheme).append(':'); - } - if (this.encodedSchemeSpecificPart != null) { - sb.append(this.encodedSchemeSpecificPart); - } else { - if (this.encodedAuthority != null) { - sb.append("//").append(this.encodedAuthority); - } else if (this.host != null) { - sb.append("//"); - if (this.encodedUserInfo != null) { - sb.append(this.encodedUserInfo).append("@"); - } else if (this.userInfo != null) { - sb.append(encodeUserInfo(this.userInfo)).append("@"); - } - if (InetAddressUtils.isIPv6Address(this.host)) { - sb.append("[").append(this.host).append("]"); - } else { - sb.append(this.host); - } - if (this.port >= 0) { - sb.append(":").append(this.port); - } - } - if (this.encodedPath != null) { - sb.append(normalizePath(this.encodedPath)); - } else if (this.path != null) { - sb.append(encodePath(normalizePath(this.path))); - } - if (this.encodedQuery != null) { - sb.append("?").append(this.encodedQuery); - } else if (this.queryParams != null) { - sb.append("?").append(encodeUrlForm(this.queryParams)); - } else if (this.query != null) { - sb.append("?").append(encodeUric(this.query)); - } - } - if (this.encodedFragment != null) { - sb.append("#").append(this.encodedFragment); - } else if (this.fragment != null) { - sb.append("#").append(encodeUric(this.fragment)); - } - return sb.toString(); - } - - private void digestURI(final URI uri) { - this.scheme = uri.getScheme(); - this.encodedSchemeSpecificPart = uri.getRawSchemeSpecificPart(); - this.encodedAuthority = uri.getRawAuthority(); - this.host = uri.getHost(); - this.port = uri.getPort(); - this.encodedUserInfo = uri.getRawUserInfo(); - this.userInfo = uri.getUserInfo(); - this.encodedPath = uri.getRawPath(); - this.path = uri.getPath(); - this.encodedQuery = uri.getRawQuery(); - this.queryParams = parseQuery(uri.getRawQuery(), this.charset != null ? this.charset : StandardCharsets.UTF_8); - this.encodedFragment = uri.getRawFragment(); - this.fragment = uri.getFragment(); - } - - private String encodeUserInfo(final String userInfo) { - return URLEncodedUtils.encUserInfo(userInfo, this.charset != null ? this.charset : StandardCharsets.UTF_8); - } - - private String encodePath(final String path) { - return URLEncodedUtils.encPath(path, this.charset != null ? this.charset : StandardCharsets.UTF_8); - } - - private String encodeUrlForm(final List params) { - return URLEncodedUtils.format(params, this.charset != null ? this.charset : StandardCharsets.UTF_8); - } - - private String encodeUric(final String fragment) { - return URLEncodedUtils.encUric(fragment, this.charset != null ? this.charset : StandardCharsets.UTF_8); - } - - /** - * Sets URI scheme. - */ - public URIBuilder setScheme(final String scheme) { - this.scheme = scheme; - return this; - } - - /** - * Sets URI user info. The value is expected to be unescaped and may contain non ASCII - * characters. - */ - public URIBuilder setUserInfo(final String userInfo) { - this.userInfo = userInfo; - this.encodedSchemeSpecificPart = null; - this.encodedAuthority = null; - this.encodedUserInfo = null; - return this; - } - - /** - * Sets URI user info as a combination of username and password. These values are expected to - * be unescaped and may contain non ASCII characters. - */ - public URIBuilder setUserInfo(final String username, final String password) { - return setUserInfo(username + ':' + password); - } - - /** - * Sets URI host. - */ - public URIBuilder setHost(final String host) { - this.host = host; - this.encodedSchemeSpecificPart = null; - this.encodedAuthority = null; - return this; - } - - /** - * Sets URI port. - */ - public URIBuilder setPort(final int port) { - this.port = port < 0 ? -1 : port; - this.encodedSchemeSpecificPart = null; - this.encodedAuthority = null; - return this; - } - - /** - * Sets URI path. The value is expected to be unescaped and may contain non ASCII characters. - */ - public URIBuilder setPath(final String path) { - this.path = path; - this.encodedSchemeSpecificPart = null; - this.encodedPath = null; - return this; - } - - /** - * Removes URI query. - */ - public URIBuilder removeQuery() { - this.queryParams = null; - this.query = null; - this.encodedQuery = null; - this.encodedSchemeSpecificPart = null; - return this; - } - - /** - * Sets URI query parameters. The parameter name / values are expected to be unescaped - * and may contain non ASCII characters. - *

- * Please note query parameters and custom query component are mutually exclusive. This method - * will remove custom query if present. - *

- * - * @since 4.3 - */ - public URIBuilder setParameters(final List nvps) { - if (this.queryParams == null) { - this.queryParams = new ArrayList<>(); - } else { - this.queryParams.clear(); - } - this.queryParams.addAll(nvps); - this.encodedQuery = null; - this.encodedSchemeSpecificPart = null; - this.query = null; - return this; - } - - /** - * Adds URI query parameters. The parameter name / values are expected to be unescaped - * and may contain non ASCII characters. - *

- * Please note query parameters and custom query component are mutually exclusive. This method - * will remove custom query if present. - *

- * - * @since 4.3 - */ - public URIBuilder addParameters(final List nvps) { - if (this.queryParams == null) { - this.queryParams = new ArrayList<>(); - } - this.queryParams.addAll(nvps); - this.encodedQuery = null; - this.encodedSchemeSpecificPart = null; - this.query = null; - return this; - } - - /** - * Sets URI query parameters. The parameter name / values are expected to be unescaped - * and may contain non ASCII characters. - *

- * Please note query parameters and custom query component are mutually exclusive. This method - * will remove custom query if present. - *

- * - * @since 4.3 - */ - public URIBuilder setParameters(final NameValuePair... nvps) { - if (this.queryParams == null) { - this.queryParams = new ArrayList<>(); - } else { - this.queryParams.clear(); - } - for (final NameValuePair nvp: nvps) { - this.queryParams.add(nvp); - } - this.encodedQuery = null; - this.encodedSchemeSpecificPart = null; - this.query = null; - return this; - } - - /** - * Adds parameter to URI query. The parameter name and value are expected to be unescaped - * and may contain non ASCII characters. - *

- * Please note query parameters and custom query component are mutually exclusive. This method - * will remove custom query if present. - *

- */ - public URIBuilder addParameter(final String param, final String value) { - if (this.queryParams == null) { - this.queryParams = new ArrayList<>(); - } - this.queryParams.add(new BasicNameValuePair(param, value)); - this.encodedQuery = null; - this.encodedSchemeSpecificPart = null; - this.query = null; - return this; - } - - /** - * Sets parameter of URI query overriding existing value if set. The parameter name and value - * are expected to be unescaped and may contain non ASCII characters. - *

- * Please note query parameters and custom query component are mutually exclusive. This method - * will remove custom query if present. - *

- */ - public URIBuilder setParameter(final String param, final String value) { - if (this.queryParams == null) { - this.queryParams = new ArrayList<>(); - } - if (!this.queryParams.isEmpty()) { - for (final Iterator it = this.queryParams.iterator(); it.hasNext(); ) { - final NameValuePair nvp = it.next(); - if (nvp.getName().equals(param)) { - it.remove(); - } - } - } - this.queryParams.add(new BasicNameValuePair(param, value)); - this.encodedQuery = null; - this.encodedSchemeSpecificPart = null; - this.query = null; - return this; - } - - /** - * Clears URI query parameters. - * - * @since 4.3 - */ - public URIBuilder clearParameters() { - this.queryParams = null; - this.encodedQuery = null; - this.encodedSchemeSpecificPart = null; - return this; - } - - /** - * Sets custom URI query. The value is expected to be unescaped and may contain non ASCII - * characters. - *

- * Please note query parameters and custom query component are mutually exclusive. This method - * will remove query parameters if present. - *

- * - * @since 4.3 - */ - public URIBuilder setCustomQuery(final String query) { - this.query = query; - this.encodedQuery = null; - this.encodedSchemeSpecificPart = null; - this.queryParams = null; - return this; - } - - /** - * Sets URI fragment. The value is expected to be unescaped and may contain non ASCII - * characters. - */ - public URIBuilder setFragment(final String fragment) { - this.fragment = fragment; - this.encodedFragment = null; - return this; - } - - /** - * @since 4.3 - */ - public boolean isAbsolute() { - return this.scheme != null; - } - - /** - * @since 4.3 - */ - public boolean isOpaque() { - return this.path == null; - } - - public String getScheme() { - return this.scheme; - } - - public String getUserInfo() { - return this.userInfo; - } - - public String getHost() { - return this.host; - } - - public int getPort() { - return this.port; - } - - public String getPath() { - return this.path; - } - - public List getQueryParams() { - if (this.queryParams != null) { - return new ArrayList<>(this.queryParams); - } else { - return new ArrayList<>(); - } - } - - public String getFragment() { - return this.fragment; - } - - @Override - public String toString() { - return buildString(); - } - - private static String normalizePath(final String path) { - String s = path; - if (s == null) { - return null; - } - int n = 0; - for (; n < s.length(); n++) { - if (s.charAt(n) != '/') { - break; - } - } - if (n > 1) { - s = s.substring(n - 1); - } - return s; - } - -} diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/utils/URIUtils.java b/httpclient5/src/main/java/org/apache/hc/client5/http/utils/URIUtils.java index 3762b0422..ba81be296 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/utils/URIUtils.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/utils/URIUtils.java @@ -32,9 +32,9 @@ import java.util.List; import java.util.Locale; import java.util.Stack; -import org.apache.hc.client5.http.RouteInfo; -import org.apache.hc.core5.annotation.Immutable; import org.apache.hc.core5.http.HttpHost; +import org.apache.hc.core5.net.URIAuthority; +import org.apache.hc.core5.net.URIBuilder; import org.apache.hc.core5.util.Args; import org.apache.hc.core5.util.TextUtils; @@ -44,7 +44,6 @@ import org.apache.hc.core5.util.TextUtils; * * @since 4.0 */ -@Immutable public class URIUtils { /** @@ -131,39 +130,6 @@ public class URIUtils { return uribuilder.build(); } - /** - * A convenience method that optionally converts the original {@link java.net.URI} either - * to a relative or an absolute form as required by the specified route. - * - * @param uri - * original URI. - * @throws URISyntaxException - * If the resulting URI is invalid. - * - * @since 4.4 - */ - public static URI rewriteURIForRoute(final URI uri, final RouteInfo route) throws URISyntaxException { - if (uri == null) { - return null; - } - if (route.getProxyHost() != null && !route.isTunnelled()) { - // Make sure the request URI is absolute - if (!uri.isAbsolute()) { - final HttpHost target = route.getTargetHost(); - return rewriteURI(uri, target, true); - } else { - return rewriteURI(uri); - } - } else { - // Make sure the request URI is relative - if (uri.isAbsolute()) { - return rewriteURI(uri, null, true); - } else { - return rewriteURI(uri); - } - } - } - /** * Resolves a URI reference against a base URI. Work-around for bug in * java.net.URI (http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4708535) @@ -369,6 +335,35 @@ public class URIUtils { return uribuilder.build(); } + /** + * Convenience factory method for {@link URI} instances. + * + * @since 5.0 + */ + public static URI create(final HttpHost host, final String path) throws URISyntaxException { + final URIBuilder builder = new URIBuilder(path); + if (host != null) { + builder.setHost(host.getHostName()).setPort(host.getPort()).setScheme(host.getSchemeName()); + } + return builder.build(); + } + + /** + * Convenience factory method for {@link URI} instances. + * + * @since 5.0 + */ + public static URI create(final String scheme, final URIAuthority host, final String path) throws URISyntaxException { + final URIBuilder builder = new URIBuilder(path); + if (scheme != null) { + builder.setScheme(scheme); + } + if (host != null) { + builder.setHost(host.getHostName()).setPort(host.getPort()); + } + return builder.build(); + } + /** * This class should not be instantiated. */ diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/utils/URLEncodedUtils.java b/httpclient5/src/main/java/org/apache/hc/client5/http/utils/URLEncodedUtils.java deleted file mode 100644 index 5487878de..000000000 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/utils/URLEncodedUtils.java +++ /dev/null @@ -1,537 +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 - * . - * - */ - -package org.apache.hc.client5.http.utils; - -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.net.URI; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.BitSet; -import java.util.Collections; -import java.util.List; - -import org.apache.hc.core5.annotation.Immutable; -import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.NameValuePair; -import org.apache.hc.core5.http.entity.ContentType; -import org.apache.hc.core5.http.message.BasicNameValuePair; -import org.apache.hc.core5.http.message.ParserCursor; -import org.apache.hc.core5.http.message.TokenParser; -import org.apache.hc.core5.util.Args; -import org.apache.hc.core5.util.CharArrayBuffer; - -/** - * A collection of utilities for encoding URLs. - * - * @since 4.0 - */ -@Immutable -public class URLEncodedUtils { - - /** - * The default HTML form content type. - */ - public static final String CONTENT_TYPE = "application/x-www-form-urlencoded"; - - private static final char QP_SEP_A = '&'; - private static final char QP_SEP_S = ';'; - private static final String NAME_VALUE_SEPARATOR = "="; - - /** - * Returns a list of {@link NameValuePair NameValuePairs} as built from the URI's query portion. For example, a URI - * of {@code http://example.org/path/to/file?a=1&b=2&c=3} would return a list of three NameValuePairs, one for a=1, - * one for b=2, and one for c=3. By convention, {@code '&'} and {@code ';'} are accepted as parameter separators. - *

- * This is typically useful while parsing an HTTP PUT. - * - * This API is currently only used for testing. - * - * @param uri - * URI to parse - * @param charset - * Charset to use while parsing the query - * @return a list of {@link NameValuePair} as built from the URI's query portion. - * - * @since 4.5 - */ - public static List parse(final URI uri, final Charset charset) { - Args.notNull(uri, "URI"); - final String query = uri.getRawQuery(); - if (query != null && !query.isEmpty()) { - return parse(query, charset); - } - return Collections.emptyList(); - } - - /** - * Returns a list of {@link NameValuePair NameValuePairs} as parsed from an {@link HttpEntity}. - * The encoding is taken from the entity's Content-Encoding header. - *

- * This is typically used while parsing an HTTP POST. - * - * @param entity - * The entity to parse - * @return a list of {@link NameValuePair} as built from the URI's query portion. - * @throws IOException - * If there was an exception getting the entity's data. - */ - public static List parse( - final HttpEntity entity) throws IOException { - Args.notNull(entity, "HTTP entity"); - final ContentType contentType = ContentType.get(entity); - if (contentType == null || !contentType.getMimeType().equalsIgnoreCase(CONTENT_TYPE)) { - return Collections.emptyList(); - } - final long len = entity.getContentLength(); - Args.check(len <= Integer.MAX_VALUE, "HTTP entity is too large"); - final Charset charset = contentType.getCharset() != null ? contentType.getCharset() : StandardCharsets.ISO_8859_1; - final InputStream instream = entity.getContent(); - if (instream == null) { - return Collections.emptyList(); - } - final CharArrayBuffer buf; - try { - buf = new CharArrayBuffer(len > 0 ? (int) len : 1024); - final Reader reader = new InputStreamReader(instream, charset); - final char[] tmp = new char[1024]; - int l; - while((l = reader.read(tmp)) != -1) { - buf.append(tmp, 0, l); - } - - } finally { - instream.close(); - } - if (buf.length() == 0) { - return Collections.emptyList(); - } - return parse(buf, charset, QP_SEP_A); - } - - /** - * Returns true if the entity's Content-Type header is - * {@code application/x-www-form-urlencoded}. - */ - public static boolean isEncoded(final HttpEntity entity) { - Args.notNull(entity, "HTTP entity"); - final ContentType contentType = ContentType.parse(entity.getContentType()); - return contentType != null && CONTENT_TYPE.equalsIgnoreCase(contentType.getMimeType()); - } - - /** - * Returns a list of {@link NameValuePair NameValuePairs} as parsed from the given string using the given character - * encoding. By convention, {@code '&'} and {@code ';'} are accepted as parameter separators. - * - * @param s - * text to parse. - * @param charset - * Encoding to use when decoding the parameters. - * @return a list of {@link NameValuePair} as built from the URI's query portion. - * - * @since 4.2 - */ - public static List parse(final String s, final Charset charset) { - if (s == null) { - return Collections.emptyList(); - } - final CharArrayBuffer buffer = new CharArrayBuffer(s.length()); - buffer.append(s); - return parse(buffer, charset, QP_SEP_A, QP_SEP_S); - } - - /** - * Returns a list of {@link NameValuePair NameValuePairs} as parsed from the given string using the given character - * encoding. - * - * @param s - * text to parse. - * @param charset - * Encoding to use when decoding the parameters. - * @param separators - * element separators. - * @return a list of {@link NameValuePair} as built from the URI's query portion. - * - * @since 4.3 - */ - public static List parse(final String s, final Charset charset, final char... separators) { - if (s == null) { - return Collections.emptyList(); - } - final CharArrayBuffer buffer = new CharArrayBuffer(s.length()); - buffer.append(s); - return parse(buffer, charset, separators); - } - - /** - * Returns a list of {@link NameValuePair NameValuePairs} as parsed from the given string using - * the given character encoding. - * - * @param buf - * text to parse. - * @param charset - * Encoding to use when decoding the parameters. - * @param separators - * element separators. - * @return a list of {@link NameValuePair} as built from the URI's query portion. - * - * @since 4.4 - */ - public static List parse( - final CharArrayBuffer buf, final Charset charset, final char... separators) { - Args.notNull(buf, "Char array buffer"); - final TokenParser tokenParser = TokenParser.INSTANCE; - final BitSet delimSet = new BitSet(); - for (final char separator: separators) { - delimSet.set(separator); - } - final ParserCursor cursor = new ParserCursor(0, buf.length()); - final List list = new ArrayList<>(); - while (!cursor.atEnd()) { - delimSet.set('='); - final String name = tokenParser.parseToken(buf, cursor, delimSet); - String value = null; - if (!cursor.atEnd()) { - final int delim = buf.charAt(cursor.getPos()); - cursor.updatePos(cursor.getPos() + 1); - if (delim == '=') { - delimSet.clear('='); - value = tokenParser.parseValue(buf, cursor, delimSet); - if (!cursor.atEnd()) { - cursor.updatePos(cursor.getPos() + 1); - } - } - } - if (!name.isEmpty()) { - list.add(new BasicNameValuePair( - decodeFormFields(name, charset), - decodeFormFields(value, charset))); - } - } - return list; - } - - /** - * Returns a String that is suitable for use as an {@code application/x-www-form-urlencoded} - * list of parameters in an HTTP PUT or HTTP POST. - * - * @param parameters The parameters to include. - * @param charset The encoding to use. - * @return An {@code application/x-www-form-urlencoded} string - * - * @since 4.2 - */ - public static String format( - final Iterable parameters, - final Charset charset) { - return format(parameters, QP_SEP_A, charset); - } - - /** - * Returns a String that is suitable for use as an {@code application/x-www-form-urlencoded} - * list of parameters in an HTTP PUT or HTTP POST. - * - * @param parameters The parameters to include. - * @param parameterSeparator The parameter separator, by convention, {@code '&'} or {@code ';'}. - * @param charset The encoding to use. - * @return An {@code application/x-www-form-urlencoded} string - * - * @since 4.3 - */ - public static String format( - final Iterable parameters, - final char parameterSeparator, - final Charset charset) { - Args.notNull(parameters, "Parameters"); - final StringBuilder result = new StringBuilder(); - for (final NameValuePair parameter : parameters) { - final String encodedName = encodeFormFields(parameter.getName(), charset); - final String encodedValue = encodeFormFields(parameter.getValue(), charset); - if (result.length() > 0) { - result.append(parameterSeparator); - } - result.append(encodedName); - if (encodedValue != null) { - result.append(NAME_VALUE_SEPARATOR); - result.append(encodedValue); - } - } - return result.toString(); - } - - /** - * Unreserved characters, i.e. alphanumeric, plus: {@code _ - ! . ~ ' ( ) *} - *

- * This list is the same as the {@code unreserved} list in - * RFC 2396 - */ - private static final BitSet UNRESERVED = new BitSet(256); - /** - * Punctuation characters: , ; : $ & + = - *

- * These are the additional characters allowed by userinfo. - */ - private static final BitSet PUNCT = new BitSet(256); - /** Characters which are safe to use in userinfo, - * i.e. {@link #UNRESERVED} plus {@link #PUNCT}uation */ - private static final BitSet USERINFO = new BitSet(256); - /** Characters which are safe to use in a path, - * i.e. {@link #UNRESERVED} plus {@link #PUNCT}uation plus / @ */ - private static final BitSet PATHSAFE = new BitSet(256); - /** Characters which are safe to use in a query or a fragment, - * i.e. {@link #RESERVED} plus {@link #UNRESERVED} */ - private static final BitSet URIC = new BitSet(256); - - /** - * Reserved characters, i.e. {@code ;/?:@&=+$,[]} - *

- * This list is the same as the {@code reserved} list in - * RFC 2396 - * as augmented by - * RFC 2732 - */ - private static final BitSet RESERVED = new BitSet(256); - - - /** - * Safe characters for x-www-form-urlencoded data, as per java.net.URLEncoder and browser behaviour, - * i.e. alphanumeric plus {@code "-", "_", ".", "*"} - */ - private static final BitSet URLENCODER = new BitSet(256); - - static { - // unreserved chars - // alpha characters - for (int i = 'a'; i <= 'z'; i++) { - UNRESERVED.set(i); - } - for (int i = 'A'; i <= 'Z'; i++) { - UNRESERVED.set(i); - } - // numeric characters - for (int i = '0'; i <= '9'; i++) { - UNRESERVED.set(i); - } - UNRESERVED.set('_'); // these are the charactes of the "mark" list - UNRESERVED.set('-'); - UNRESERVED.set('.'); - UNRESERVED.set('*'); - URLENCODER.or(UNRESERVED); // skip remaining unreserved characters - UNRESERVED.set('!'); - UNRESERVED.set('~'); - UNRESERVED.set('\''); - UNRESERVED.set('('); - UNRESERVED.set(')'); - // punct chars - PUNCT.set(','); - PUNCT.set(';'); - PUNCT.set(':'); - PUNCT.set('$'); - PUNCT.set('&'); - PUNCT.set('+'); - PUNCT.set('='); - // Safe for userinfo - USERINFO.or(UNRESERVED); - USERINFO.or(PUNCT); - - // URL path safe - PATHSAFE.or(UNRESERVED); - PATHSAFE.set('/'); // segment separator - PATHSAFE.set(';'); // param separator - PATHSAFE.set(':'); // rest as per list in 2396, i.e. : @ & = + $ , - PATHSAFE.set('@'); - PATHSAFE.set('&'); - PATHSAFE.set('='); - PATHSAFE.set('+'); - PATHSAFE.set('$'); - PATHSAFE.set(','); - - RESERVED.set(';'); - RESERVED.set('/'); - RESERVED.set('?'); - RESERVED.set(':'); - RESERVED.set('@'); - RESERVED.set('&'); - RESERVED.set('='); - RESERVED.set('+'); - RESERVED.set('$'); - RESERVED.set(','); - RESERVED.set('['); // added by RFC 2732 - RESERVED.set(']'); // added by RFC 2732 - - URIC.or(RESERVED); - URIC.or(UNRESERVED); - } - - private static final int RADIX = 16; - - private static String urlEncode( - final String content, - final Charset charset, - final BitSet safechars, - final boolean blankAsPlus) { - if (content == null) { - return null; - } - final StringBuilder buf = new StringBuilder(); - final ByteBuffer bb = charset.encode(content); - while (bb.hasRemaining()) { - final int b = bb.get() & 0xff; - if (safechars.get(b)) { - buf.append((char) b); - } else if (blankAsPlus && b == ' ') { - buf.append('+'); - } else { - buf.append("%"); - final char hex1 = Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, RADIX)); - final char hex2 = Character.toUpperCase(Character.forDigit(b & 0xF, RADIX)); - buf.append(hex1); - buf.append(hex2); - } - } - return buf.toString(); - } - - /** - * Decode/unescape a portion of a URL, to use with the query part ensure {@code plusAsBlank} is true. - * - * @param content the portion to decode - * @param charset the charset to use - * @param plusAsBlank if {@code true}, then convert '+' to space (e.g. for www-url-form-encoded content), otherwise leave as is. - * @return encoded string - */ - private static String urlDecode( - final String content, - final Charset charset, - final boolean plusAsBlank) { - if (content == null) { - return null; - } - final ByteBuffer bb = ByteBuffer.allocate(content.length()); - final CharBuffer cb = CharBuffer.wrap(content); - while (cb.hasRemaining()) { - final char c = cb.get(); - if (c == '%' && cb.remaining() >= 2) { - final char uc = cb.get(); - final char lc = cb.get(); - final int u = Character.digit(uc, 16); - final int l = Character.digit(lc, 16); - if (u != -1 && l != -1) { - bb.put((byte) ((u << 4) + l)); - } else { - bb.put((byte) '%'); - bb.put((byte) uc); - bb.put((byte) lc); - } - } else if (plusAsBlank && c == '+') { - bb.put((byte) ' '); - } else { - bb.put((byte) c); - } - } - bb.flip(); - return charset.decode(bb).toString(); - } - - /** - * Decode/unescape www-url-form-encoded content. - * - * @param content the content to decode, will decode '+' as space - * @param charset the charset to use - * @return encoded string - */ - private static String decodeFormFields (final String content, final Charset charset) { - if (content == null) { - return null; - } - return urlDecode(content, charset != null ? charset : StandardCharsets.UTF_8, true); - } - - /** - * Encode/escape www-url-form-encoded content. - *

- * Uses the {@link #URLENCODER} set of characters, rather than - * the {@link #UNRESERVED} set; this is for compatibilty with previous - * releases, URLEncoder.encode() and most browsers. - * - * @param content the content to encode, will convert space to '+' - * @param charset the charset to use - * @return encoded string - */ - private static String encodeFormFields (final String content, final Charset charset) { - if (content == null) { - return null; - } - return urlEncode(content, charset != null ? charset : StandardCharsets.UTF_8, URLENCODER, true); - } - - /** - * Encode a String using the {@link #USERINFO} set of characters. - *

- * Used by URIBuilder to encode the userinfo segment. - * - * @param content the string to encode, does not convert space to '+' - * @param charset the charset to use - * @return the encoded string - */ - static String encUserInfo(final String content, final Charset charset) { - return urlEncode(content, charset, USERINFO, false); - } - - /** - * Encode a String using the {@link #URIC} set of characters. - *

- * Used by URIBuilder to encode the query and fragment segments. - * - * @param content the string to encode, does not convert space to '+' - * @param charset the charset to use - * @return the encoded string - */ - static String encUric(final String content, final Charset charset) { - return urlEncode(content, charset, URIC, false); - } - - /** - * Encode a String using the {@link #PATHSAFE} set of characters. - *

- * Used by URIBuilder to encode path segments. - * - * @param content the string to encode, does not convert space to '+' - * @param charset the charset to use - * @return the encoded string - */ - static String encPath(final String content, final Charset charset) { - return urlEncode(content, charset, PATHSAFE, false); - } - -} diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/config/TestRequestConfig.java b/httpclient5/src/test/java/org/apache/hc/client5/http/config/TestRequestConfig.java index 9e634e695..b692ed11f 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/config/TestRequestConfig.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/config/TestRequestConfig.java @@ -70,7 +70,6 @@ public class TestRequestConfig { .setExpectContinueEnabled(true) .setAuthenticationEnabled(false) .setRedirectsEnabled(false) - .setRelativeRedirectsAllowed(false) .setCircularRedirectsAllowed(true) .setMaxRedirects(100) .setCookieSpec(CookieSpecs.STANDARD) diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/entity/TestDecompressingEntity.java b/httpclient5/src/test/java/org/apache/hc/client5/http/entity/TestDecompressingEntity.java index 09f630e13..8830527f5 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/entity/TestDecompressingEntity.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/entity/TestDecompressingEntity.java @@ -37,9 +37,9 @@ import java.util.zip.CheckedInputStream; import java.util.zip.Checksum; import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.entity.EntityUtils; -import org.apache.hc.core5.http.entity.InputStreamEntity; -import org.apache.hc.core5.http.entity.StringEntity; +import org.apache.hc.core5.http.io.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.InputStreamEntity; +import org.apache.hc.core5.http.io.entity.StringEntity; import org.junit.Assert; import org.junit.Test; diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/entity/TestDeflate.java b/httpclient5/src/test/java/org/apache/hc/client5/http/entity/TestDeflate.java index 1468eca84..a14110df0 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/entity/TestDeflate.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/entity/TestDeflate.java @@ -31,8 +31,8 @@ import java.nio.charset.StandardCharsets; import java.util.zip.Deflater; import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.entity.ByteArrayEntity; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.ByteArrayEntity; +import org.apache.hc.core5.http.io.entity.EntityUtils; import org.junit.Assert; import org.junit.Test; diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/entity/TestEntityBuilder.java b/httpclient5/src/test/java/org/apache/hc/client5/http/entity/TestEntityBuilder.java index a6e15371e..e65dcd882 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/entity/TestEntityBuilder.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/entity/TestEntityBuilder.java @@ -30,9 +30,9 @@ package org.apache.hc.client5.http.entity; import java.io.File; import java.io.InputStream; +import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.entity.ContentType; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.EntityUtils; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/entity/TestGZip.java b/httpclient5/src/test/java/org/apache/hc/client5/http/entity/TestGZip.java index ddc19f156..6b19fb8c3 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/entity/TestGZip.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/entity/TestGZip.java @@ -32,11 +32,11 @@ import java.io.IOException; import java.io.OutputStream; import java.nio.charset.StandardCharsets; +import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.entity.ByteArrayEntity; -import org.apache.hc.core5.http.entity.ContentType; -import org.apache.hc.core5.http.entity.EntityUtils; -import org.apache.hc.core5.http.entity.StringEntity; +import org.apache.hc.core5.http.io.entity.ByteArrayEntity; +import org.apache.hc.core5.http.io.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.StringEntity; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/entity/mime/FormBodyPartTest.java b/httpclient5/src/test/java/org/apache/hc/client5/http/entity/mime/FormBodyPartTest.java index d783222a9..57c5a78d6 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/entity/mime/FormBodyPartTest.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/entity/mime/FormBodyPartTest.java @@ -29,7 +29,7 @@ package org.apache.hc.client5.http.entity.mime; import java.io.File; -import org.apache.hc.core5.http.entity.ContentType; +import org.apache.hc.core5.http.ContentType; import org.junit.Assert; import org.junit.Test; @@ -42,4 +42,4 @@ public class FormBodyPartTest { final FileBody obj = new FileBody(tmp, ContentType.APPLICATION_OCTET_STREAM); Assert.assertEquals(tmp.getName(), obj.getFilename()); } -} \ No newline at end of file +} diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/entity/mime/TestFormBodyPartBuilder.java b/httpclient5/src/test/java/org/apache/hc/client5/http/entity/mime/TestFormBodyPartBuilder.java index 62501572b..e333b5f3e 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/entity/mime/TestFormBodyPartBuilder.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/entity/mime/TestFormBodyPartBuilder.java @@ -31,7 +31,7 @@ import java.io.File; import java.util.Arrays; import java.util.List; -import org.apache.hc.core5.http.entity.ContentType; +import org.apache.hc.core5.http.ContentType; import org.junit.Assert; import org.junit.Test; diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/entity/mime/TestMultipartContentBody.java b/httpclient5/src/test/java/org/apache/hc/client5/http/entity/mime/TestMultipartContentBody.java index 7b4c32b8c..37590fd31 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/entity/mime/TestMultipartContentBody.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/entity/mime/TestMultipartContentBody.java @@ -30,7 +30,7 @@ package org.apache.hc.client5.http.entity.mime; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; -import org.apache.hc.core5.http.entity.ContentType; +import org.apache.hc.core5.http.ContentType; import org.junit.Assert; import org.junit.Test; diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/entity/mime/TestMultipartEntityBuilder.java b/httpclient5/src/test/java/org/apache/hc/client5/http/entity/mime/TestMultipartEntityBuilder.java index a6ba1b489..c130b6916 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/entity/mime/TestMultipartEntityBuilder.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/entity/mime/TestMultipartEntityBuilder.java @@ -32,7 +32,7 @@ import java.io.File; import java.nio.charset.StandardCharsets; import java.util.List; -import org.apache.hc.core5.http.entity.ContentType; +import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.message.BasicNameValuePair; import org.junit.Assert; import org.junit.Test; diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/entity/mime/TestMultipartForm.java b/httpclient5/src/test/java/org/apache/hc/client5/http/entity/mime/TestMultipartForm.java index 91fae95d6..8c729b7b0 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/entity/mime/TestMultipartForm.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/entity/mime/TestMultipartForm.java @@ -36,7 +36,7 @@ import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Arrays; -import org.apache.hc.core5.http.entity.ContentType; +import org.apache.hc.core5.http.ContentType; import org.junit.After; import org.junit.Assert; import org.junit.Test; diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/entity/mime/TestMultipartFormHttpEntity.java b/httpclient5/src/test/java/org/apache/hc/client5/http/entity/mime/TestMultipartFormHttpEntity.java index e7efc5867..8838e59d0 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/entity/mime/TestMultipartFormHttpEntity.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/entity/mime/TestMultipartFormHttpEntity.java @@ -31,10 +31,10 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; +import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.HeaderElement; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.NameValuePair; -import org.apache.hc.core5.http.entity.ContentType; import org.apache.hc.core5.http.message.BasicHeaderValueParser; import org.apache.hc.core5.http.message.ParserCursor; import org.junit.Assert; diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/TestAbstractResponseHandler.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/TestAbstractResponseHandler.java index 8777aca55..507ce1464 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/TestAbstractResponseHandler.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/TestAbstractResponseHandler.java @@ -32,13 +32,10 @@ import java.io.InputStream; import org.apache.hc.client5.http.impl.sync.AbstractResponseHandler; import org.apache.hc.client5.http.protocol.HttpResponseException; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.HttpResponse; -import org.apache.hc.core5.http.HttpVersion; -import org.apache.hc.core5.http.StatusLine; -import org.apache.hc.core5.http.entity.EntityUtils; -import org.apache.hc.core5.http.entity.StringEntity; -import org.apache.hc.core5.http.message.BasicStatusLine; +import org.apache.hc.core5.http.io.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.StringEntity; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; @@ -50,10 +47,9 @@ public class TestAbstractResponseHandler { @Test public void testSuccessfulResponse() throws Exception { - final StatusLine sl = new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"); - final HttpResponse response = Mockito.mock(HttpResponse.class); + final ClassicHttpResponse response = Mockito.mock(ClassicHttpResponse.class); final HttpEntity entity = new StringEntity("42"); - Mockito.when(response.getStatusLine()).thenReturn(sl); + Mockito.when(response.getCode()).thenReturn(200); Mockito.when(response.getEntity()).thenReturn(entity); final AbstractResponseHandler handler = new AbstractResponseHandler() { @@ -74,9 +70,8 @@ public class TestAbstractResponseHandler { final HttpEntity entity = Mockito.mock(HttpEntity.class); Mockito.when(entity.isStreaming()).thenReturn(true); Mockito.when(entity.getContent()).thenReturn(instream); - final StatusLine sl = new BasicStatusLine(HttpVersion.HTTP_1_1, 404, "Not Found"); - final HttpResponse response = Mockito.mock(HttpResponse.class); - Mockito.when(response.getStatusLine()).thenReturn(sl); + final ClassicHttpResponse response = Mockito.mock(ClassicHttpResponse.class); + Mockito.when(response.getCode()).thenReturn(404); Mockito.when(response.getEntity()).thenReturn(entity); final BasicResponseHandler handler = new BasicResponseHandler(); @@ -85,7 +80,6 @@ public class TestAbstractResponseHandler { Assert.fail("HttpResponseException expected"); } catch (final HttpResponseException ex) { Assert.assertEquals(404, ex.getStatusCode()); - Assert.assertEquals("Not Found", ex.getMessage()); } Mockito.verify(entity).getContent(); Mockito.verify(instream).close(); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/TestBasicResponseHandler.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/TestBasicResponseHandler.java index bec0114f8..035987831 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/TestBasicResponseHandler.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/TestBasicResponseHandler.java @@ -30,12 +30,9 @@ package org.apache.hc.client5.http.impl; import java.io.InputStream; import org.apache.hc.client5.http.protocol.HttpResponseException; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.HttpResponse; -import org.apache.hc.core5.http.HttpVersion; -import org.apache.hc.core5.http.StatusLine; -import org.apache.hc.core5.http.entity.StringEntity; -import org.apache.hc.core5.http.message.BasicStatusLine; +import org.apache.hc.core5.http.io.entity.StringEntity; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; @@ -48,10 +45,9 @@ public class TestBasicResponseHandler { @Test public void testSuccessfulResponse() throws Exception { - final StatusLine sl = new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"); - final HttpResponse response = Mockito.mock(HttpResponse.class); + final ClassicHttpResponse response = Mockito.mock(ClassicHttpResponse.class); final HttpEntity entity = new StringEntity("stuff"); - Mockito.when(response.getStatusLine()).thenReturn(sl); + Mockito.when(response.getCode()).thenReturn(200); Mockito.when(response.getEntity()).thenReturn(entity); final BasicResponseHandler handler = new BasicResponseHandler(); @@ -65,9 +61,8 @@ public class TestBasicResponseHandler { final HttpEntity entity = Mockito.mock(HttpEntity.class); Mockito.when(entity.isStreaming()).thenReturn(true); Mockito.when(entity.getContent()).thenReturn(instream); - final StatusLine sl = new BasicStatusLine(HttpVersion.HTTP_1_1, 404, "Not Found"); - final HttpResponse response = Mockito.mock(HttpResponse.class); - Mockito.when(response.getStatusLine()).thenReturn(sl); + final ClassicHttpResponse response = Mockito.mock(ClassicHttpResponse.class); + Mockito.when(response.getCode()).thenReturn(404); Mockito.when(response.getEntity()).thenReturn(entity); final BasicResponseHandler handler = new BasicResponseHandler(); @@ -76,7 +71,6 @@ public class TestBasicResponseHandler { Assert.fail("HttpResponseException expected"); } catch (final HttpResponseException ex) { Assert.assertEquals(404, ex.getStatusCode()); - Assert.assertEquals("Not Found", ex.getMessage()); } Mockito.verify(entity).getContent(); Mockito.verify(instream).close(); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/TestDefaultConnKeepAliveStrategy.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/TestDefaultConnKeepAliveStrategy.java index b6fd3e21b..af375b27a 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/TestDefaultConnKeepAliveStrategy.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/TestDefaultConnKeepAliveStrategy.java @@ -29,9 +29,7 @@ package org.apache.hc.client5.http.impl; import org.apache.hc.client5.http.ConnectionKeepAliveStrategy; import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.HttpStatus; -import org.apache.hc.core5.http.HttpVersion; import org.apache.hc.core5.http.message.BasicHttpResponse; -import org.apache.hc.core5.http.message.BasicStatusLine; import org.apache.hc.core5.http.protocol.BasicHttpContext; import org.apache.hc.core5.http.protocol.HttpContext; import org.junit.Assert; @@ -52,8 +50,7 @@ public class TestDefaultConnKeepAliveStrategy { @Test public void testNoKeepAliveHeader() throws Exception { final HttpContext context = new BasicHttpContext(null); - final HttpResponse response = new BasicHttpResponse( - new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK")); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_OK); final ConnectionKeepAliveStrategy keepAliveStrat = new DefaultConnectionKeepAliveStrategy(); final long d = keepAliveStrat.getKeepAliveDuration(response, context); Assert.assertEquals(-1, d); @@ -62,8 +59,7 @@ public class TestDefaultConnKeepAliveStrategy { @Test public void testEmptyKeepAliveHeader() throws Exception { final HttpContext context = new BasicHttpContext(null); - final HttpResponse response = new BasicHttpResponse( - new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK")); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_OK); response.addHeader("Keep-Alive", "timeout, max=20"); final ConnectionKeepAliveStrategy keepAliveStrat = new DefaultConnectionKeepAliveStrategy(); final long d = keepAliveStrat.getKeepAliveDuration(response, context); @@ -73,8 +69,7 @@ public class TestDefaultConnKeepAliveStrategy { @Test public void testInvalidKeepAliveHeader() throws Exception { final HttpContext context = new BasicHttpContext(null); - final HttpResponse response = new BasicHttpResponse( - new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK")); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_OK); response.addHeader("Keep-Alive", "timeout=whatever, max=20"); final ConnectionKeepAliveStrategy keepAliveStrat = new DefaultConnectionKeepAliveStrategy(); final long d = keepAliveStrat.getKeepAliveDuration(response, context); @@ -84,8 +79,7 @@ public class TestDefaultConnKeepAliveStrategy { @Test public void testKeepAliveHeader() throws Exception { final HttpContext context = new BasicHttpContext(null); - final HttpResponse response = new BasicHttpResponse( - new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK")); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_OK); response.addHeader("Keep-Alive", "timeout=300, max=20"); final ConnectionKeepAliveStrategy keepAliveStrat = new DefaultConnectionKeepAliveStrategy(); final long d = keepAliveStrat.getKeepAliveDuration(response, context); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/auth/TestDigestScheme.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/auth/TestDigestScheme.java index 4ac69626b..e64b9e0d3 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/auth/TestDigestScheme.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/auth/TestDigestScheme.java @@ -45,12 +45,14 @@ import org.apache.hc.client5.http.auth.Credentials; import org.apache.hc.client5.http.auth.MalformedChallengeException; import org.apache.hc.client5.http.auth.UsernamePasswordCredentials; import org.apache.hc.client5.http.impl.sync.BasicCredentialsProvider; +import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.HeaderElement; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.ParseException; -import org.apache.hc.core5.http.entity.InputStreamEntity; -import org.apache.hc.core5.http.entity.StringEntity; +import org.apache.hc.core5.http.io.entity.InputStreamEntity; +import org.apache.hc.core5.http.io.entity.StringEntity; +import org.apache.hc.core5.http.message.BasicClassicHttpRequest; import org.apache.hc.core5.http.message.BasicHeaderValueParser; import org.apache.hc.core5.http.message.BasicHttpRequest; import org.apache.hc.core5.http.message.ParserCursor; @@ -583,7 +585,7 @@ public class TestDigestScheme { @Test public void testDigestAuthenticationQopAuthInt() throws Exception { - final HttpRequest request = new BasicHttpRequest("Post", "/"); + final ClassicHttpRequest request = new BasicClassicHttpRequest("Post", "/"); request.setEntity(new StringEntity("abc\u00e4\u00f6\u00fcabc", StandardCharsets.ISO_8859_1)); final HttpHost host = new HttpHost("somehost", 80); final AuthScope authScope = new AuthScope(host, "realm1", null); @@ -638,7 +640,7 @@ public class TestDigestScheme { @Test public void testDigestAuthenticationQopAuthOrAuthIntNonRepeatableEntity() throws Exception { - final HttpRequest request = new BasicHttpRequest("Post", "/"); + final ClassicHttpRequest request = new BasicClassicHttpRequest("Post", "/"); request.setEntity(new InputStreamEntity(new ByteArrayInputStream(new byte[] {'a'}), -1)); final HttpHost host = new HttpHost("somehost", 80); final AuthScope authScope = new AuthScope(host, "realm1", null); @@ -687,7 +689,7 @@ public class TestDigestScheme { @Test(expected=AuthenticationException.class) public void testDigestAuthenticationQopIntOnlyNonRepeatableEntity() throws Exception { - final HttpRequest request = new BasicHttpRequest("Post", "/"); + final ClassicHttpRequest request = new BasicClassicHttpRequest("Post", "/"); request.setEntity(new InputStreamEntity(new ByteArrayInputStream(new byte[] {'a'}), -1)); final HttpHost host = new HttpHost("somehost", 80); final AuthScope authScope = new AuthScope(host, "realm1", null); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/auth/TestHttpAuthenticator.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/auth/TestHttpAuthenticator.java index 7320ea86b..27ddcf863 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/auth/TestHttpAuthenticator.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/auth/TestHttpAuthenticator.java @@ -46,7 +46,6 @@ import org.apache.hc.core5.http.HttpHost; 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.HttpVersion; import org.apache.hc.core5.http.config.Lookup; import org.apache.hc.core5.http.config.RegistryBuilder; import org.apache.hc.core5.http.message.BasicHeader; @@ -54,7 +53,6 @@ import org.apache.hc.core5.http.message.BasicHttpRequest; import org.apache.hc.core5.http.message.BasicHttpResponse; import org.apache.hc.core5.http.protocol.BasicHttpContext; import org.apache.hc.core5.http.protocol.HttpContext; -import org.apache.hc.core5.http.protocol.HttpCoreContext; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -80,7 +78,6 @@ public class TestHttpAuthenticator { Mockito.when(this.authScheme.isChallengeComplete()).thenReturn(Boolean.TRUE); this.context = new BasicHttpContext(); this.defaultHost = new HttpHost("localhost", 80); - this.context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.defaultHost); this.credentialsProvider = Mockito.mock(CredentialsProvider.class); this.context.setAttribute(HttpClientContext.CREDS_PROVIDER, this.credentialsProvider); this.authSchemeRegistry = RegistryBuilder.create() @@ -95,7 +92,7 @@ public class TestHttpAuthenticator { @Test public void testUpdateAuthExchange() throws Exception { - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=test"); Assert.assertTrue(this.httpAuthenticator.isChallenged( this.defaultHost, ChallengeType.TARGET, response, this.authExchange, this.context)); @@ -104,7 +101,7 @@ public class TestHttpAuthenticator { @Test public void testAuthenticationRequestedAfterSuccess() throws Exception { - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=test"); this.authExchange.select(this.authScheme); @@ -118,7 +115,7 @@ public class TestHttpAuthenticator { @Test public void testAuthenticationNotRequestedUnchallenged() throws Exception { - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_OK, "OK"); Assert.assertFalse(this.httpAuthenticator.isChallenged( this.defaultHost, ChallengeType.TARGET, response, this.authExchange, this.context)); @@ -127,7 +124,7 @@ public class TestHttpAuthenticator { @Test public void testAuthenticationNotRequestedSuccess1() throws Exception { - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_OK, "OK"); this.authExchange.select(this.authScheme); this.authExchange.setState(AuthExchange.State.CHALLENGED); @@ -140,7 +137,7 @@ public class TestHttpAuthenticator { @Test public void testAuthenticationNotRequestedSuccess2() throws Exception { - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_OK, "OK"); this.authExchange.select(this.authScheme); this.authExchange.setState(AuthExchange.State.HANDSHAKE); @@ -154,7 +151,7 @@ public class TestHttpAuthenticator { @Test public void testAuthentication() throws Exception { final HttpHost host = new HttpHost("somehost", 80); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); response.addHeader(new BasicHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"test\"")); response.addHeader(new BasicHeader(HttpHeaders.WWW_AUTHENTICATE, "Digest realm=\"realm1\", nonce=\"1234\"")); response.addHeader(new BasicHeader(HttpHeaders.WWW_AUTHENTICATE, "whatever realm=\"realm1\", stuff=\"1234\"")); @@ -184,7 +181,7 @@ public class TestHttpAuthenticator { public void testAuthenticationCredentialsForBasic() throws Exception { final HttpHost host = new HttpHost("somehost", 80); final HttpResponse response = - new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); + new BasicHttpResponse(HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); response.addHeader(new BasicHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"test\"")); response.addHeader(new BasicHeader(HttpHeaders.WWW_AUTHENTICATE, "Digest realm=\"realm1\", nonce=\"1234\"")); @@ -209,7 +206,7 @@ public class TestHttpAuthenticator { @Test public void testAuthenticationNoChallenges() throws Exception { final HttpHost host = new HttpHost("somehost", 80); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); final DefaultAuthenticationStrategy authStrategy = new DefaultAuthenticationStrategy(); @@ -220,7 +217,7 @@ public class TestHttpAuthenticator { @Test public void testAuthenticationNoSupportedChallenges() throws Exception { final HttpHost host = new HttpHost("somehost", 80); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); response.addHeader(new BasicHeader(HttpHeaders.WWW_AUTHENTICATE, "This realm=\"test\"")); response.addHeader(new BasicHeader(HttpHeaders.WWW_AUTHENTICATE, "That realm=\"realm1\", nonce=\"1234\"")); @@ -233,7 +230,7 @@ public class TestHttpAuthenticator { @Test public void testAuthenticationNoCredentials() throws Exception { final HttpHost host = new HttpHost("somehost", 80); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); response.addHeader(new BasicHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"test\"")); response.addHeader(new BasicHeader(HttpHeaders.WWW_AUTHENTICATE, "Digest realm=\"realm1\", nonce=\"1234\"")); @@ -246,7 +243,7 @@ public class TestHttpAuthenticator { @Test public void testAuthenticationFailed() throws Exception { final HttpHost host = new HttpHost("somehost", 80); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); response.addHeader(new BasicHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"test\"")); response.addHeader(new BasicHeader(HttpHeaders.WWW_AUTHENTICATE, "Digest realm=\"realm1\", nonce=\"1234\"")); @@ -266,7 +263,7 @@ public class TestHttpAuthenticator { @Test public void testAuthenticationFailedPreviously() throws Exception { final HttpHost host = new HttpHost("somehost", 80); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); response.addHeader(new BasicHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"test\"")); response.addHeader(new BasicHeader(HttpHeaders.WWW_AUTHENTICATE, "Digest realm=\"realm1\", nonce=\"1234\"")); @@ -283,7 +280,7 @@ public class TestHttpAuthenticator { @Test public void testAuthenticationFailure() throws Exception { final HttpHost host = new HttpHost("somehost", 80); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); response.addHeader(new BasicHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"test\"")); response.addHeader(new BasicHeader(HttpHeaders.WWW_AUTHENTICATE, "Digest realm=\"realm1\", nonce=\"1234\"")); response.addHeader(new BasicHeader(HttpHeaders.WWW_AUTHENTICATE, "whatever realm=\"realm1\", stuff=\"1234\"")); @@ -301,7 +298,7 @@ public class TestHttpAuthenticator { @Test public void testAuthenticationHandshaking() throws Exception { final HttpHost host = new HttpHost("somehost", 80); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); response.addHeader(new BasicHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"test\"")); response.addHeader(new BasicHeader(HttpHeaders.WWW_AUTHENTICATE, "Digest realm=\"realm1\", stale=true, nonce=\"1234\"")); response.addHeader(new BasicHeader(HttpHeaders.WWW_AUTHENTICATE, "whatever realm=\"realm1\", stuff=\"1234\"")); @@ -320,7 +317,7 @@ public class TestHttpAuthenticator { @Test public void testAuthenticationNoMatchingChallenge() throws Exception { final HttpHost host = new HttpHost("somehost", 80); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); response.addHeader(new BasicHeader(HttpHeaders.WWW_AUTHENTICATE, "Digest realm=\"realm1\", nonce=\"1234\"")); response.addHeader(new BasicHeader(HttpHeaders.WWW_AUTHENTICATE, "whatever realm=\"realm1\", stuff=\"1234\"")); @@ -348,7 +345,7 @@ public class TestHttpAuthenticator { @Test public void testAuthenticationException() throws Exception { final HttpHost host = new HttpHost("somehost", 80); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); response.addHeader(new BasicHeader(HttpHeaders.WWW_AUTHENTICATE, "blah blah blah")); this.authExchange.setState(AuthExchange.State.CHALLENGED); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/auth/TestRequestAuthCache.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/auth/TestRequestAuthCache.java index bda81f1e8..0052705a9 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/auth/TestRequestAuthCache.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/auth/TestRequestAuthCache.java @@ -39,7 +39,6 @@ import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.HttpRequestInterceptor; import org.apache.hc.core5.http.message.BasicHttpRequest; -import org.apache.hc.core5.http.protocol.HttpCoreContext; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -77,14 +76,14 @@ public class TestRequestAuthCache { public void testRequestParameterCheck() throws Exception { final HttpClientContext context = HttpClientContext.create(); final HttpRequestInterceptor interceptor = new RequestAuthCache(); - interceptor.process(null, context); + interceptor.process(null, null, context); } @Test(expected=IllegalArgumentException.class) public void testContextParameterCheck() throws Exception { final HttpRequest request = new BasicHttpRequest("GET", "/"); final HttpRequestInterceptor interceptor = new RequestAuthCache(); - interceptor.process(request, null); + interceptor.process(request, null, null); } @Test @@ -93,7 +92,6 @@ public class TestRequestAuthCache { final HttpClientContext context = HttpClientContext.create(); context.setAttribute(HttpClientContext.CREDS_PROVIDER, this.credProvider); - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target); context.setAttribute(HttpClientContext.HTTP_ROUTE, new HttpRoute(this.target, null, this.proxy, false)); final AuthCache authCache = new BasicAuthCache(); @@ -103,7 +101,7 @@ public class TestRequestAuthCache { context.setAttribute(HttpClientContext.AUTH_CACHE, authCache); final HttpRequestInterceptor interceptor = new RequestAuthCache(); - interceptor.process(request, context); + interceptor.process(request, null, context); final AuthExchange targetAuthExchange = context.getAuthExchange(this.target); final AuthExchange proxyAuthExchange = context.getAuthExchange(this.proxy); @@ -120,7 +118,6 @@ public class TestRequestAuthCache { final HttpClientContext context = HttpClientContext.create(); context.setAttribute(HttpClientContext.CREDS_PROVIDER, null); - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target); context.setAttribute(HttpClientContext.HTTP_ROUTE, new HttpRoute(this.target, null, this.proxy, false)); final AuthCache authCache = new BasicAuthCache(); @@ -130,7 +127,7 @@ public class TestRequestAuthCache { context.setAttribute(HttpClientContext.AUTH_CACHE, authCache); final HttpRequestInterceptor interceptor = new RequestAuthCache(); - interceptor.process(request, context); + interceptor.process(request, null, context); final AuthExchange targetAuthExchange = context.getAuthExchange(this.target); final AuthExchange proxyAuthExchange = context.getAuthExchange(this.proxy); @@ -147,12 +144,11 @@ public class TestRequestAuthCache { final HttpClientContext context = HttpClientContext.create(); context.setAttribute(HttpClientContext.CREDS_PROVIDER, this.credProvider); - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target); context.setAttribute(HttpClientContext.HTTP_ROUTE, new HttpRoute(this.target, null, this.proxy, false)); context.setAttribute(HttpClientContext.AUTH_CACHE, null); final HttpRequestInterceptor interceptor = new RequestAuthCache(); - interceptor.process(request, context); + interceptor.process(request, null, context); final AuthExchange targetAuthExchange = context.getAuthExchange(this.target); final AuthExchange proxyAuthExchange = context.getAuthExchange(this.proxy); @@ -169,14 +165,13 @@ public class TestRequestAuthCache { final HttpClientContext context = HttpClientContext.create(); context.setAttribute(HttpClientContext.CREDS_PROVIDER, this.credProvider); - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target); context.setAttribute(HttpClientContext.HTTP_ROUTE, new HttpRoute(this.target, null, this.proxy, false)); final AuthCache authCache = new BasicAuthCache(); context.setAttribute(HttpClientContext.AUTH_CACHE, authCache); final HttpRequestInterceptor interceptor = new RequestAuthCache(); - interceptor.process(request, context); + interceptor.process(request, null, context); final AuthExchange targetAuthExchange = context.getAuthExchange(this.target); final AuthExchange proxyAuthExchange = context.getAuthExchange(this.proxy); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/auth/TestSystemDefaultCredentialsProvider.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/auth/TestSystemDefaultCredentialsProvider.java index ee58305e1..8445b6156 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/auth/TestSystemDefaultCredentialsProvider.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/auth/TestSystemDefaultCredentialsProvider.java @@ -29,15 +29,12 @@ package org.apache.hc.client5.http.impl.auth; import java.net.Authenticator; import java.net.Authenticator.RequestorType; import java.net.InetAddress; -import java.net.MalformedURLException; import java.net.PasswordAuthentication; -import java.net.URISyntaxException; import java.net.URL; import org.apache.hc.client5.http.auth.AuthScope; import org.apache.hc.client5.http.auth.Credentials; import org.apache.hc.client5.http.methods.HttpGet; -import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.protocol.HttpCoreContext; import org.junit.Assert; import org.junit.Test; @@ -88,15 +85,13 @@ public class TestSystemDefaultCredentialsProvider { } @Test - public void testSystemCredentialsProviderCredentials() throws MalformedURLException, - URISyntaxException { + public void testSystemCredentialsProviderCredentials() throws Exception { final AuthenticatorDelegate authenticatorDelegate = installAuthenticator(AUTH1); - final URL httpRequestUrl = new URL(TARGET_SCHEME1, TARGET_HOST1, TARGET_PORT1, ""); + final URL httpRequestUrl = new URL(TARGET_SCHEME1, TARGET_HOST1, TARGET_PORT1, "/"); final AuthScope authScope = new AuthScope(PROXY_HOST1, PROXY_PORT1, PROMPT1, "BASIC"); final HttpCoreContext coreContext = new HttpCoreContext(); - coreContext.setTargetHost(new HttpHost(TARGET_HOST1, TARGET_PORT1, TARGET_SCHEME1)); coreContext.setAttribute(HttpCoreContext.HTTP_REQUEST, new HttpGet(httpRequestUrl.toURI())); final Credentials receivedCredentials = @@ -111,8 +106,7 @@ public class TestSystemDefaultCredentialsProvider { } @Test - public void testSystemCredentialsProviderNoContext() throws MalformedURLException, - URISyntaxException { + public void testSystemCredentialsProviderNoContext() throws Exception { final AuthenticatorDelegate authenticatorDelegate = installAuthenticator(AUTH1); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestAbortHandling.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestAbortHandling.java index 082e3b375..c73e2014f 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestAbortHandling.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestAbortHandling.java @@ -44,16 +44,16 @@ import org.apache.hc.client5.http.localserver.LocalServerTestBase; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.core5.concurrent.Cancellable; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpHost; 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.ProtocolVersion; -import org.apache.hc.core5.http.entity.StringEntity; import org.apache.hc.core5.http.io.HttpClientConnection; import org.apache.hc.core5.http.io.HttpRequestHandler; import org.apache.hc.core5.http.io.UriHttpRequestHandlerMapper; +import org.apache.hc.core5.http.io.entity.StringEntity; import org.apache.hc.core5.http.message.BasicHeader; import org.apache.hc.core5.http.protocol.BasicHttpContext; import org.apache.hc.core5.http.protocol.HttpContext; @@ -73,16 +73,18 @@ public class TestAbortHandling extends LocalServerTestBase { this.serverBootstrap.registerHandler("*", new HttpRequestHandler() { @Override - public void handle(final HttpRequest request, final HttpResponse response, - final HttpContext context) throws HttpException, IOException { + public void handle( + final ClassicHttpRequest request, + final ClassicHttpResponse response, + final HttpContext context) throws HttpException, IOException { try { wait.countDown(); // trigger abort Thread.sleep(2000); // allow time for abort to happen - response.setStatusCode(HttpStatus.SC_OK); + response.setCode(HttpStatus.SC_OK); final StringEntity entity = new StringEntity("Whatever"); response.setEntity(entity); } catch (final Exception e) { - response.setStatusCode(HttpStatus.SC_REQUEST_TIMEOUT); + response.setCode(HttpStatus.SC_REQUEST_TIMEOUT); } } }); @@ -316,10 +318,11 @@ public class TestAbortHandling extends LocalServerTestBase { private static class BasicService implements HttpRequestHandler { @Override - public void handle(final HttpRequest request, - final HttpResponse response, + public void handle( + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { - response.setStatusCode(200); + response.setCode(200); response.setEntity(new StringEntity("Hello World")); } } @@ -333,11 +336,11 @@ public class TestAbortHandling extends LocalServerTestBase { } @Override - public void handle(final HttpRequest request, - final HttpResponse response, final HttpContext context) - throws HttpException, IOException { - final ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); - response.setStatusLine(ver, this.statuscode); + public void handle( + final ClassicHttpRequest request, + final ClassicHttpResponse response, + final HttpContext context) throws HttpException, IOException { + response.setCode(this.statuscode); response.addHeader(new BasicHeader("Location", "http://localhost:" + this.port + "/newlocation/")); response.addHeader(new BasicHeader("Connection", "close")); @@ -400,12 +403,12 @@ public class TestAbortHandling extends LocalServerTestBase { } @Override - public void closeIdleConnections(final long idletime, final TimeUnit tunit) { + public void closeIdle(final long idletime, final TimeUnit tunit) { throw new UnsupportedOperationException("just a mockup"); } @Override - public void closeExpiredConnections() { + public void closeExpired() { throw new UnsupportedOperationException("just a mockup"); } diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestBasicConnectionManager.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestBasicConnectionManager.java index 727bdf10d..1b41e55df 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestBasicConnectionManager.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestBasicConnectionManager.java @@ -28,10 +28,10 @@ package org.apache.hc.client5.http.impl.integration; import org.apache.hc.client5.http.impl.io.BasicHttpClientConnectionManager; import org.apache.hc.client5.http.localserver.LocalServerTestBase; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.sync.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.core5.http.HttpHost; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.EntityUtils; import org.junit.Assert; import org.junit.Test; @@ -44,7 +44,7 @@ public class TestBasicConnectionManager extends LocalServerTestBase { final HttpHost target = start(); final HttpGet get = new HttpGet("/random/1024"); try (CloseableHttpResponse response = this.httpclient.execute(target, get)) { - Assert.assertEquals(200, response.getStatusLine().getStatusCode()); + Assert.assertEquals(200, response.getCode()); EntityUtils.consume(response.getEntity()); } } diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestClientAuthentication.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestClientAuthentication.java index d44cd5528..6945a47b0 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestClientAuthentication.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestClientAuthentication.java @@ -57,29 +57,25 @@ import org.apache.hc.client5.http.methods.HttpPut; import org.apache.hc.client5.http.protocol.ClientProtocolException; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.protocol.NonRepeatableRequestException; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HeaderElements; import org.apache.hc.core5.http.HttpConnection; import org.apache.hc.core5.http.HttpEntity; 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.HttpResponse; import org.apache.hc.core5.http.HttpStatus; -import org.apache.hc.core5.http.entity.EntityUtils; -import org.apache.hc.core5.http.entity.InputStreamEntity; -import org.apache.hc.core5.http.entity.StringEntity; +import org.apache.hc.core5.http.impl.HttpProcessors; +import org.apache.hc.core5.http.io.HttpExpectationVerifier; import org.apache.hc.core5.http.io.HttpRequestHandler; +import org.apache.hc.core5.http.io.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.InputStreamEntity; +import org.apache.hc.core5.http.io.entity.StringEntity; import org.apache.hc.core5.http.message.BasicHeader; import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.http.protocol.HttpCoreContext; -import org.apache.hc.core5.http.protocol.HttpExpectationVerifier; import org.apache.hc.core5.http.protocol.HttpProcessor; -import org.apache.hc.core5.http.protocol.HttpProcessorBuilder; -import org.apache.hc.core5.http.protocol.ResponseConnControl; -import org.apache.hc.core5.http.protocol.ResponseContent; -import org.apache.hc.core5.http.protocol.ResponseDate; -import org.apache.hc.core5.http.protocol.ResponseServer; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -92,11 +88,7 @@ public class TestClientAuthentication extends LocalServerTestBase { @Before @Override public void setUp() throws Exception { super.setUp(); - final HttpProcessor httpproc = HttpProcessorBuilder.create() - .add(new ResponseDate()) - .add(new ResponseServer(LocalServerTestBase.ORIGIN)) - .add(new ResponseContent()) - .add(new ResponseConnControl()) + final HttpProcessor httpproc = HttpProcessors.customServer(null) .add(new RequestBasicAuth()) .add(new ResponseBasicUnauthorized()).build(); this.serverBootstrap.setHttpProcessor(httpproc); @@ -106,14 +98,14 @@ public class TestClientAuthentication extends LocalServerTestBase { @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { final String creds = (String) context.getAttribute("creds"); if (creds == null || !creds.equals("test:test")) { - response.setStatusCode(HttpStatus.SC_UNAUTHORIZED); + response.setCode(HttpStatus.SC_UNAUTHORIZED); } else { - response.setStatusCode(HttpStatus.SC_OK); + response.setCode(HttpStatus.SC_OK); final StringEntity entity = new StringEntity("success", StandardCharsets.US_ASCII); response.setEntity(entity); } @@ -132,14 +124,14 @@ public class TestClientAuthentication extends LocalServerTestBase { @Override public void verify( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException { final String creds = this.authTokenExtractor.extract(request); if (creds == null || !creds.equals("test:test")) { - response.setStatusCode(HttpStatus.SC_UNAUTHORIZED); + response.setCode(HttpStatus.SC_UNAUTHORIZED); } else { - response.setStatusCode(HttpStatus.SC_CONTINUE); + response.setCode(HttpStatus.SC_CONTINUE); } } @@ -178,9 +170,9 @@ public class TestClientAuthentication extends LocalServerTestBase { context.setCredentialsProvider(credsProvider); final HttpGet httpget = new HttpGet("/"); - final HttpResponse response = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context); final HttpEntity entity = response.getEntity(); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode()); Assert.assertNotNull(entity); EntityUtils.consume(entity); final AuthScope authscope = credsProvider.getAuthScope(); @@ -200,9 +192,9 @@ public class TestClientAuthentication extends LocalServerTestBase { context.setCredentialsProvider(credsProvider); final HttpGet httpget = new HttpGet("/"); - final HttpResponse response = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context); final HttpEntity entity = response.getEntity(); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode()); Assert.assertNotNull(entity); EntityUtils.consume(entity); final AuthScope authscope = credsProvider.getAuthScope(); @@ -222,9 +214,9 @@ public class TestClientAuthentication extends LocalServerTestBase { final HttpHost target = start(); - final HttpResponse response = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context); final HttpEntity entity = response.getEntity(); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_OK, response.getCode()); Assert.assertNotNull(entity); EntityUtils.consume(entity); final AuthScope authscope = credsProvider.getAuthScope(); @@ -234,11 +226,7 @@ public class TestClientAuthentication extends LocalServerTestBase { @Test public void testBasicAuthenticationSuccessOnNonRepeatablePutExpectContinue() throws Exception { - final HttpProcessor httpproc = HttpProcessorBuilder.create() - .add(new ResponseDate()) - .add(new ResponseServer(LocalServerTestBase.ORIGIN)) - .add(new ResponseContent()) - .add(new ResponseConnControl()) + final HttpProcessor httpproc = HttpProcessors.customServer(null) .add(new RequestBasicAuth()) .add(new ResponseBasicUnauthorized()).build(); this.serverBootstrap.setHttpProcessor(httpproc) @@ -261,9 +249,9 @@ public class TestClientAuthentication extends LocalServerTestBase { new UsernamePasswordCredentials("test", "test".toCharArray())); context.setCredentialsProvider(credsProvider); - final HttpResponse response = this.httpclient.execute(target, httpput, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httpput, context); final HttpEntity entity = response.getEntity(); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_OK, response.getCode()); Assert.assertNotNull(entity); } @@ -311,9 +299,9 @@ public class TestClientAuthentication extends LocalServerTestBase { new UsernamePasswordCredentials("test", "test".toCharArray())); context.setCredentialsProvider(credsProvider); - final HttpResponse response = this.httpclient.execute(target, httppost, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httppost, context); final HttpEntity entity = response.getEntity(); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_OK, response.getCode()); Assert.assertNotNull(entity); EntityUtils.consume(entity); final AuthScope authscope = credsProvider.getAuthScope(); @@ -390,15 +378,15 @@ public class TestClientAuthentication extends LocalServerTestBase { final HttpGet httpget = new HttpGet("/"); - final HttpResponse response1 = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response1 = this.httpclient.execute(target, httpget, context); final HttpEntity entity1 = response1.getEntity(); - Assert.assertEquals(HttpStatus.SC_OK, response1.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_OK, response1.getCode()); Assert.assertNotNull(entity1); EntityUtils.consume(entity1); - final HttpResponse response2 = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response2 = this.httpclient.execute(target, httpget, context); final HttpEntity entity2 = response1.getEntity(); - Assert.assertEquals(HttpStatus.SC_OK, response2.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_OK, response2.getCode()); Assert.assertNotNull(entity2); EntityUtils.consume(entity2); @@ -417,15 +405,15 @@ public class TestClientAuthentication extends LocalServerTestBase { @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { final String givenCreds = (String) context.getAttribute("creds"); if (givenCreds == null || !givenCreds.equals(this.realmCreds)) { - response.setStatusCode(HttpStatus.SC_UNAUTHORIZED); + response.setCode(HttpStatus.SC_UNAUTHORIZED); response.addHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"" + this.realm + "\""); } else { - response.setStatusCode(HttpStatus.SC_OK); + response.setCode(HttpStatus.SC_OK); final StringEntity entity = new StringEntity("success", StandardCharsets.US_ASCII); response.setEntity(entity); } @@ -458,25 +446,25 @@ public class TestClientAuthentication extends LocalServerTestBase { final HttpGet httpget1 = new HttpGet("/this"); - final HttpResponse response1 = this.httpclient.execute(target, httpget1, context); + final ClassicHttpResponse response1 = this.httpclient.execute(target, httpget1, context); final HttpEntity entity1 = response1.getEntity(); - Assert.assertEquals(HttpStatus.SC_OK, response1.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_OK, response1.getCode()); Assert.assertNotNull(entity1); EntityUtils.consume(entity1); final HttpGet httpget2 = new HttpGet("/this"); - final HttpResponse response2 = this.httpclient.execute(target, httpget2, context); + final ClassicHttpResponse response2 = this.httpclient.execute(target, httpget2, context); final HttpEntity entity2 = response1.getEntity(); - Assert.assertEquals(HttpStatus.SC_OK, response2.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_OK, response2.getCode()); Assert.assertNotNull(entity2); EntityUtils.consume(entity2); final HttpGet httpget3 = new HttpGet("/that"); - final HttpResponse response3 = this.httpclient.execute(target, httpget3, context); + final ClassicHttpResponse response3 = this.httpclient.execute(target, httpget3, context); final HttpEntity entity3 = response1.getEntity(); - Assert.assertEquals(HttpStatus.SC_OK, response3.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_OK, response3.getCode()); Assert.assertNotNull(entity3); EntityUtils.consume(entity3); @@ -491,9 +479,9 @@ public class TestClientAuthentication extends LocalServerTestBase { final HttpGet httpget = new HttpGet("http://test:test@" + target.toHostString() + "/"); final HttpClientContext context = HttpClientContext.create(); - final HttpResponse response = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context); final HttpEntity entity = response.getEntity(); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_OK, response.getCode()); Assert.assertNotNull(entity); EntityUtils.consume(entity); } @@ -506,9 +494,9 @@ public class TestClientAuthentication extends LocalServerTestBase { final HttpGet httpget = new HttpGet("http://test:all-wrong@" + target.toHostString() + "/"); final HttpClientContext context = HttpClientContext.create(); - final HttpResponse response = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context); final HttpEntity entity = response.getEntity(); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode()); Assert.assertNotNull(entity); EntityUtils.consume(entity); } @@ -521,14 +509,14 @@ public class TestClientAuthentication extends LocalServerTestBase { @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { final HttpConnection conn = (HttpConnection) context.getAttribute(HttpCoreContext.HTTP_CONNECTION); final InetSocketAddress socketAddress = (InetSocketAddress) conn.getLocalAddress(); final String localhost = socketAddress.getHostName(); final int port = socketAddress.getPort(); - response.setStatusCode(HttpStatus.SC_MOVED_PERMANENTLY); + response.setCode(HttpStatus.SC_MOVED_PERMANENTLY); response.addHeader(new BasicHeader("Location", "http://test:test@" + localhost + ":" + port + "/")); } @@ -545,9 +533,9 @@ public class TestClientAuthentication extends LocalServerTestBase { final HttpGet httpget = new HttpGet("http://" + target.toHostString() + "/thatway"); final HttpClientContext context = HttpClientContext.create(); - final HttpResponse response = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context); final HttpEntity entity = response.getEntity(); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_OK, response.getCode()); Assert.assertNotNull(entity); EntityUtils.consume(entity); } @@ -563,15 +551,15 @@ public class TestClientAuthentication extends LocalServerTestBase { @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { this.count.incrementAndGet(); final String creds = (String) context.getAttribute("creds"); if (creds == null || !creds.equals("test:test")) { - response.setStatusCode(HttpStatus.SC_UNAUTHORIZED); + response.setCode(HttpStatus.SC_UNAUTHORIZED); } else { - response.setStatusCode(HttpStatus.SC_OK); + response.setCode(HttpStatus.SC_OK); final StringEntity entity = new StringEntity("success", StandardCharsets.US_ASCII); response.setEntity(entity); } @@ -598,9 +586,9 @@ public class TestClientAuthentication extends LocalServerTestBase { context.setAuthCache(authCache); final HttpGet httpget = new HttpGet("/"); - final HttpResponse response1 = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response1 = this.httpclient.execute(target, httpget, context); final HttpEntity entity1 = response1.getEntity(); - Assert.assertEquals(HttpStatus.SC_OK, response1.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_OK, response1.getCode()); Assert.assertNotNull(entity1); EntityUtils.consume(entity1); @@ -624,9 +612,9 @@ public class TestClientAuthentication extends LocalServerTestBase { context.setCredentialsProvider(credsProvider); final HttpGet httpget = new HttpGet("/"); - final HttpResponse response1 = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response1 = this.httpclient.execute(target, httpget, context); final HttpEntity entity1 = response1.getEntity(); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response1.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response1.getCode()); Assert.assertNotNull(entity1); EntityUtils.consume(entity1); @@ -637,14 +625,14 @@ public class TestClientAuthentication extends LocalServerTestBase { @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { final String creds = (String) context.getAttribute("creds"); if (creds == null || !creds.equals("test:test")) { - response.setStatusCode(HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED); + response.setCode(HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED); } else { - response.setStatusCode(HttpStatus.SC_OK); + response.setCode(HttpStatus.SC_OK); final StringEntity entity = new StringEntity("success", StandardCharsets.US_ASCII); response.setEntity(entity); } @@ -663,10 +651,10 @@ public class TestClientAuthentication extends LocalServerTestBase { context.setCredentialsProvider(credsProvider); final HttpGet httpget = new HttpGet("/"); - final HttpResponse response = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context); final HttpEntity entity = response.getEntity(); Assert.assertEquals(HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED, - response.getStatusLine().getStatusCode()); + response.getCode()); EntityUtils.consume(entity); } @@ -674,14 +662,14 @@ public class TestClientAuthentication extends LocalServerTestBase { @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { final String creds = (String) context.getAttribute("creds"); if (creds == null || !creds.equals("test:test")) { - response.setStatusCode(HttpStatus.SC_UNAUTHORIZED); + response.setCode(HttpStatus.SC_UNAUTHORIZED); } else { - response.setStatusCode(HttpStatus.SC_OK); + response.setCode(HttpStatus.SC_OK); final StringEntity entity = new StringEntity("success", StandardCharsets.US_ASCII); response.setEntity(entity); response.setHeader(HttpHeaders.CONNECTION, HeaderElements.CLOSE); @@ -705,9 +693,9 @@ public class TestClientAuthentication extends LocalServerTestBase { for (int i = 0; i < 2; i++) { final HttpGet httpget = new HttpGet("/"); - final HttpResponse response = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context); EntityUtils.consume(response.getEntity()); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_OK, response.getCode()); } } diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestClientAuthenticationFakeNTLM.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestClientAuthenticationFakeNTLM.java index 761f1bb61..fa0786fa6 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestClientAuthenticationFakeNTLM.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestClientAuthenticationFakeNTLM.java @@ -35,16 +35,14 @@ import org.apache.hc.client5.http.impl.sync.HttpClients; import org.apache.hc.client5.http.localserver.LocalServerTestBase; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.client5.http.protocol.HttpClientContext; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; 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.HttpResponse; import org.apache.hc.core5.http.HttpStatus; -import org.apache.hc.core5.http.HttpVersion; -import org.apache.hc.core5.http.entity.EntityUtils; import org.apache.hc.core5.http.io.HttpRequestHandler; -import org.apache.hc.core5.http.message.BasicStatusLine; +import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.http.protocol.HttpContext; import org.junit.Assert; import org.junit.Test; @@ -58,13 +56,10 @@ public class TestClientAuthenticationFakeNTLM extends LocalServerTestBase { @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { - response.setStatusLine(new BasicStatusLine( - HttpVersion.HTTP_1_1, - HttpStatus.SC_UNAUTHORIZED, - "Authentication Required")); + response.setCode(HttpStatus.SC_UNAUTHORIZED); response.setHeader("Connection", "Keep-Alive"); response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "NTLM"); } @@ -87,10 +82,10 @@ public class TestClientAuthenticationFakeNTLM extends LocalServerTestBase { final HttpContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("/"); - final HttpResponse response = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context); EntityUtils.consume(response.getEntity()); Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, - response.getStatusLine().getStatusCode()); + response.getCode()); } static class NtlmType2MessageResponseHandler implements HttpRequestHandler { @@ -103,13 +98,10 @@ public class TestClientAuthenticationFakeNTLM extends LocalServerTestBase { @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { - response.setStatusLine(new BasicStatusLine( - HttpVersion.HTTP_1_1, - HttpStatus.SC_UNAUTHORIZED, - "Authentication Required")); + response.setCode(HttpStatus.SC_UNAUTHORIZED); response.setHeader("Connection", "Keep-Alive"); if (!request.containsHeader(HttpHeaders.AUTHORIZATION)) { response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "NTLM"); @@ -137,10 +129,10 @@ public class TestClientAuthenticationFakeNTLM extends LocalServerTestBase { final HttpContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("/"); - final HttpResponse response = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context); EntityUtils.consume(response.getEntity()); Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, - response.getStatusLine().getStatusCode()); + response.getCode()); } @Test @@ -161,10 +153,10 @@ public class TestClientAuthenticationFakeNTLM extends LocalServerTestBase { final HttpContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("/"); - final HttpResponse response = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context); EntityUtils.consume(response.getEntity()); Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, - response.getStatusLine().getStatusCode()); + response.getCode()); } static class NtlmType2MessageOnlyResponseHandler implements HttpRequestHandler { @@ -177,13 +169,10 @@ public class TestClientAuthenticationFakeNTLM extends LocalServerTestBase { @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { - response.setStatusLine(new BasicStatusLine( - HttpVersion.HTTP_1_1, - HttpStatus.SC_UNAUTHORIZED, - "Authentication Required")); + response.setCode(HttpStatus.SC_UNAUTHORIZED); response.setHeader("Connection", "Keep-Alive"); response.setHeader(HttpHeaders.WWW_AUTHENTICATE, authenticateHeaderValue); } @@ -204,10 +193,10 @@ public class TestClientAuthenticationFakeNTLM extends LocalServerTestBase { context.setCredentialsProvider(credsProvider); final HttpGet httpget = new HttpGet("/"); - final HttpResponse response = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context); EntityUtils.consume(response.getEntity()); Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, - response.getStatusLine().getStatusCode()); + response.getCode()); } @Test @@ -225,10 +214,10 @@ public class TestClientAuthenticationFakeNTLM extends LocalServerTestBase { context.setCredentialsProvider(credsProvider); final HttpGet httpget = new HttpGet("/"); - final HttpResponse response = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context); EntityUtils.consume(response.getEntity()); Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, - response.getStatusLine().getStatusCode()); + response.getCode()); } } diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestClientAuthenticationFallBack.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestClientAuthenticationFallBack.java index d95ffa3ec..0c8f9222d 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestClientAuthenticationFallBack.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestClientAuthenticationFallBack.java @@ -37,24 +37,22 @@ import org.apache.hc.client5.http.localserver.LocalServerTestBase; import org.apache.hc.client5.http.localserver.RequestBasicAuth; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.client5.http.protocol.HttpClientContext; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; +import org.apache.hc.core5.http.EntityDetails; import org.apache.hc.core5.http.HttpEntity; 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.HttpResponse; import org.apache.hc.core5.http.HttpResponseInterceptor; import org.apache.hc.core5.http.HttpStatus; -import org.apache.hc.core5.http.entity.EntityUtils; -import org.apache.hc.core5.http.entity.StringEntity; +import org.apache.hc.core5.http.impl.HttpProcessors; import org.apache.hc.core5.http.io.HttpRequestHandler; +import org.apache.hc.core5.http.io.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.StringEntity; import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.http.protocol.HttpProcessor; -import org.apache.hc.core5.http.protocol.HttpProcessorBuilder; -import org.apache.hc.core5.http.protocol.ResponseConnControl; -import org.apache.hc.core5.http.protocol.ResponseContent; -import org.apache.hc.core5.http.protocol.ResponseDate; -import org.apache.hc.core5.http.protocol.ResponseServer; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -66,8 +64,9 @@ public class TestClientAuthenticationFallBack extends LocalServerTestBase { @Override public void process( final HttpResponse response, + final EntityDetails entityDetails, final HttpContext context) throws HttpException, IOException { - if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { + if (response.getCode() == HttpStatus.SC_UNAUTHORIZED) { response.addHeader(HttpHeaders.WWW_AUTHENTICATE, "Digest realm=\"test realm\" invalid"); response.addHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"test realm\""); } @@ -78,11 +77,7 @@ public class TestClientAuthenticationFallBack extends LocalServerTestBase { @Before @Override public void setUp() throws Exception { super.setUp(); - final HttpProcessor httpproc = HttpProcessorBuilder.create() - .add(new ResponseDate()) - .add(new ResponseServer(LocalServerTestBase.ORIGIN)) - .add(new ResponseContent()) - .add(new ResponseConnControl()) + final HttpProcessor httpproc = HttpProcessors.customServer(null) .add(new RequestBasicAuth()) .add(new ResponseBasicUnauthorized()).build(); this.serverBootstrap.setHttpProcessor(httpproc); @@ -92,14 +87,14 @@ public class TestClientAuthenticationFallBack extends LocalServerTestBase { @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { final String creds = (String) context.getAttribute("creds"); if (creds == null || !creds.equals("test:test")) { - response.setStatusCode(HttpStatus.SC_UNAUTHORIZED); + response.setCode(HttpStatus.SC_UNAUTHORIZED); } else { - response.setStatusCode(HttpStatus.SC_OK); + response.setCode(HttpStatus.SC_OK); final StringEntity entity = new StringEntity("success", StandardCharsets.US_ASCII); response.setEntity(entity); } @@ -141,9 +136,9 @@ public class TestClientAuthenticationFallBack extends LocalServerTestBase { context.setCredentialsProvider(credsProvider); final HttpGet httpget = new HttpGet("/"); - final HttpResponse response = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context); final HttpEntity entity = response.getEntity(); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_OK, response.getCode()); Assert.assertNotNull(entity); EntityUtils.consume(entity); final AuthScope authscope = credsProvider.getAuthScope(); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestClientReauthentication.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestClientReauthentication.java index 31db7ea71..096ee8ec4 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestClientReauthentication.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestClientReauthentication.java @@ -42,29 +42,27 @@ import org.apache.hc.client5.http.impl.auth.BasicScheme; import org.apache.hc.client5.http.impl.auth.BasicSchemeFactory; import org.apache.hc.client5.http.localserver.LocalServerTestBase; import org.apache.hc.client5.http.localserver.RequestBasicAuth; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.sync.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.client5.http.protocol.HttpClientContext; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; +import org.apache.hc.core5.http.EntityDetails; import org.apache.hc.core5.http.HttpEntity; 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.HttpResponse; import org.apache.hc.core5.http.HttpResponseInterceptor; import org.apache.hc.core5.http.HttpStatus; import org.apache.hc.core5.http.config.Registry; import org.apache.hc.core5.http.config.RegistryBuilder; -import org.apache.hc.core5.http.entity.EntityUtils; -import org.apache.hc.core5.http.entity.StringEntity; +import org.apache.hc.core5.http.impl.HttpProcessors; import org.apache.hc.core5.http.io.HttpRequestHandler; +import org.apache.hc.core5.http.io.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.StringEntity; import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.http.protocol.HttpProcessor; -import org.apache.hc.core5.http.protocol.HttpProcessorBuilder; -import org.apache.hc.core5.http.protocol.ResponseConnControl; -import org.apache.hc.core5.http.protocol.ResponseContent; -import org.apache.hc.core5.http.protocol.ResponseDate; -import org.apache.hc.core5.http.protocol.ResponseServer; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -76,8 +74,9 @@ public class TestClientReauthentication extends LocalServerTestBase { @Override public void process( final HttpResponse response, + final EntityDetails entityDetails, final HttpContext context) throws HttpException, IOException { - if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { + if (response.getCode() == HttpStatus.SC_UNAUTHORIZED) { response.addHeader(HttpHeaders.WWW_AUTHENTICATE, "MyBasic realm=\"test realm\""); } } @@ -87,11 +86,7 @@ public class TestClientReauthentication extends LocalServerTestBase { @Before @Override public void setUp() throws Exception { super.setUp(); - final HttpProcessor httpproc = HttpProcessorBuilder.create() - .add(new ResponseDate()) - .add(new ResponseServer(LocalServerTestBase.ORIGIN)) - .add(new ResponseContent()) - .add(new ResponseConnControl()) + final HttpProcessor httpproc = HttpProcessors.customServer(null) .add(new RequestBasicAuth()) .add(new ResponseBasicUnauthorized()).build(); this.serverBootstrap.setHttpProcessor(httpproc); @@ -103,18 +98,18 @@ public class TestClientReauthentication extends LocalServerTestBase { @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { final String creds = (String) context.getAttribute("creds"); if (creds == null || !creds.equals("test:test")) { - response.setStatusCode(HttpStatus.SC_UNAUTHORIZED); + response.setCode(HttpStatus.SC_UNAUTHORIZED); } else { // Make client re-authenticate on each fourth request if (this.count.incrementAndGet() % 4 == 0) { - response.setStatusCode(HttpStatus.SC_UNAUTHORIZED); + response.setCode(HttpStatus.SC_UNAUTHORIZED); } else { - response.setStatusCode(HttpStatus.SC_OK); + response.setCode(HttpStatus.SC_OK); final StringEntity entity = new StringEntity("success", StandardCharsets.US_ASCII); response.setEntity(entity); } @@ -184,7 +179,7 @@ public class TestClientReauthentication extends LocalServerTestBase { httpget.setConfig(config); try (final CloseableHttpResponse response = this.httpclient.execute(target, httpget, context)) { final HttpEntity entity = response.getEntity(); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_OK, response.getCode()); Assert.assertNotNull(entity); EntityUtils.consume(entity); } diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestClientRequestExecution.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestClientRequestExecution.java index 1aa96da08..cf0a66bc0 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestClientRequestExecution.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestClientRequestExecution.java @@ -38,23 +38,25 @@ import org.apache.hc.client5.http.protocol.ClientProtocolException; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.protocol.NonRepeatableRequestException; import org.apache.hc.client5.http.sync.HttpRequestRetryHandler; -import org.apache.hc.client5.http.utils.URIBuilder; import org.apache.hc.client5.http.utils.URIUtils; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; +import org.apache.hc.core5.http.EntityDetails; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.HttpRequestInterceptor; -import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.HttpStatus; -import org.apache.hc.core5.http.entity.EntityUtils; -import org.apache.hc.core5.http.entity.InputStreamEntity; -import org.apache.hc.core5.http.entity.StringEntity; import org.apache.hc.core5.http.impl.io.HttpRequestExecutor; import org.apache.hc.core5.http.io.HttpClientConnection; import org.apache.hc.core5.http.io.HttpRequestHandler; -import org.apache.hc.core5.http.message.BasicHttpRequest; +import org.apache.hc.core5.http.io.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.InputStreamEntity; +import org.apache.hc.core5.http.io.entity.StringEntity; +import org.apache.hc.core5.http.message.BasicClassicHttpRequest; import org.apache.hc.core5.http.protocol.HttpContext; +import org.apache.hc.core5.net.URIBuilder; import org.junit.Assert; import org.junit.Test; @@ -71,10 +73,10 @@ public class TestClientRequestExecution extends LocalServerTestBase { @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { - response.setStatusCode(HttpStatus.SC_OK); + response.setCode(HttpStatus.SC_OK); final StringEntity entity = new StringEntity("Whatever"); response.setEntity(entity); } @@ -91,12 +93,12 @@ public class TestClientRequestExecution extends LocalServerTestBase { } @Override - public HttpResponse execute( - final HttpRequest request, + public ClassicHttpResponse execute( + final ClassicHttpRequest request, final HttpClientConnection conn, final HttpContext context) throws IOException, HttpException { - final HttpResponse response = super.execute(request, conn, context); + final ClassicHttpResponse response = super.execute(request, conn, context); final Object marker = context.getAttribute(MARKER); if (marker == null) { context.setAttribute(MARKER, Boolean.TRUE); @@ -116,6 +118,7 @@ public class TestClientRequestExecution extends LocalServerTestBase { @Override public void process( final HttpRequest request, + final EntityDetails entityDetails, final HttpContext context) throws HttpException, IOException { request.addHeader("my-header", "stuff"); } @@ -147,12 +150,12 @@ public class TestClientRequestExecution extends LocalServerTestBase { final HttpGet httpget = new HttpGet("/"); - final HttpResponse response = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context); EntityUtils.consume(response.getEntity()); final HttpRequest reqWrapper = context.getRequest(); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_OK, response.getCode()); final Header[] myheaders = reqWrapper.getHeaders("my-header"); Assert.assertNotNull(myheaders); @@ -209,15 +212,15 @@ public class TestClientRequestExecution extends LocalServerTestBase { final HttpHost target = start(); final HttpClientContext context = HttpClientContext.create(); - final BasicHttpRequest request = new BasicHttpRequest("GET", "blah.:.blah.:."); - final HttpResponse response = this.httpclient.execute(target, request, context); + final ClassicHttpRequest request = new BasicClassicHttpRequest("GET", "blah.:.blah.:."); + final ClassicHttpResponse response = this.httpclient.execute(target, request, context); EntityUtils.consume(response.getEntity()); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_OK, response.getCode()); final HttpRequest reqWrapper = context.getRequest(); - Assert.assertEquals("blah.:.blah.:.", reqWrapper.getRequestLine().getUri()); + Assert.assertEquals("blah.:.blah.:.", reqWrapper.getRequestUri()); } @Test @@ -229,12 +232,12 @@ public class TestClientRequestExecution extends LocalServerTestBase { final HttpGet httpget = new HttpGet("/stuff#blahblah"); final HttpClientContext context = HttpClientContext.create(); - final HttpResponse response = this.httpclient.execute(target, httpget, context); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context); + Assert.assertEquals(HttpStatus.SC_OK, response.getCode()); EntityUtils.consume(response.getEntity()); final HttpRequest request = context.getRequest(); - Assert.assertEquals("/stuff", request.getRequestLine().getUri()); + Assert.assertEquals("/stuff", request.getRequestUri()); } @Test @@ -254,12 +257,12 @@ public class TestClientRequestExecution extends LocalServerTestBase { final HttpGet httpget = new HttpGet(uri); final HttpClientContext context = HttpClientContext.create(); - final HttpResponse response = this.httpclient.execute(httpget, context); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + final ClassicHttpResponse response = this.httpclient.execute(httpget, context); + Assert.assertEquals(HttpStatus.SC_OK, response.getCode()); EntityUtils.consume(response.getEntity()); final HttpRequest request = context.getRequest(); - Assert.assertEquals("/stuff", request.getRequestLine().getUri()); + Assert.assertEquals("/stuff", request.getRequestUri()); final List redirectLocations = context.getRedirectLocations(); final URI location = URIUtils.resolve(uri, target, redirectLocations); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestConnectionAutoRelease.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestConnectionAutoRelease.java index 0026c2f95..327c8c79a 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestConnectionAutoRelease.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestConnectionAutoRelease.java @@ -37,17 +37,17 @@ import org.apache.hc.client5.http.HttpRoute; import org.apache.hc.client5.http.io.ConnectionRequest; import org.apache.hc.client5.http.localserver.LocalServerTestBase; import org.apache.hc.client5.http.methods.HttpGet; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpHost; -import org.apache.hc.core5.http.HttpRequest; -import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.MalformedChunkCodingException; -import org.apache.hc.core5.http.entity.BasicHttpEntity; -import org.apache.hc.core5.http.entity.EntityUtils; import org.apache.hc.core5.http.impl.io.DefaultBHttpServerConnection; import org.apache.hc.core5.http.io.HttpClientConnection; import org.apache.hc.core5.http.io.HttpRequestHandler; +import org.apache.hc.core5.http.io.entity.BasicHttpEntity; +import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.http.protocol.HttpCoreContext; import org.apache.hc.core5.pool.PoolStats; @@ -68,7 +68,7 @@ public class TestConnectionAutoRelease extends LocalServerTestBase { final HttpHost target = start(); // Get some random data final HttpGet httpget = new HttpGet("/random/20000"); - final HttpResponse response = this.httpclient.execute(target, httpget); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget); ConnectionRequest connreq = this.connManager.requestConnection(new HttpRoute(target), null); try { @@ -104,7 +104,7 @@ public class TestConnectionAutoRelease extends LocalServerTestBase { final HttpHost target = start(); // Get some random data final HttpGet httpget = new HttpGet("/random/20000"); - final HttpResponse response = this.httpclient.execute(target, httpget); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget); ConnectionRequest connreq = this.connManager.requestConnection(new HttpRoute(target), null); try { @@ -142,7 +142,7 @@ public class TestConnectionAutoRelease extends LocalServerTestBase { // Get some random data final HttpGet httpget = new HttpGet("/random/20000"); - final HttpResponse response = this.httpclient.execute(target, httpget); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget); ConnectionRequest connreq = this.connManager.requestConnection(new HttpRoute(target), null); try { @@ -171,8 +171,8 @@ public class TestConnectionAutoRelease extends LocalServerTestBase { @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { final BasicHttpEntity entity = new BasicHttpEntity() { @@ -210,7 +210,7 @@ public class TestConnectionAutoRelease extends LocalServerTestBase { // Get some random data final HttpGet httpget = new HttpGet("/dropdead"); - final HttpResponse response = this.httpclient.execute(target, httpget); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget); ConnectionRequest connreq = this.connManager.requestConnection(new HttpRoute(target), null); try { diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestConnectionManagement.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestConnectionManagement.java index b47aeb182..233134bd7 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestConnectionManagement.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestConnectionManagement.java @@ -27,15 +27,9 @@ package org.apache.hc.client5.http.impl.integration; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.net.SocketException; import java.util.Collections; -import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; import org.apache.hc.client5.http.ConnectionPoolTimeoutException; import org.apache.hc.client5.http.HttpRoute; @@ -43,24 +37,19 @@ import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager; import org.apache.hc.client5.http.io.ConnectionRequest; import org.apache.hc.client5.http.io.HttpClientConnectionManager; import org.apache.hc.client5.http.localserver.LocalServerTestBase; -import org.apache.hc.client5.http.socket.ConnectionSocketFactory; -import org.apache.hc.client5.http.socket.PlainConnectionSocketFactory; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpHost; -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.HttpVersion; -import org.apache.hc.core5.http.config.Registry; -import org.apache.hc.core5.http.config.RegistryBuilder; -import org.apache.hc.core5.http.entity.EntityUtils; import org.apache.hc.core5.http.impl.io.HttpRequestExecutor; import org.apache.hc.core5.http.io.HttpClientConnection; -import org.apache.hc.core5.http.message.BasicHttpRequest; +import org.apache.hc.core5.http.io.entity.EntityUtils; +import org.apache.hc.core5.http.message.BasicClassicHttpRequest; import org.apache.hc.core5.http.protocol.BasicHttpContext; +import org.apache.hc.core5.http.protocol.DefaultHttpProcessor; import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.http.protocol.HttpCoreContext; import org.apache.hc.core5.http.protocol.HttpProcessor; -import org.apache.hc.core5.http.protocol.ImmutableHttpProcessor; import org.apache.hc.core5.http.protocol.RequestConnControl; import org.apache.hc.core5.http.protocol.RequestContent; import org.apache.hc.core5.http.protocol.RequestTargetHost; @@ -102,7 +91,7 @@ public class TestConnectionManagement extends LocalServerTestBase { final int rsplen = 8; final String uri = "/random/" + rsplen; - final HttpRequest request = new BasicHttpRequest("GET", uri, HttpVersion.HTTP_1_1); + final ClassicHttpRequest request = new BasicClassicHttpRequest("GET", uri); final HttpContext context = new BasicHttpContext(); HttpClientConnection conn = getConnection(this.connManager, route); @@ -110,18 +99,17 @@ public class TestConnectionManagement extends LocalServerTestBase { this.connManager.routeComplete(conn, route, context); context.setAttribute(HttpCoreContext.HTTP_CONNECTION, conn); - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target); - final HttpProcessor httpProcessor = new ImmutableHttpProcessor( + final HttpProcessor httpProcessor = new DefaultHttpProcessor( new RequestTargetHost(), new RequestContent(), new RequestConnControl()); final HttpRequestExecutor exec = new HttpRequestExecutor(); exec.preProcess(request, httpProcessor, context); - HttpResponse response = exec.execute(request, conn, context); + ClassicHttpResponse response = exec.execute(request, conn, context); Assert.assertEquals("wrong status in first response", HttpStatus.SC_OK, - response.getStatusLine().getStatusCode()); + response.getCode()); byte[] data = EntityUtils.toByteArray(response.getEntity()); Assert.assertEquals("wrong length of first response entity", rsplen, data.length); @@ -150,7 +138,7 @@ public class TestConnectionManagement extends LocalServerTestBase { Assert.assertEquals("wrong status in second response", HttpStatus.SC_OK, - response.getStatusLine().getStatusCode()); + response.getCode()); data = EntityUtils.toByteArray(response.getEntity()); Assert.assertEquals("wrong length of second response entity", rsplen, data.length); @@ -168,7 +156,7 @@ public class TestConnectionManagement extends LocalServerTestBase { Assert.assertEquals("wrong status in third response", HttpStatus.SC_OK, - response.getStatusLine().getStatusCode()); + response.getCode()); data = EntityUtils.toByteArray(response.getEntity()); Assert.assertEquals("wrong length of third response entity", rsplen, data.length); @@ -191,7 +179,7 @@ public class TestConnectionManagement extends LocalServerTestBase { final int rsplen = 8; final String uri = "/random/" + rsplen; - final HttpRequest request = new BasicHttpRequest("GET", uri, HttpVersion.HTTP_1_1); + final ClassicHttpRequest request = new BasicClassicHttpRequest("GET", uri); final HttpContext context = new BasicHttpContext(); HttpClientConnection conn = getConnection(this.connManager, route); @@ -199,18 +187,17 @@ public class TestConnectionManagement extends LocalServerTestBase { this.connManager.routeComplete(conn, route, context); context.setAttribute(HttpCoreContext.HTTP_CONNECTION, conn); - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target); - final HttpProcessor httpProcessor = new ImmutableHttpProcessor( + final HttpProcessor httpProcessor = new DefaultHttpProcessor( new RequestTargetHost(), new RequestContent(), new RequestConnControl()); final HttpRequestExecutor exec = new HttpRequestExecutor(); exec.preProcess(request, httpProcessor, context); - HttpResponse response = exec.execute(request, conn, context); + ClassicHttpResponse response = exec.execute(request, conn, context); Assert.assertEquals("wrong status in first response", HttpStatus.SC_OK, - response.getStatusLine().getStatusCode()); + response.getCode()); byte[] data = EntityUtils.toByteArray(response.getEntity()); Assert.assertEquals("wrong length of first response entity", rsplen, data.length); @@ -239,7 +226,7 @@ public class TestConnectionManagement extends LocalServerTestBase { Assert.assertEquals("wrong status in second response", HttpStatus.SC_OK, - response.getStatusLine().getStatusCode()); + response.getCode()); data = EntityUtils.toByteArray(response.getEntity()); Assert.assertEquals("wrong length of second response entity", rsplen, data.length); @@ -255,7 +242,7 @@ public class TestConnectionManagement extends LocalServerTestBase { Assert.assertEquals("wrong status in third response", HttpStatus.SC_OK, - response.getStatusLine().getStatusCode()); + response.getCode()); data = EntityUtils.toByteArray(response.getEntity()); Assert.assertEquals("wrong length of third response entity", rsplen, data.length); @@ -275,7 +262,7 @@ public class TestConnectionManagement extends LocalServerTestBase { Assert.assertEquals("wrong status in third response", HttpStatus.SC_OK, - response.getStatusLine().getStatusCode()); + response.getCode()); data = EntityUtils.toByteArray(response.getEntity()); Assert.assertEquals("wrong length of fourth response entity", rsplen, data.length); @@ -308,7 +295,7 @@ public class TestConnectionManagement extends LocalServerTestBase { Assert.assertEquals(1, this.connManager.getTotalStats().getAvailable()); Assert.assertEquals(1, this.connManager.getStats(route).getAvailable()); - this.connManager.closeExpiredConnections(); + this.connManager.closeExpired(); // Time has not expired yet. Assert.assertEquals(Collections.singleton(route), this.connManager.getRoutes()); @@ -317,7 +304,7 @@ public class TestConnectionManagement extends LocalServerTestBase { Thread.sleep(150); - this.connManager.closeExpiredConnections(); + this.connManager.closeExpired(); // Time expired now, connections are destroyed. Assert.assertEquals(Collections.emptySet(), this.connManager.getRoutes()); @@ -355,7 +342,7 @@ public class TestConnectionManagement extends LocalServerTestBase { Assert.assertEquals(1, this.connManager.getTotalStats().getAvailable()); Assert.assertEquals(1, this.connManager.getStats(route).getAvailable()); - this.connManager.closeExpiredConnections(); + this.connManager.closeExpired(); // Time has not expired yet. Assert.assertEquals(Collections.singleton(route), this.connManager.getRoutes()); @@ -364,7 +351,7 @@ public class TestConnectionManagement extends LocalServerTestBase { Thread.sleep(150); - this.connManager.closeExpiredConnections(); + this.connManager.closeExpired(); // TTL expired now, connections are destroyed. Assert.assertEquals(Collections.emptySet(), this.connManager.getRoutes()); @@ -389,26 +376,25 @@ public class TestConnectionManagement extends LocalServerTestBase { final String uri = "/random/" + rsplen; final HttpContext context = new BasicHttpContext(); - final HttpRequest request = - new BasicHttpRequest("GET", uri, HttpVersion.HTTP_1_1); + final ClassicHttpRequest request = + new BasicClassicHttpRequest("GET", uri); HttpClientConnection conn = getConnection(this.connManager, route); this.connManager.connect(conn, route, 0, context); this.connManager.routeComplete(conn, route, context); context.setAttribute(HttpCoreContext.HTTP_CONNECTION, conn); - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target); - final HttpProcessor httpProcessor = new ImmutableHttpProcessor( + final HttpProcessor httpProcessor = new DefaultHttpProcessor( new RequestTargetHost(), new RequestContent(), new RequestConnControl()); final HttpRequestExecutor exec = new HttpRequestExecutor(); exec.preProcess(request, httpProcessor, context); - final HttpResponse response = exec.execute(request, conn, context); + final ClassicHttpResponse response = exec.execute(request, conn, context); Assert.assertEquals("wrong status in first response", HttpStatus.SC_OK, - response.getStatusLine().getStatusCode()); + response.getCode()); // check that there are no connections available try { @@ -432,253 +418,4 @@ public class TestConnectionManagement extends LocalServerTestBase { this.connManager.shutdown(); } - @Test - public void testAbortDuringConnecting() throws Exception { - final CountDownLatch connectLatch = new CountDownLatch(1); - final StallingSocketFactory stallingSocketFactory = new StallingSocketFactory( - connectLatch, WaitPolicy.BEFORE_CONNECT, PlainConnectionSocketFactory.getSocketFactory()); - final Registry registry = RegistryBuilder.create() - .register("http", stallingSocketFactory) - .build(); - - this.connManager = new PoolingHttpClientConnectionManager(registry); - this.clientBuilder.setConnectionManager(this.connManager); - - this.connManager.setMaxTotal(1); - - final HttpHost target = start(); - final HttpRoute route = new HttpRoute(target, null, false); - final HttpContext context = new BasicHttpContext(); - - final HttpClientConnection conn = getConnection(this.connManager, route); - - final AtomicReference throwRef = new AtomicReference<>(); - final Thread abortingThread = new Thread(new Runnable() { - @Override - public void run() { - try { - stallingSocketFactory.waitForState(); - conn.shutdown(); - connManager.releaseConnection(conn, null, -1, null); - connectLatch.countDown(); - } catch (final Throwable e) { - throwRef.set(e); - } - } - }); - abortingThread.start(); - - try { - this.connManager.connect(conn, route, 0, context); - this.connManager.routeComplete(conn, route, context); - Assert.fail("expected SocketException"); - } catch(final SocketException expected) {} - - abortingThread.join(5000); - if(throwRef.get() != null) { - throw new RuntimeException(throwRef.get()); - } - - Assert.assertFalse(conn.isOpen()); - - // the connection is expected to be released back to the manager - final HttpClientConnection conn2 = getConnection(this.connManager, route, 5L, TimeUnit.SECONDS); - Assert.assertFalse("connection should have been closed", conn2.isOpen()); - - this.connManager.releaseConnection(conn2, null, -1, null); - this.connManager.shutdown(); - } - - @Test - public void testAbortBeforeSocketCreate() throws Exception { - final CountDownLatch connectLatch = new CountDownLatch(1); - final StallingSocketFactory stallingSocketFactory = new StallingSocketFactory( - connectLatch, WaitPolicy.BEFORE_CREATE, PlainConnectionSocketFactory.getSocketFactory()); - final Registry registry = RegistryBuilder.create() - .register("http", stallingSocketFactory) - .build(); - - this.connManager = new PoolingHttpClientConnectionManager(registry); - this.clientBuilder.setConnectionManager(this.connManager); - - this.connManager.setMaxTotal(1); - - final HttpHost target = start(); - final HttpRoute route = new HttpRoute(target, null, false); - final HttpContext context = new BasicHttpContext(); - - final HttpClientConnection conn = getConnection(this.connManager, route); - - final AtomicReference throwRef = new AtomicReference<>(); - final Thread abortingThread = new Thread(new Runnable() { - @Override - public void run() { - try { - stallingSocketFactory.waitForState(); - conn.shutdown(); - connManager.releaseConnection(conn, null, -1, null); - connectLatch.countDown(); - } catch (final Throwable e) { - throwRef.set(e); - } - } - }); - abortingThread.start(); - - try { - this.connManager.connect(conn, route, 0, context); - this.connManager.routeComplete(conn, route, context); - Assert.fail("IOException expected"); - } catch(final IOException expected) { - } - - abortingThread.join(5000); - if(throwRef.get() != null) { - throw new RuntimeException(throwRef.get()); - } - - Assert.assertFalse(conn.isOpen()); - - // the connection is expected to be released back to the manager - final HttpClientConnection conn2 = getConnection(this.connManager, route, 5L, TimeUnit.SECONDS); - Assert.assertFalse("connection should have been closed", conn2.isOpen()); - - this.connManager.releaseConnection(conn2, null, -1, null); - this.connManager.shutdown(); - } - - @Test - public void testAbortAfterSocketConnect() throws Exception { - final CountDownLatch connectLatch = new CountDownLatch(1); - final StallingSocketFactory stallingSocketFactory = new StallingSocketFactory( - connectLatch, WaitPolicy.AFTER_CONNECT, PlainConnectionSocketFactory.getSocketFactory()); - final Registry registry = RegistryBuilder.create() - .register("http", stallingSocketFactory) - .build(); - - this.connManager = new PoolingHttpClientConnectionManager(registry); - this.clientBuilder.setConnectionManager(this.connManager); - - this.connManager.setMaxTotal(1); - - final HttpHost target = start(); - final HttpRoute route = new HttpRoute(target, null, false); - final HttpContext context = new BasicHttpContext(); - - final HttpClientConnection conn = getConnection(this.connManager, route); - - final AtomicReference throwRef = new AtomicReference<>(); - final Thread abortingThread = new Thread(new Runnable() { - @Override - public void run() { - try { - stallingSocketFactory.waitForState(); - conn.shutdown(); - connManager.releaseConnection(conn, null, -1, null); - connectLatch.countDown(); - } catch (final Throwable e) { - throwRef.set(e); - } - } - }); - abortingThread.start(); - - try { - this.connManager.connect(conn, route, 0, context); - this.connManager.routeComplete(conn, route, context); - Assert.fail("IOException expected"); - } catch(final IOException expected) { - } - - abortingThread.join(5000); - if(throwRef.get() != null) { - throw new RuntimeException(throwRef.get()); - } - - Assert.assertFalse(conn.isOpen()); - - // the connection is expected to be released back to the manager - final HttpClientConnection conn2 = getConnection(this.connManager, route, 5L, TimeUnit.SECONDS); - Assert.assertFalse("connection should have been closed", conn2.isOpen()); - - this.connManager.releaseConnection(conn2, null, -1, null); - this.connManager.shutdown(); - } - - static class LatchSupport { - - private final CountDownLatch continueLatch; - private final CountDownLatch waitLatch = new CountDownLatch(1); - protected final WaitPolicy waitPolicy; - - LatchSupport(final CountDownLatch continueLatch, final WaitPolicy waitPolicy) { - this.continueLatch = continueLatch; - this.waitPolicy = waitPolicy; - } - - void waitForState() throws InterruptedException { - if(!waitLatch.await(1, TimeUnit.SECONDS)) { - throw new RuntimeException("waited too long"); - } - } - - void latch() { - waitLatch.countDown(); - try { - if (!continueLatch.await(60, TimeUnit.SECONDS)) { - throw new RuntimeException("waited too long!"); - } - } catch (final InterruptedException e) { - throw new RuntimeException(e); - } - } - } - - private static class StallingSocketFactory extends LatchSupport implements ConnectionSocketFactory { - - private final ConnectionSocketFactory delegate; - - public StallingSocketFactory( - final CountDownLatch continueLatch, - final WaitPolicy waitPolicy, - final ConnectionSocketFactory delegate) { - super(continueLatch, waitPolicy); - this.delegate = delegate; - } - - @Override - public Socket connectSocket( - final int connectTimeout, - final Socket sock, - final HttpHost host, - final InetSocketAddress remoteAddress, - final InetSocketAddress localAddress, - final HttpContext context) throws IOException { - if(waitPolicy == WaitPolicy.BEFORE_CONNECT) { - latch(); - } - - final Socket socket = delegate.connectSocket( - connectTimeout, sock, host, remoteAddress, localAddress, context); - - if(waitPolicy == WaitPolicy.AFTER_CONNECT) { - latch(); - } - - return socket; - } - - @Override - public Socket createSocket(final HttpContext context) throws IOException { - if(waitPolicy == WaitPolicy.BEFORE_CREATE) { - latch(); - } - - return delegate.createSocket(context); - } - - } - - private enum WaitPolicy { BEFORE_CREATE, BEFORE_CONNECT, AFTER_CONNECT, AFTER_OPEN } - } diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestConnectionReuse.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestConnectionReuse.java index a0c603a71..23753a716 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestConnectionReuse.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestConnectionReuse.java @@ -34,6 +34,8 @@ import org.apache.hc.client5.http.impl.sync.CloseableHttpClient; import org.apache.hc.client5.http.localserver.LocalServerTestBase; import org.apache.hc.client5.http.localserver.RandomHandler; import org.apache.hc.client5.http.methods.HttpGet; +import org.apache.hc.core5.http.ClassicHttpResponse; +import org.apache.hc.core5.http.EntityDetails; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HeaderElements; import org.apache.hc.core5.http.HttpException; @@ -41,14 +43,10 @@ import org.apache.hc.core5.http.HttpHeaders; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.HttpResponseInterceptor; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.impl.HttpProcessors; +import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.http.protocol.HttpProcessor; -import org.apache.hc.core5.http.protocol.HttpProcessorBuilder; -import org.apache.hc.core5.http.protocol.ResponseConnControl; -import org.apache.hc.core5.http.protocol.ResponseContent; -import org.apache.hc.core5.http.protocol.ResponseDate; -import org.apache.hc.core5.http.protocol.ResponseServer; import org.junit.Assert; import org.junit.Test; @@ -56,11 +54,7 @@ public class TestConnectionReuse extends LocalServerTestBase { @Test public void testReuseOfPersistentConnections() throws Exception { - final HttpProcessor httpproc = HttpProcessorBuilder.create() - .add(new ResponseDate()) - .add(new ResponseServer(LocalServerTestBase.ORIGIN)) - .add(new ResponseContent()) - .add(new ResponseConnControl()).build(); + final HttpProcessor httpproc = HttpProcessors.customServer(null).build(); this.serverBootstrap.setHttpProcessor(httpproc) .registerHandler("/random/*", new RandomHandler()); @@ -99,6 +93,7 @@ public class TestConnectionReuse extends LocalServerTestBase { @Override public void process( final HttpResponse response, + final EntityDetails entityDetails, final HttpContext context) throws HttpException, IOException { response.setHeader(HttpHeaders.CONNECTION, HeaderElements.CLOSE); } @@ -107,11 +102,8 @@ public class TestConnectionReuse extends LocalServerTestBase { @Test public void testReuseOfClosedConnections() throws Exception { - final HttpProcessor httpproc = HttpProcessorBuilder.create() - .add(new ResponseDate()) - .add(new ResponseServer(LocalServerTestBase.ORIGIN)) - .add(new ResponseContent()) - .add(new AlwaysCloseConn()).build(); + final HttpProcessor httpproc = HttpProcessors.customServer(null) + .add(new AlwaysCloseConn()).build(); this.serverBootstrap.setHttpProcessor(httpproc) .registerHandler("/random/*", new RandomHandler()); @@ -147,11 +139,7 @@ public class TestConnectionReuse extends LocalServerTestBase { @Test public void testReuseOfAbortedConnections() throws Exception { - final HttpProcessor httpproc = HttpProcessorBuilder.create() - .add(new ResponseDate()) - .add(new ResponseServer(LocalServerTestBase.ORIGIN)) - .add(new ResponseContent()) - .add(new ResponseConnControl()).build(); + final HttpProcessor httpproc = HttpProcessors.customServer(null).build(); this.serverBootstrap.setHttpProcessor(httpproc) .registerHandler("/random/*", new RandomHandler()); @@ -187,12 +175,8 @@ public class TestConnectionReuse extends LocalServerTestBase { @Test public void testKeepAliveHeaderRespected() throws Exception { - final HttpProcessor httpproc = HttpProcessorBuilder.create() - .add(new ResponseDate()) - .add(new ResponseServer(LocalServerTestBase.ORIGIN)) - .add(new ResponseContent()) - .add(new ResponseConnControl()) - .add(new ResponseKeepAlive()).build(); + final HttpProcessor httpproc = HttpProcessors.customServer(null) + .add(new ResponseKeepAlive()).build(); this.serverBootstrap.setHttpProcessor(httpproc) .registerHandler("/random/*", new RandomHandler()); @@ -202,7 +186,7 @@ public class TestConnectionReuse extends LocalServerTestBase { final HttpHost target = start(); - HttpResponse response = this.httpclient.execute(target, new HttpGet("/random/2000")); + ClassicHttpResponse response = this.httpclient.execute(target, new HttpGet("/random/2000")); EntityUtils.consume(response.getEntity()); Assert.assertEquals(1, this.connManager.getTotalStats().getAvailable()); @@ -257,7 +241,7 @@ public class TestConnectionReuse extends LocalServerTestBase { try { for (int i = 0; i < this.repetitions; i++) { final HttpGet httpget = new HttpGet(this.requestURI); - final HttpResponse response = this.httpclient.execute( + final ClassicHttpResponse response = this.httpclient.execute( this.target, httpget); if (this.forceClose) { @@ -281,8 +265,10 @@ public class TestConnectionReuse extends LocalServerTestBase { // if there is no Connection: close header. private static class ResponseKeepAlive implements HttpResponseInterceptor { @Override - public void process(final HttpResponse response, final HttpContext context) - throws HttpException, IOException { + public void process( + final HttpResponse response, + final EntityDetails entityDetails, + final HttpContext context) throws HttpException, IOException { final Header connection = response.getFirstHeader(HttpHeaders.CONNECTION); if(connection != null) { if(!connection.getValue().equalsIgnoreCase("Close")) { diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestContentCodings.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestContentCodings.java index a2d1714b5..e3b4c695a 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestContentCodings.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestContentCodings.java @@ -33,6 +33,7 @@ import java.io.IOException; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.Iterator; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; @@ -44,19 +45,20 @@ import org.apache.hc.client5.http.impl.BasicResponseHandler; import org.apache.hc.client5.http.impl.sync.CloseableHttpClient; import org.apache.hc.client5.http.localserver.LocalServerTestBase; import org.apache.hc.client5.http.methods.HttpGet; -import org.apache.hc.core5.http.Header; +import org.apache.hc.core5.http.message.MessageSupport; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HeaderElement; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpHost; -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.entity.EntityUtils; -import org.apache.hc.core5.http.entity.InputStreamEntity; -import org.apache.hc.core5.http.entity.StringEntity; import org.apache.hc.core5.http.io.HttpRequestHandler; +import org.apache.hc.core5.http.io.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.InputStreamEntity; +import org.apache.hc.core5.http.io.entity.StringEntity; import org.apache.hc.core5.http.protocol.HttpContext; import org.junit.Assert; +import org.junit.Ignore; import org.junit.Test; /** @@ -64,6 +66,7 @@ import org.junit.Test; * require no intervention from the user of HttpClient, but we still want to let clients do their * own thing if they so wish. */ +@Ignore(value = "Disabled until content coding is fixed") public class TestContentCodings extends LocalServerTestBase { /** @@ -82,18 +85,18 @@ public class TestContentCodings extends LocalServerTestBase { */ @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { - response.setStatusCode(HttpStatus.SC_NO_CONTENT); + response.setCode(HttpStatus.SC_NO_CONTENT); } }); final HttpHost target = start(); final HttpGet request = new HttpGet("/some-resource"); - final HttpResponse response = this.httpclient.execute(target, request); - Assert.assertEquals(HttpStatus.SC_NO_CONTENT, response.getStatusLine().getStatusCode()); + final ClassicHttpResponse response = this.httpclient.execute(target, request); + Assert.assertEquals(HttpStatus.SC_NO_CONTENT, response.getCode()); Assert.assertNull(response.getEntity()); } @@ -112,7 +115,7 @@ public class TestContentCodings extends LocalServerTestBase { final HttpHost target = start(); final HttpGet request = new HttpGet("/some-resource"); - final HttpResponse response = this.httpclient.execute(target, request); + final ClassicHttpResponse response = this.httpclient.execute(target, request); Assert.assertEquals("The entity text is correctly transported", entityText, EntityUtils.toString(response.getEntity())); } @@ -132,7 +135,7 @@ public class TestContentCodings extends LocalServerTestBase { final HttpHost target = start(); final HttpGet request = new HttpGet("/some-resource"); - final HttpResponse response = this.httpclient.execute(target, request); + final ClassicHttpResponse response = this.httpclient.execute(target, request); Assert.assertEquals("The entity text is correctly transported", entityText, EntityUtils.toString(response.getEntity())); } @@ -151,7 +154,7 @@ public class TestContentCodings extends LocalServerTestBase { final HttpHost target = start(); final HttpGet request = new HttpGet("/some-resource"); - final HttpResponse response = this.httpclient.execute(target, request); + final ClassicHttpResponse response = this.httpclient.execute(target, request); Assert.assertEquals("The entity text is correctly transported", entityText, EntityUtils.toString(response.getEntity())); } @@ -217,7 +220,7 @@ public class TestContentCodings extends LocalServerTestBase { final HttpHost target = start(); final HttpGet request = new HttpGet("/some-resource"); - final HttpResponse response = this.httpclient.execute(target, request); + final ClassicHttpResponse response = this.httpclient.execute(target, request); final ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); @@ -234,7 +237,7 @@ public class TestContentCodings extends LocalServerTestBase { final HttpHost target = start(); final HttpGet request = new HttpGet("/some-resource"); - final HttpResponse response = this.httpclient.execute(target, request); + final ClassicHttpResponse response = this.httpclient.execute(target, request); final ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); @@ -289,34 +292,32 @@ public class TestContentCodings extends LocalServerTestBase { */ @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { response.setEntity(new StringEntity(entityText)); response.addHeader("Content-Type", "text/plain"); - final Header[] acceptEncodings = request.getHeaders("Accept-Encoding"); - - for (final Header header : acceptEncodings) { - for (final HeaderElement element : header.getElements()) { - if ("deflate".equalsIgnoreCase(element.getName())) { - response.addHeader("Content-Encoding", "deflate"); + final Iterator it = MessageSupport.iterate(request, "Accept-Encoding"); + while (it.hasNext()) { + final HeaderElement element = it.next(); + if ("deflate".equalsIgnoreCase(element.getName())) { + response.addHeader("Content-Encoding", "deflate"); /* Gack. DeflaterInputStream is Java 6. */ - // response.setEntity(new InputStreamEntity(new DeflaterInputStream(new - // ByteArrayInputStream( - // entityText.getBytes("utf-8"))), -1)); - final byte[] uncompressed = entityText.getBytes(StandardCharsets.UTF_8); - final Deflater compressor = new Deflater(Deflater.DEFAULT_COMPRESSION, rfc1951); - compressor.setInput(uncompressed); - compressor.finish(); - final byte[] output = new byte[100]; - final int compressedLength = compressor.deflate(output); - final byte[] compressed = new byte[compressedLength]; - System.arraycopy(output, 0, compressed, 0, compressedLength); - response.setEntity(new InputStreamEntity( - new ByteArrayInputStream(compressed), compressedLength)); - return; - } + // response.setEntity(new InputStreamEntity(new DeflaterInputStream(new + // ByteArrayInputStream( + // entityText.getBytes("utf-8"))), -1)); + final byte[] uncompressed = entityText.getBytes(StandardCharsets.UTF_8); + final Deflater compressor = new Deflater(Deflater.DEFAULT_COMPRESSION, rfc1951); + compressor.setInput(uncompressed); + compressor.finish(); + final byte[] output = new byte[100]; + final int compressedLength = compressor.deflate(output); + final byte[] compressed = new byte[compressedLength]; + System.arraycopy(output, 0, compressed, 0, compressedLength); + response.setEntity(new InputStreamEntity( + new ByteArrayInputStream(compressed), compressedLength)); + return; } } } @@ -339,47 +340,46 @@ public class TestContentCodings extends LocalServerTestBase { */ @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { response.setEntity(new StringEntity(entityText)); response.addHeader("Content-Type", "text/plain"); - final Header[] acceptEncodings = request.getHeaders("Accept-Encoding"); + response.addHeader("Content-Type", "text/plain"); + final Iterator it = MessageSupport.iterate(request, "Accept-Encoding"); + while (it.hasNext()) { + final HeaderElement element = it.next(); + if ("gzip".equalsIgnoreCase(element.getName())) { + response.addHeader("Content-Encoding", "gzip"); - for (final Header header : acceptEncodings) { - for (final HeaderElement element : header.getElements()) { - if ("gzip".equalsIgnoreCase(element.getName())) { - response.addHeader("Content-Encoding", "gzip"); + /* + * We have to do a bit more work with gzip versus deflate, since + * Gzip doesn't appear to have an equivalent to DeflaterInputStream in + * the JDK. + * + * UPDATE: DeflaterInputStream is Java 6 anyway, so we have to do a bit + * of work there too! + */ + final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + final OutputStream out = new GZIPOutputStream(bytes); - /* - * We have to do a bit more work with gzip versus deflate, since - * Gzip doesn't appear to have an equivalent to DeflaterInputStream in - * the JDK. - * - * UPDATE: DeflaterInputStream is Java 6 anyway, so we have to do a bit - * of work there too! - */ - final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - final OutputStream out = new GZIPOutputStream(bytes); + final ByteArrayInputStream uncompressed = new ByteArrayInputStream( + entityText.getBytes(StandardCharsets.UTF_8)); - final ByteArrayInputStream uncompressed = new ByteArrayInputStream( - entityText.getBytes(StandardCharsets.UTF_8)); + final byte[] buf = new byte[60]; - final byte[] buf = new byte[60]; - - int n; - while ((n = uncompressed.read(buf)) != -1) { - out.write(buf, 0, n); - } - - out.close(); - - final byte[] arr = bytes.toByteArray(); - response.setEntity(new InputStreamEntity(new ByteArrayInputStream(arr), - arr.length)); - - return; + int n; + while ((n = uncompressed.read(buf)) != -1) { + out.write(buf, 0, n); } + + out.close(); + + final byte[] arr = bytes.toByteArray(); + response.setEntity(new InputStreamEntity(new ByteArrayInputStream(arr), + arr.length)); + + return; } } } @@ -431,7 +431,7 @@ public class TestContentCodings extends LocalServerTestBase { try { startGate.await(); try { - final HttpResponse response = client.execute(target, request); + final ClassicHttpResponse response = client.execute(target, request); text = EntityUtils.toString(response.getEntity()); } catch (final Exception e) { failed = true; diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestCookieVirtualHost.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestCookieVirtualHost.java index e6b2a1331..58fdcf254 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestCookieVirtualHost.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestCookieVirtualHost.java @@ -34,17 +34,16 @@ import org.apache.hc.client5.http.cookie.BasicCookieStore; import org.apache.hc.client5.http.cookie.Cookie; import org.apache.hc.client5.http.cookie.CookieStore; import org.apache.hc.client5.http.localserver.LocalServerTestBase; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.sync.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.client5.http.protocol.HttpClientContext; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpHost; -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.HttpVersion; -import org.apache.hc.core5.http.entity.EntityUtils; import org.apache.hc.core5.http.io.HttpRequestHandler; +import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.http.message.BasicHeader; import org.apache.hc.core5.http.protocol.HttpContext; import org.junit.Assert; @@ -60,8 +59,8 @@ public class TestCookieVirtualHost extends LocalServerTestBase { this.serverBootstrap.registerHandler("*", new HttpRequestHandler() { @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { final int n = Integer.parseInt(request.getFirstHeader("X-Request").getValue()); @@ -71,8 +70,7 @@ public class TestCookieVirtualHost extends LocalServerTestBase { Assert.assertEquals("app.mydomain.fr", request .getFirstHeader("Host").getValue()); - response.setStatusLine(HttpVersion.HTTP_1_1, - HttpStatus.SC_OK); + response.setCode(HttpStatus.SC_OK); // Respond with Set-Cookie on virtual host domain. This // should be valid. response.addHeader(new BasicHeader("Set-Cookie", @@ -87,8 +85,7 @@ public class TestCookieVirtualHost extends LocalServerTestBase { // We should get our cookie back. Assert.assertNotNull("We must get a cookie header", request.getFirstHeader("Cookie")); - response.setStatusLine(HttpVersion.HTTP_1_1, - HttpStatus.SC_OK); + response.setCode(HttpStatus.SC_OK); break; case 3: @@ -96,8 +93,7 @@ public class TestCookieVirtualHost extends LocalServerTestBase { Assert.assertEquals("app.mydomain.fr", request .getFirstHeader("Host").getValue()); - response.setStatusLine(HttpVersion.HTTP_1_1, - HttpStatus.SC_OK); + response.setCode(HttpStatus.SC_OK); break; default: Assert.fail("Unexpected value: " + n); @@ -115,7 +111,7 @@ public class TestCookieVirtualHost extends LocalServerTestBase { // First request : retrieve a domain cookie from remote server. URI uri = new URI("http://app.mydomain.fr"); - HttpRequest httpRequest = new HttpGet(uri); + HttpGet httpRequest = new HttpGet(uri); httpRequest.addHeader("X-Request", "1"); try (CloseableHttpResponse response1 = this.httpclient.execute(target, httpRequest, context)) { EntityUtils.consume(response1.getEntity()); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestIdleConnectionEviction.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestIdleConnectionEviction.java index 11d548af4..9f024d415 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestIdleConnectionEviction.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestIdleConnectionEviction.java @@ -35,9 +35,9 @@ import org.apache.hc.client5.http.localserver.LocalServerTestBase; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.client5.http.methods.HttpUriRequest; import org.apache.hc.client5.http.protocol.ClientProtocolException; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpHost; -import org.apache.hc.core5.http.HttpResponse; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.EntityUtils; import org.junit.Test; public class TestIdleConnectionEviction extends LocalServerTestBase { @@ -96,8 +96,8 @@ public class TestIdleConnectionEviction extends LocalServerTestBase { public void run() { try { for (int i = 0; i < this.count; i++) { - final HttpResponse response = this.httpclient.execute(this.target, this.request); - final int status = response.getStatusLine().getStatusCode(); + final ClassicHttpResponse response = this.httpclient.execute(this.target, this.request); + final int status = response.getCode(); if (status != 200) { this.request.abort(); throw new ClientProtocolException("Unexpected status code: " + status); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestMalformedServerResponse.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestMalformedServerResponse.java index c55aed91d..48252e1fd 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestMalformedServerResponse.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestMalformedServerResponse.java @@ -30,18 +30,18 @@ import java.io.IOException; import java.net.Socket; import org.apache.hc.client5.http.localserver.LocalServerTestBase; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.sync.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpGet; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpHost; -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.entity.EntityUtils; -import org.apache.hc.core5.http.entity.StringEntity; import org.apache.hc.core5.http.impl.io.DefaultBHttpServerConnection; import org.apache.hc.core5.http.io.HttpConnectionFactory; import org.apache.hc.core5.http.io.HttpRequestHandler; +import org.apache.hc.core5.http.io.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.StringEntity; import org.apache.hc.core5.http.protocol.HttpContext; import org.junit.Assert; import org.junit.Test; @@ -55,9 +55,9 @@ public class TestMalformedServerResponse extends LocalServerTestBase { } @Override - public void sendResponseHeader(final HttpResponse response) throws HttpException, IOException { + public void sendResponseHeader(final ClassicHttpResponse response) throws HttpException, IOException { super.sendResponseHeader(response); - if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NO_CONTENT) { + if (response.getCode() == HttpStatus.SC_NO_CONTENT) { response.setEntity(new StringEntity( "garbage\ngarbage\n" + "garbage\ngarbage\n" + @@ -90,10 +90,10 @@ public class TestMalformedServerResponse extends LocalServerTestBase { @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { - response.setStatusCode(HttpStatus.SC_NO_CONTENT); + response.setCode(HttpStatus.SC_NO_CONTENT); } }); @@ -101,10 +101,10 @@ public class TestMalformedServerResponse extends LocalServerTestBase { @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { - response.setStatusCode(HttpStatus.SC_OK); + response.setCode(HttpStatus.SC_OK); response.setEntity(new StringEntity("Some important stuff")); } @@ -113,12 +113,12 @@ public class TestMalformedServerResponse extends LocalServerTestBase { final HttpHost target = start(); final HttpGet get1 = new HttpGet("/nostuff"); try (CloseableHttpResponse response1 = this.httpclient.execute(target, get1)) { - Assert.assertEquals(HttpStatus.SC_NO_CONTENT, response1.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_NO_CONTENT, response1.getCode()); EntityUtils.consume(response1.getEntity()); } final HttpGet get2 = new HttpGet("/stuff"); try (CloseableHttpResponse response2 = this.httpclient.execute(target, get2)) { - Assert.assertEquals(HttpStatus.SC_OK, response2.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_OK, response2.getCode()); EntityUtils.consume(response2.getEntity()); } } diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestMinimalClientRequestExecution.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestMinimalClientRequestExecution.java index 882be045e..dbfd2b90b 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestMinimalClientRequestExecution.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestMinimalClientRequestExecution.java @@ -35,15 +35,16 @@ import org.apache.hc.client5.http.impl.sync.HttpClients; import org.apache.hc.client5.http.localserver.LocalServerTestBase; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.client5.http.protocol.HttpClientContext; +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.HttpHost; 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.entity.EntityUtils; -import org.apache.hc.core5.http.entity.StringEntity; import org.apache.hc.core5.http.io.HttpRequestHandler; +import org.apache.hc.core5.http.io.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.StringEntity; import org.apache.hc.core5.http.protocol.HttpContext; import org.junit.Assert; import org.junit.Test; @@ -61,10 +62,10 @@ public class TestMinimalClientRequestExecution extends LocalServerTestBase { @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { - response.setStatusCode(HttpStatus.SC_OK); + response.setCode(HttpStatus.SC_OK); final StringEntity entity = new StringEntity("Whatever"); response.setEntity(entity); } @@ -79,9 +80,9 @@ public class TestMinimalClientRequestExecution extends LocalServerTestBase { final HttpClientContext context = HttpClientContext.create(); for (int i = 0; i < 10; i++) { final HttpGet request = new HttpGet("/"); - final HttpResponse response = this.httpclient.execute(target, request, context); + final ClassicHttpResponse response = this.httpclient.execute(target, request, context); EntityUtils.consume(response.getEntity()); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_OK, response.getCode()); final HttpRequest reqWrapper = context.getRequest(); Assert.assertNotNull(reqWrapper); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestRedirects.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestRedirects.java index 0a9302813..fec5fe824 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestRedirects.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestRedirects.java @@ -44,19 +44,20 @@ import org.apache.hc.client5.http.protocol.ClientProtocolException; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.protocol.RedirectException; import org.apache.hc.client5.http.utils.URIUtils; +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.HttpConnection; 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.HttpResponse; import org.apache.hc.core5.http.HttpStatus; import org.apache.hc.core5.http.ProtocolException; -import org.apache.hc.core5.http.entity.EntityUtils; -import org.apache.hc.core5.http.entity.StringEntity; import org.apache.hc.core5.http.io.HttpRequestHandler; import org.apache.hc.core5.http.io.UriHttpRequestHandlerMapper; +import org.apache.hc.core5.http.io.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.StringEntity; import org.apache.hc.core5.http.message.BasicHeader; import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.http.protocol.HttpCoreContext; @@ -83,8 +84,8 @@ public class TestRedirects extends LocalServerTestBase { @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { final HttpConnection conn = (HttpConnection) context.getAttribute(HttpCoreContext.HTTP_CONNECTION); final InetSocketAddress socketAddress = (InetSocketAddress) conn.getLocalAddress(); @@ -93,18 +94,18 @@ public class TestRedirects extends LocalServerTestBase { localhost = "localhost"; } final int port = socketAddress.getPort(); - final String uri = request.getRequestLine().getUri(); + final String uri = request.getRequestUri(); if (uri.equals("/oldlocation/")) { - response.setStatusCode(this.statuscode); + response.setCode(this.statuscode); response.addHeader(new BasicHeader("Location", "http://" + localhost + ":" + port + "/newlocation/")); response.addHeader(new BasicHeader("Connection", "close")); } else if (uri.equals("/newlocation/")) { - response.setStatusCode(HttpStatus.SC_OK); + response.setCode(HttpStatus.SC_OK); final StringEntity entity = new StringEntity("Successful redirect"); response.setEntity(entity); } else { - response.setStatusCode(HttpStatus.SC_NOT_FOUND); + response.setCode(HttpStatus.SC_NOT_FOUND); } } @@ -118,18 +119,18 @@ public class TestRedirects extends LocalServerTestBase { @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { - final String uri = request.getRequestLine().getUri(); + final String uri = request.getRequestUri(); if (uri.startsWith("/circular-oldlocation")) { - response.setStatusCode(HttpStatus.SC_MOVED_TEMPORARILY); + response.setCode(HttpStatus.SC_MOVED_TEMPORARILY); response.addHeader(new BasicHeader("Location", "/circular-location2")); } else if (uri.startsWith("/circular-location2")) { - response.setStatusCode(HttpStatus.SC_MOVED_TEMPORARILY); + response.setCode(HttpStatus.SC_MOVED_TEMPORARILY); response.addHeader(new BasicHeader("Location", "/circular-oldlocation")); } else { - response.setStatusCode(HttpStatus.SC_NOT_FOUND); + response.setCode(HttpStatus.SC_NOT_FOUND); } } } @@ -142,19 +143,19 @@ public class TestRedirects extends LocalServerTestBase { @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { - final String uri = request.getRequestLine().getUri(); + final String uri = request.getRequestUri(); if (uri.equals("/oldlocation/")) { - response.setStatusCode(HttpStatus.SC_MOVED_TEMPORARILY); + response.setCode(HttpStatus.SC_MOVED_TEMPORARILY); response.addHeader(new BasicHeader("Location", "/relativelocation/")); } else if (uri.equals("/relativelocation/")) { - response.setStatusCode(HttpStatus.SC_OK); + response.setCode(HttpStatus.SC_OK); final StringEntity entity = new StringEntity("Successful redirect"); response.setEntity(entity); } else { - response.setStatusCode(HttpStatus.SC_NOT_FOUND); + response.setCode(HttpStatus.SC_NOT_FOUND); } } } @@ -167,19 +168,19 @@ public class TestRedirects extends LocalServerTestBase { @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { - final String uri = request.getRequestLine().getUri(); + final String uri = request.getRequestUri(); if (uri.equals("/test/oldlocation")) { - response.setStatusCode(HttpStatus.SC_MOVED_TEMPORARILY); + response.setCode(HttpStatus.SC_MOVED_TEMPORARILY); response.addHeader(new BasicHeader("Location", "relativelocation")); } else if (uri.equals("/test/relativelocation")) { - response.setStatusCode(HttpStatus.SC_OK); + response.setCode(HttpStatus.SC_OK); final StringEntity entity = new StringEntity("Successful redirect"); response.setEntity(entity); } else { - response.setStatusCode(HttpStatus.SC_NOT_FOUND); + response.setCode(HttpStatus.SC_NOT_FOUND); } } } @@ -192,16 +193,16 @@ public class TestRedirects extends LocalServerTestBase { @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { - final String uri = request.getRequestLine().getUri(); + final String uri = request.getRequestUri(); if (uri.equals("/rome")) { - response.setStatusCode(HttpStatus.SC_OK); + response.setCode(HttpStatus.SC_OK); final StringEntity entity = new StringEntity("Successful redirect"); response.setEntity(entity); } else { - response.setStatusCode(HttpStatus.SC_MOVED_TEMPORARILY); + response.setCode(HttpStatus.SC_MOVED_TEMPORARILY); response.addHeader(new BasicHeader("Location", "/rome")); } } @@ -217,19 +218,19 @@ public class TestRedirects extends LocalServerTestBase { @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { - final String uri = request.getRequestLine().getUri(); + final String uri = request.getRequestUri(); if (uri.equals("/oldlocation/")) { - response.setStatusCode(HttpStatus.SC_MOVED_TEMPORARILY); + response.setCode(HttpStatus.SC_MOVED_TEMPORARILY); response.addHeader(new BasicHeader("Location", url)); } else if (uri.equals("/relativelocation/")) { - response.setStatusCode(HttpStatus.SC_OK); + response.setCode(HttpStatus.SC_OK); final StringEntity entity = new StringEntity("Successful redirect"); response.setEntity(entity); } else { - response.setStatusCode(HttpStatus.SC_NOT_FOUND); + response.setCode(HttpStatus.SC_NOT_FOUND); } } } @@ -245,13 +246,13 @@ public class TestRedirects extends LocalServerTestBase { final HttpGet httpget = new HttpGet("/oldlocation/"); - final HttpResponse response = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context); EntityUtils.consume(response.getEntity()); final HttpRequest reqWrapper = context.getRequest(); - Assert.assertEquals(HttpStatus.SC_MULTIPLE_CHOICES, response.getStatusLine().getStatusCode()); - Assert.assertEquals("/oldlocation/", reqWrapper.getRequestLine().getUri()); + Assert.assertEquals(HttpStatus.SC_MULTIPLE_CHOICES, response.getCode()); + Assert.assertEquals(URIUtils.create(target, "/oldlocation/"), reqWrapper.getUri()); final List redirects = context.getRedirectLocations(); Assert.assertNull(redirects); @@ -268,15 +269,13 @@ public class TestRedirects extends LocalServerTestBase { final HttpGet httpget = new HttpGet("/oldlocation/"); - final HttpResponse response = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context); EntityUtils.consume(response.getEntity()); final HttpRequest reqWrapper = context.getRequest(); - final HttpHost host = context.getTargetHost(); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); - Assert.assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri()); - Assert.assertEquals(target, host); + Assert.assertEquals(HttpStatus.SC_OK, response.getCode()); + Assert.assertEquals(URIUtils.create(target, "/newlocation/"), reqWrapper.getUri()); final List redirects = context.getRedirectLocations(); Assert.assertNotNull(redirects); @@ -297,15 +296,13 @@ public class TestRedirects extends LocalServerTestBase { final HttpGet httpget = new HttpGet("/oldlocation/"); - final HttpResponse response = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context); EntityUtils.consume(response.getEntity()); final HttpRequest reqWrapper = context.getRequest(); - final HttpHost host = context.getTargetHost(); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); - Assert.assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri()); - Assert.assertEquals(target, host); + Assert.assertEquals(HttpStatus.SC_OK, response.getCode()); + Assert.assertEquals(URIUtils.create(target, "/newlocation/"), reqWrapper.getUri()); } @Test @@ -314,10 +311,10 @@ public class TestRedirects extends LocalServerTestBase { @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { - response.setStatusCode(HttpStatus.SC_MOVED_TEMPORARILY); + response.setCode(HttpStatus.SC_MOVED_TEMPORARILY); } }); @@ -328,15 +325,13 @@ public class TestRedirects extends LocalServerTestBase { final HttpGet httpget = new HttpGet("/oldlocation/"); - final HttpResponse response = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context); EntityUtils.consume(response.getEntity()); final HttpRequest reqWrapper = context.getRequest(); - final HttpHost host = context.getTargetHost(); - Assert.assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, response.getStatusLine().getStatusCode()); - Assert.assertEquals("/oldlocation/", reqWrapper.getRequestLine().getUri()); - Assert.assertEquals(target, host); + Assert.assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, response.getCode()); + Assert.assertEquals("/oldlocation/", reqWrapper.getRequestUri()); } @Test @@ -350,15 +345,13 @@ public class TestRedirects extends LocalServerTestBase { final HttpGet httpget = new HttpGet("/oldlocation/"); - final HttpResponse response = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context); EntityUtils.consume(response.getEntity()); final HttpRequest reqWrapper = context.getRequest(); - final HttpHost host = context.getTargetHost(); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); - Assert.assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri()); - Assert.assertEquals(target, host); + Assert.assertEquals(HttpStatus.SC_OK, response.getCode()); + Assert.assertEquals(URIUtils.create(target, "/newlocation/"), reqWrapper.getUri()); } @Test @@ -372,13 +365,13 @@ public class TestRedirects extends LocalServerTestBase { final HttpGet httpget = new HttpGet("/oldlocation/"); - final HttpResponse response = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context); EntityUtils.consume(response.getEntity()); final HttpRequest reqWrapper = context.getRequest(); - Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, response.getStatusLine().getStatusCode()); - Assert.assertEquals("/oldlocation/", reqWrapper.getRequestLine().getUri()); + Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, response.getCode()); + Assert.assertEquals(URIUtils.create(target, "/oldlocation/"), reqWrapper.getUri()); } @Test @@ -391,13 +384,13 @@ public class TestRedirects extends LocalServerTestBase { final HttpGet httpget = new HttpGet("/oldlocation/"); - final HttpResponse response = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context); EntityUtils.consume(response.getEntity()); final HttpRequest reqWrapper = context.getRequest(); - Assert.assertEquals(HttpStatus.SC_USE_PROXY, response.getStatusLine().getStatusCode()); - Assert.assertEquals("/oldlocation/", reqWrapper.getRequestLine().getUri()); + Assert.assertEquals(HttpStatus.SC_USE_PROXY, response.getCode()); + Assert.assertEquals(URIUtils.create(target, "/oldlocation/"), reqWrapper.getUri()); } @Test @@ -411,15 +404,13 @@ public class TestRedirects extends LocalServerTestBase { final HttpGet httpget = new HttpGet("/oldlocation/"); - final HttpResponse response = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context); EntityUtils.consume(response.getEntity()); final HttpRequest reqWrapper = context.getRequest(); - final HttpHost host = context.getTargetHost(); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); - Assert.assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri()); - Assert.assertEquals(target, host); + Assert.assertEquals(HttpStatus.SC_OK, response.getCode()); + Assert.assertEquals(URIUtils.create(target, "/newlocation/"), reqWrapper.getUri()); } @Test(expected=ClientProtocolException.class) @@ -471,24 +462,19 @@ public class TestRedirects extends LocalServerTestBase { final HttpClientContext context = HttpClientContext.create(); - final RequestConfig config = RequestConfig.custom().setRelativeRedirectsAllowed(true).build(); final HttpGet first = new HttpGet("/rome"); - first.setConfig(config); EntityUtils.consume(this.httpclient.execute(target, first, context).getEntity()); final HttpGet second = new HttpGet("/rome"); - second.setConfig(config); - final HttpResponse response = this.httpclient.execute(target, second, context); + final ClassicHttpResponse response = this.httpclient.execute(target, second, context); EntityUtils.consume(response.getEntity()); final HttpRequest reqWrapper = context.getRequest(); - final HttpHost host = context.getTargetHost(); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); - Assert.assertEquals("/rome", reqWrapper.getRequestLine().getUri()); - Assert.assertEquals(host, target); + Assert.assertEquals(HttpStatus.SC_OK, response.getCode()); + Assert.assertEquals(URIUtils.create(target, "/rome"), reqWrapper.getUri()); } @Test @@ -499,25 +485,19 @@ public class TestRedirects extends LocalServerTestBase { final HttpClientContext context = HttpClientContext.create(); - final RequestConfig config = RequestConfig.custom().setRelativeRedirectsAllowed(true).build(); final HttpGet first = new HttpGet("/lille"); - first.setConfig(config); - - final HttpResponse response1 = this.httpclient.execute(target, first, context); + final ClassicHttpResponse response1 = this.httpclient.execute(target, first, context); EntityUtils.consume(response1.getEntity()); final HttpGet second = new HttpGet("/lille"); - second.setConfig(config); - final HttpResponse response2 = this.httpclient.execute(target, second, context); + final ClassicHttpResponse response2 = this.httpclient.execute(target, second, context); EntityUtils.consume(response2.getEntity()); final HttpRequest reqWrapper = context.getRequest(); - final HttpHost host = context.getTargetHost(); - Assert.assertEquals(HttpStatus.SC_OK, response2.getStatusLine().getStatusCode()); - Assert.assertEquals("/rome", reqWrapper.getRequestLine().getUri()); - Assert.assertEquals(host, target); + Assert.assertEquals(HttpStatus.SC_OK, response2.getCode()); + Assert.assertEquals(URIUtils.create(target, "/rome"), reqWrapper.getUri()); } @Test @@ -528,25 +508,20 @@ public class TestRedirects extends LocalServerTestBase { final HttpClientContext context = HttpClientContext.create(); - final RequestConfig config = RequestConfig.custom().setRelativeRedirectsAllowed(true).build(); final HttpGet first = new HttpGet("/alian"); - first.setConfig(config); - final HttpResponse response1 = this.httpclient.execute(target, first, context); + final ClassicHttpResponse response1 = this.httpclient.execute(target, first, context); EntityUtils.consume(response1.getEntity()); final HttpGet second = new HttpGet("/lille"); - second.setConfig(config); - final HttpResponse response2 = this.httpclient.execute(target, second, context); + final ClassicHttpResponse response2 = this.httpclient.execute(target, second, context); EntityUtils.consume(response2.getEntity()); final HttpRequest reqWrapper = context.getRequest(); - final HttpHost host = context.getTargetHost(); - Assert.assertEquals(HttpStatus.SC_OK, response2.getStatusLine().getStatusCode()); - Assert.assertEquals("/rome", reqWrapper.getRequestLine().getUri()); - Assert.assertEquals(host, target); + Assert.assertEquals(HttpStatus.SC_OK, response2.getCode()); + Assert.assertEquals(URIUtils.create(target, "/rome"), reqWrapper.getUri()); } @Test @@ -560,14 +535,14 @@ public class TestRedirects extends LocalServerTestBase { final HttpPost httppost = new HttpPost("/oldlocation/"); httppost.setEntity(new StringEntity("stuff")); - final HttpResponse response = this.httpclient.execute(target, httppost, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httppost, context); EntityUtils.consume(response.getEntity()); final HttpRequest reqWrapper = context.getRequest(); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); - Assert.assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri()); - Assert.assertEquals("GET", reqWrapper.getRequestLine().getMethod()); + Assert.assertEquals(HttpStatus.SC_OK, response.getCode()); + Assert.assertEquals(URIUtils.create(target, "/newlocation/"), reqWrapper.getUri()); + Assert.assertEquals("GET", reqWrapper.getMethod()); } @Test @@ -578,19 +553,15 @@ public class TestRedirects extends LocalServerTestBase { final HttpClientContext context = HttpClientContext.create(); - final RequestConfig config = RequestConfig.custom().setRelativeRedirectsAllowed(true).build(); final HttpGet httpget = new HttpGet("/oldlocation/"); - httpget.setConfig(config); - final HttpResponse response = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context); EntityUtils.consume(response.getEntity()); final HttpRequest reqWrapper = context.getRequest(); - final HttpHost host = context.getTargetHost(); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); - Assert.assertEquals("/relativelocation/", reqWrapper.getRequestLine().getUri()); - Assert.assertEquals(host, target); + Assert.assertEquals(HttpStatus.SC_OK, response.getCode()); + Assert.assertEquals(URIUtils.create(target, "/relativelocation/"), reqWrapper.getUri()); } @Test @@ -601,19 +572,15 @@ public class TestRedirects extends LocalServerTestBase { final HttpClientContext context = HttpClientContext.create(); - final RequestConfig config = RequestConfig.custom().setRelativeRedirectsAllowed(true).build(); final HttpGet httpget = new HttpGet("/test/oldlocation"); - httpget.setConfig(config); - final HttpResponse response = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context); EntityUtils.consume(response.getEntity()); final HttpRequest reqWrapper = context.getRequest(); - final HttpHost host = context.getTargetHost(); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); - Assert.assertEquals("/test/relativelocation", reqWrapper.getRequestLine().getUri()); - Assert.assertEquals(host, target); + Assert.assertEquals(HttpStatus.SC_OK, response.getCode()); + Assert.assertEquals(URIUtils.create(target, "/test/relativelocation"), reqWrapper.getUri()); } @Test(expected=ClientProtocolException.class) @@ -672,13 +639,13 @@ public class TestRedirects extends LocalServerTestBase { context.setCookieStore(cookieStore); final HttpGet httpget = new HttpGet("/oldlocation/"); - final HttpResponse response = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context); EntityUtils.consume(response.getEntity()); final HttpRequest reqWrapper = context.getRequest(); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); - Assert.assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri()); + Assert.assertEquals(HttpStatus.SC_OK, response.getCode()); + Assert.assertEquals(URIUtils.create(target, "/newlocation/"), reqWrapper.getUri()); final Header[] headers = reqWrapper.getHeaders("Cookie"); Assert.assertEquals("There can only be one (cookie)", 1, headers.length); @@ -697,13 +664,13 @@ public class TestRedirects extends LocalServerTestBase { final HttpGet httpget = new HttpGet("/oldlocation/"); - final HttpResponse response = this.httpclient.execute(target, httpget, context); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context); EntityUtils.consume(response.getEntity()); final HttpRequest reqWrapper = context.getRequest(); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); - Assert.assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri()); + Assert.assertEquals(HttpStatus.SC_OK, response.getCode()); + Assert.assertEquals(URIUtils.create(target, "/newlocation/"), reqWrapper.getUri()); final Header header = reqWrapper.getFirstHeader(HttpHeaders.USER_AGENT); Assert.assertEquals("my-test-client", header.getValue()); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestSPNegoScheme.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestSPNegoScheme.java index 0a9bc2d09..c68aa3a1d 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestSPNegoScheme.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestSPNegoScheme.java @@ -39,16 +39,16 @@ import org.apache.hc.client5.http.impl.sync.BasicCredentialsProvider; import org.apache.hc.client5.http.impl.sync.HttpClients; import org.apache.hc.client5.http.localserver.LocalServerTestBase; import org.apache.hc.client5.http.methods.HttpGet; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpHost; -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.config.Registry; import org.apache.hc.core5.http.config.RegistryBuilder; -import org.apache.hc.core5.http.entity.EntityUtils; -import org.apache.hc.core5.http.entity.StringEntity; import org.apache.hc.core5.http.io.HttpRequestHandler; +import org.apache.hc.core5.http.io.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.StringEntity; import org.apache.hc.core5.http.message.BasicHeader; import org.apache.hc.core5.http.protocol.HttpContext; import org.ietf.jgss.GSSContext; @@ -73,10 +73,10 @@ public class TestSPNegoScheme extends LocalServerTestBase { @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { - response.setStatusCode(HttpStatus.SC_UNAUTHORIZED); + response.setCode(HttpStatus.SC_UNAUTHORIZED); response.addHeader(new BasicHeader("WWW-Authenticate", "Negotiate blablabla")); response.addHeader(new BasicHeader("Connection", "Keep-Alive")); response.setEntity(new StringEntity("auth required ")); @@ -168,10 +168,10 @@ public class TestSPNegoScheme extends LocalServerTestBase { final String s = "/path"; final HttpGet httpget = new HttpGet(s); - final HttpResponse response = this.httpclient.execute(target, httpget); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget); EntityUtils.consume(response.getEntity()); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode()); } /** @@ -199,10 +199,10 @@ public class TestSPNegoScheme extends LocalServerTestBase { final String s = "/path"; final HttpGet httpget = new HttpGet(s); - final HttpResponse response = this.httpclient.execute(target, httpget); + final ClassicHttpResponse response = this.httpclient.execute(target, httpget); EntityUtils.consume(response.getEntity()); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode()); } } diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestStatefulConnManagement.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestStatefulConnManagement.java index f361376bb..e78c91fb9 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestStatefulConnManagement.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/integration/TestStatefulConnManagement.java @@ -34,15 +34,15 @@ import org.apache.hc.client5.http.localserver.LocalServerTestBase; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.protocol.UserTokenHandler; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpHost; -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.entity.EntityUtils; -import org.apache.hc.core5.http.entity.StringEntity; import org.apache.hc.core5.http.io.HttpClientConnection; import org.apache.hc.core5.http.io.HttpRequestHandler; +import org.apache.hc.core5.http.io.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.StringEntity; import org.apache.hc.core5.http.protocol.BasicHttpContext; import org.apache.hc.core5.http.protocol.HttpContext; import org.junit.Assert; @@ -61,10 +61,10 @@ public class TestStatefulConnManagement extends LocalServerTestBase { @Override public void handle( - final HttpRequest request, - final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { - response.setStatusCode(HttpStatus.SC_OK); + response.setCode(HttpStatus.SC_OK); final StringEntity entity = new StringEntity("Whatever"); response.setEntity(entity); } @@ -170,7 +170,7 @@ public class TestStatefulConnManagement extends LocalServerTestBase { this.context.setAttribute("user", this.uid); for (int r = 0; r < this.requestCount; r++) { final HttpGet httpget = new HttpGet("/"); - final HttpResponse response = this.httpclient.execute( + final ClassicHttpResponse response = this.httpclient.execute( this.target, httpget, this.context); @@ -223,7 +223,7 @@ public class TestStatefulConnManagement extends LocalServerTestBase { // Bottom of the pool : a *keep alive* connection to Route 1. final HttpContext context1 = new BasicHttpContext(); context1.setAttribute("user", "stuff"); - final HttpResponse response1 = this.httpclient.execute( + final ClassicHttpResponse response1 = this.httpclient.execute( target, new HttpGet("/"), context1); EntityUtils.consume(response1.getEntity()); @@ -236,7 +236,7 @@ public class TestStatefulConnManagement extends LocalServerTestBase { // Send a very simple HTTP get (it MUST be simple, no auth, no proxy, no 302, no 401, ...) // Send it to another route. Must be a keepalive. final HttpContext context2 = new BasicHttpContext(); - final HttpResponse response2 = this.httpclient.execute( + final ClassicHttpResponse response2 = this.httpclient.execute( new HttpHost("127.0.0.1", this.server.getLocalPort()), new HttpGet("/"), context2); EntityUtils.consume(response2.getEntity()); // ConnPoolByRoute now has 2 free connexions, out of its 2 max. @@ -251,7 +251,7 @@ public class TestStatefulConnManagement extends LocalServerTestBase { // The killed conn is the oldest, which means the first HTTPGet ([localhost][stuff]). // When this happens, the RouteSpecificPool becomes empty. final HttpContext context3 = new BasicHttpContext(); - final HttpResponse response3 = this.httpclient.execute( + final ClassicHttpResponse response3 = this.httpclient.execute( target, new HttpGet("/"), context3); // If the ConnPoolByRoute did not behave coherently with the RouteSpecificPool diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/SessionInputBufferMock.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/SessionInputBufferMock.java deleted file mode 100644 index d0456ddb6..000000000 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/SessionInputBufferMock.java +++ /dev/null @@ -1,104 +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 - * . - * - */ - -package org.apache.hc.client5.http.impl.io; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; - -import org.apache.hc.core5.http.config.MessageConstraints; -import org.apache.hc.core5.http.impl.io.HttpTransportMetricsImpl; -import org.apache.hc.core5.http.impl.io.SessionInputBufferImpl; - -/** - * {@link org.apache.hc.core5.http.io.SessionInputBuffer} mockup implementation. - */ -public class SessionInputBufferMock extends SessionInputBufferImpl { - - public static final int BUFFER_SIZE = 16; - - public SessionInputBufferMock( - final InputStream instream, - final int buffersize, - final MessageConstraints constrains, - final CharsetDecoder decoder) { - super(new HttpTransportMetricsImpl(), buffersize, -1, constrains, decoder); - bind(instream); - } - - public SessionInputBufferMock( - final InputStream instream, - final int buffersize) { - this(instream, buffersize, null, null); - } - - public SessionInputBufferMock( - final byte[] bytes, - final int buffersize, - final MessageConstraints constrains, - final CharsetDecoder decoder) { - this(new ByteArrayInputStream(bytes), buffersize, constrains, decoder); - } - - public SessionInputBufferMock( - final byte[] bytes, - final int buffersize, - final MessageConstraints constrains) { - this(new ByteArrayInputStream(bytes), buffersize, constrains, null); - } - - public SessionInputBufferMock( - final byte[] bytes, - final int buffersize) { - this(new ByteArrayInputStream(bytes), buffersize); - } - - public SessionInputBufferMock( - final byte[] bytes) { - this(bytes, BUFFER_SIZE); - } - - public SessionInputBufferMock( - final byte[] bytes, final Charset charset) { - this(bytes, BUFFER_SIZE, null, charset != null ? charset.newDecoder() : null); - } - - public SessionInputBufferMock( - final byte[] bytes, - final CharsetDecoder decoder) { - this(bytes, BUFFER_SIZE, null, decoder); - } - - public SessionInputBufferMock( - final String s, - final Charset charset) { - this(s.getBytes(charset), charset); - } - -} diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/TestBasicHttpClientConnectionManager.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/TestBasicHttpClientConnectionManager.java index da39dcc07..cbe00253f 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/TestBasicHttpClientConnectionManager.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/TestBasicHttpClientConnectionManager.java @@ -288,8 +288,8 @@ public class TestBasicHttpClientConnectionManager { } // Should have no effect - mgr.closeExpiredConnections(); - mgr.closeIdleConnections(0L, TimeUnit.MILLISECONDS); + mgr.closeExpired(); + mgr.closeIdle(0L, TimeUnit.MILLISECONDS); mgr.shutdown(); Mockito.verify(conn, Mockito.times(1)).shutdown(); @@ -319,7 +319,7 @@ public class TestBasicHttpClientConnectionManager { Thread.sleep(50); - mgr.closeExpiredConnections(); + mgr.closeExpired(); Mockito.verify(conn).close(); } @@ -348,7 +348,7 @@ public class TestBasicHttpClientConnectionManager { Thread.sleep(100); - mgr.closeIdleConnections(50, TimeUnit.MILLISECONDS); + mgr.closeIdle(50, TimeUnit.MILLISECONDS); Mockito.verify(conn).close(); } diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/TestDefaultHttpResponseParser.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/TestDefaultHttpResponseParser.java index 8b4a34290..37cfae32c 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/TestDefaultHttpResponseParser.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/TestDefaultHttpResponseParser.java @@ -27,18 +27,20 @@ package org.apache.hc.client5.http.impl.io; +import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.HttpVersion; import org.apache.hc.core5.http.MessageConstraintException; import org.apache.hc.core5.http.NoHttpResponseException; -import org.apache.hc.core5.http.config.MessageConstraints; +import org.apache.hc.core5.http.config.H1Config; +import org.apache.hc.core5.http.impl.io.SessionInputBufferImpl; import org.apache.hc.core5.http.io.HttpMessageParser; import org.apache.hc.core5.http.io.SessionInputBuffer; import org.junit.Assert; -import org.junit.Ignore; import org.junit.Test; /** @@ -46,7 +48,7 @@ import org.junit.Test; */ public class TestDefaultHttpResponseParser { - @Test @Ignore(value = "Requires a fix in DefaultHttpResponseParser") + @Test public void testResponseParsingWithSomeGarbage() throws Exception { final String s = "garbage\r\n" + @@ -57,14 +59,15 @@ public class TestDefaultHttpResponseParser { "header2: value2\r\n" + "\r\n"; - final SessionInputBuffer inbuffer = new SessionInputBufferMock(s, StandardCharsets.US_ASCII); - final MessageConstraints messageConstraints = MessageConstraints.custom().setMaxEmptyLineCount(Integer.MAX_VALUE).build(); - final HttpMessageParser parser = new LenientHttpResponseParser(messageConstraints); + final SessionInputBuffer inbuffer = new SessionInputBufferImpl(1024); + final H1Config h1Config = H1Config.custom().setMaxEmptyLineCount(Integer.MAX_VALUE).build(); + final HttpMessageParser parser = new LenientHttpResponseParser(h1Config); - final HttpResponse response = parser.parse(inbuffer); + final HttpResponse response = parser.parse(inbuffer, + new ByteArrayInputStream(s.getBytes(StandardCharsets.US_ASCII))); Assert.assertNotNull(response); - Assert.assertEquals(HttpVersion.HTTP_1_1, response.getProtocolVersion()); - Assert.assertEquals(200, response.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpVersion.HTTP_1_1, response.getVersion()); + Assert.assertEquals(200, response.getCode()); final Header[] headers = response.getAllHeaders(); Assert.assertNotNull(headers); @@ -84,29 +87,29 @@ public class TestDefaultHttpResponseParser { "header2: value2\r\n" + "\r\n"; - final SessionInputBuffer inbuffer = new SessionInputBufferMock(s, StandardCharsets.US_ASCII); - final MessageConstraints messageConstraints = MessageConstraints.custom().setMaxEmptyLineCount(2).build(); - final HttpMessageParser parser = new LenientHttpResponseParser(messageConstraints); - parser.parse(inbuffer); + final SessionInputBuffer inbuffer = new SessionInputBufferImpl(1024); + final H1Config h1Config = H1Config.custom().setMaxEmptyLineCount(2).build(); + final HttpMessageParser parser = new LenientHttpResponseParser(h1Config); + parser.parse(inbuffer, new ByteArrayInputStream(s.getBytes(StandardCharsets.US_ASCII))); } @Test(expected=NoHttpResponseException.class) public void testResponseParsingNoResponse() throws Exception { - final SessionInputBuffer inbuffer = new SessionInputBufferMock("", StandardCharsets.US_ASCII); - final HttpMessageParser parser = new LenientHttpResponseParser(MessageConstraints.DEFAULT); - parser.parse(inbuffer); + final SessionInputBuffer inbuffer = new SessionInputBufferImpl(1024); + final HttpMessageParser parser = new LenientHttpResponseParser(H1Config.DEFAULT); + parser.parse(inbuffer, new ByteArrayInputStream(new byte[]{})); } - @Test(expected=MessageConstraintException.class) + @Test(expected=NoHttpResponseException.class) public void testResponseParsingOnlyGarbage() throws Exception { final String s = "garbage\r\n" + "garbage\r\n" + "more garbage\r\n" + "a lot more garbage\r\n"; - final SessionInputBuffer inbuffer = new SessionInputBufferMock(s, StandardCharsets.US_ASCII); - final HttpMessageParser parser = new LenientHttpResponseParser(MessageConstraints.DEFAULT); - parser.parse(inbuffer); + final SessionInputBuffer inbuffer = new SessionInputBufferImpl(1024); + final HttpMessageParser parser = new LenientHttpResponseParser(H1Config.DEFAULT); + parser.parse(inbuffer, new ByteArrayInputStream(s.getBytes(StandardCharsets.US_ASCII))); } } diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/TestPoolingHttpClientConnectionManager.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/TestPoolingHttpClientConnectionManager.java index 351ace237..9e6802ac1 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/TestPoolingHttpClientConnectionManager.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/TestPoolingHttpClientConnectionManager.java @@ -49,7 +49,8 @@ import org.apache.hc.core5.http.config.Lookup; import org.apache.hc.core5.http.config.SocketConfig; import org.apache.hc.core5.http.io.HttpClientConnection; import org.apache.hc.core5.http.protocol.HttpContext; -import org.apache.logging.log4j.LogManager; +import org.apache.hc.core5.pool.PoolEntry; +import org.apache.hc.core5.pool.StrictConnPool; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -78,9 +79,9 @@ public class TestPoolingHttpClientConnectionManager { @Mock private DnsResolver dnsResolver; @Mock - private Future future; + private Future> future; @Mock - private CPool pool; + private StrictConnPool pool; private PoolingHttpClientConnectionManager mgr; @Before @@ -95,9 +96,8 @@ public class TestPoolingHttpClientConnectionManager { final HttpHost target = new HttpHost("localhost", 80); final HttpRoute route = new HttpRoute(target); - final CPoolEntry entry = new CPoolEntry(LogManager.getLogger(getClass()), "id", route, conn, - -1, TimeUnit.MILLISECONDS); - entry.markRouteComplete(); + final PoolEntry entry = new PoolEntry<>(route, -1, TimeUnit.MILLISECONDS); + entry.assignConnection(conn); Mockito.when(future.isCancelled()).thenReturn(Boolean.FALSE); Mockito.when(socketFactoryRegistry.lookup("http")).thenReturn(plainSocketFactory); @@ -113,6 +113,8 @@ public class TestPoolingHttpClientConnectionManager { final HttpClientConnection conn1 = connRequest1.get(1, TimeUnit.SECONDS); Assert.assertNotNull(conn1); Assert.assertNotSame(conn, conn1); + final CPoolProxy poolProxy = CPoolProxy.getProxy(conn1); + poolProxy.markRouteComplete(); mgr.releaseConnection(conn1, null, 0, TimeUnit.MILLISECONDS); @@ -124,8 +126,7 @@ public class TestPoolingHttpClientConnectionManager { final HttpHost target = new HttpHost("localhost", 80); final HttpRoute route = new HttpRoute(target); - final CPoolEntry entry = new CPoolEntry(LogManager.getLogger(getClass()), "id", route, conn, - -1, TimeUnit.MILLISECONDS); + final PoolEntry entry = new PoolEntry<>(route, -1, TimeUnit.MILLISECONDS); Mockito.when(future.isCancelled()).thenReturn(Boolean.FALSE); Mockito.when(socketFactoryRegistry.lookup("http")).thenReturn(plainSocketFactory); @@ -152,9 +153,8 @@ public class TestPoolingHttpClientConnectionManager { final HttpHost target = new HttpHost("localhost", 80); final HttpRoute route = new HttpRoute(target); - final CPoolEntry entry = new CPoolEntry(LogManager.getLogger(getClass()), "id", route, conn, - -1, TimeUnit.MILLISECONDS); - entry.markRouteComplete(); + final PoolEntry entry = new PoolEntry<>(route, -1, TimeUnit.MILLISECONDS); + entry.assignConnection(conn); Mockito.when(future.isCancelled()).thenReturn(Boolean.TRUE); Mockito.when(future.get(1, TimeUnit.SECONDS)).thenReturn(entry); @@ -182,9 +182,8 @@ public class TestPoolingHttpClientConnectionManager { final HttpHost target = new HttpHost("localhost", 80); final HttpRoute route = new HttpRoute(target); - final CPoolEntry entry = Mockito.spy(new CPoolEntry(LogManager.getLogger(getClass()), "id", route, conn, - -1, TimeUnit.MILLISECONDS)); - entry.markRouteComplete(); + final PoolEntry entry = new PoolEntry<>(route, -1, TimeUnit.MILLISECONDS); + entry.assignConnection(conn); Mockito.when(future.isCancelled()).thenReturn(Boolean.FALSE); Mockito.when(future.get(1, TimeUnit.SECONDS)).thenReturn(entry); @@ -195,12 +194,13 @@ public class TestPoolingHttpClientConnectionManager { final HttpClientConnection conn1 = connRequest1.get(1, TimeUnit.SECONDS); Assert.assertNotNull(conn1); Assert.assertTrue(conn1.isOpen()); + final CPoolProxy poolProxy = CPoolProxy.getProxy(conn1); + poolProxy.markRouteComplete(); - mgr.releaseConnection(conn1, "some state", 0, TimeUnit.MILLISECONDS); + mgr.releaseConnection(conn1, "some state", 10, TimeUnit.MILLISECONDS); Mockito.verify(pool).release(entry, true); - Mockito.verify(entry).setState("some state"); - Mockito.verify(entry).updateExpiry(Mockito.anyLong(), Mockito.eq(TimeUnit.MILLISECONDS)); + Assert.assertEquals("some state", entry.getState()); } @Test @@ -208,9 +208,8 @@ public class TestPoolingHttpClientConnectionManager { final HttpHost target = new HttpHost("localhost", 80); final HttpRoute route = new HttpRoute(target); - final CPoolEntry entry = Mockito.spy(new CPoolEntry(LogManager.getLogger(getClass()), "id", route, conn, - -1, TimeUnit.MILLISECONDS)); - entry.markRouteComplete(); + final PoolEntry entry = new PoolEntry<>(route, -1, TimeUnit.MILLISECONDS); + entry.assignConnection(conn); Mockito.when(future.isCancelled()).thenReturn(Boolean.FALSE); Mockito.when(future.get(1, TimeUnit.SECONDS)).thenReturn(entry); @@ -221,12 +220,13 @@ public class TestPoolingHttpClientConnectionManager { final HttpClientConnection conn1 = connRequest1.get(1, TimeUnit.SECONDS); Assert.assertNotNull(conn1); Assert.assertFalse(conn1.isOpen()); + final CPoolProxy poolProxy = CPoolProxy.getProxy(conn1); + poolProxy.markRouteComplete(); mgr.releaseConnection(conn1, "some state", 0, TimeUnit.MILLISECONDS); Mockito.verify(pool).release(entry, false); - Mockito.verify(entry, Mockito.never()).setState(Mockito.anyObject()); - Mockito.verify(entry, Mockito.never()).updateExpiry(Mockito.anyLong(), Mockito.eq(TimeUnit.MILLISECONDS)); + Assert.assertEquals(null, entry.getState()); } @Test @@ -236,9 +236,9 @@ public class TestPoolingHttpClientConnectionManager { final InetAddress local = InetAddress.getByAddress(new byte[]{127, 0, 0, 1}); final HttpRoute route = new HttpRoute(target, local, true); - final CPoolEntry entry = new CPoolEntry(LogManager.getLogger(getClass()), "id", route, conn, - -1, TimeUnit.MILLISECONDS); - entry.markRouteComplete(); + final PoolEntry entry = new PoolEntry<>(route, -1, TimeUnit.MILLISECONDS); + entry.assignConnection(conn); + Mockito.when(future.isCancelled()).thenReturn(Boolean.FALSE); Mockito.when(conn.isOpen()).thenReturn(true); Mockito.when(future.isCancelled()).thenReturn(false); @@ -248,6 +248,8 @@ public class TestPoolingHttpClientConnectionManager { final ConnectionRequest connRequest1 = mgr.requestConnection(route, null); final HttpClientConnection conn1 = connRequest1.get(1, TimeUnit.SECONDS); Assert.assertNotNull(conn1); + final CPoolProxy poolProxy = CPoolProxy.getProxy(conn1); + poolProxy.markRouteComplete(); final HttpClientContext context = HttpClientContext.create(); final SocketConfig sconfig = SocketConfig.custom().build(); @@ -286,9 +288,9 @@ public class TestPoolingHttpClientConnectionManager { final InetAddress local = InetAddress.getByAddress(new byte[] {127, 0, 0, 1}); final HttpRoute route = new HttpRoute(target, local, proxy, true); - final CPoolEntry entry = new CPoolEntry(LogManager.getLogger(getClass()), "id", route, conn, - -1, TimeUnit.MILLISECONDS); - entry.markRouteComplete(); + final PoolEntry entry = new PoolEntry<>(route, -1, TimeUnit.MILLISECONDS); + entry.assignConnection(conn); + Mockito.when(future.isCancelled()).thenReturn(Boolean.FALSE); Mockito.when(conn.isOpen()).thenReturn(true); Mockito.when(future.isCancelled()).thenReturn(false); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/protocol/TestDefaultRedirectStrategy.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/protocol/TestDefaultRedirectStrategy.java index 30ab3dd98..13f82c86f 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/protocol/TestDefaultRedirectStrategy.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/protocol/TestDefaultRedirectStrategy.java @@ -39,16 +39,13 @@ import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.core5.http.HttpEntity; 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.HttpResponse; import org.apache.hc.core5.http.HttpStatus; -import org.apache.hc.core5.http.HttpVersion; import org.apache.hc.core5.http.ProtocolException; -import org.apache.hc.core5.http.entity.BasicHttpEntity; +import org.apache.hc.core5.http.io.entity.BasicHttpEntity; import org.apache.hc.core5.http.message.BasicHttpResponse; import org.apache.hc.core5.http.protocol.BasicHttpContext; import org.apache.hc.core5.http.protocol.HttpContext; -import org.apache.hc.core5.http.protocol.HttpCoreContext; import org.junit.Assert; import org.junit.Test; @@ -59,8 +56,7 @@ public class TestDefaultRedirectStrategy { final DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); final HttpClientContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("http://localhost/"); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); Assert.assertFalse(redirectStrategy.isRedirected(httpget, response, context)); response.setHeader(HttpHeaders.LOCATION, "http://localhost/blah"); Assert.assertTrue(redirectStrategy.isRedirected(httpget, response, context)); @@ -71,8 +67,7 @@ public class TestDefaultRedirectStrategy { final DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); final HttpClientContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("http://localhost/"); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); Assert.assertFalse(redirectStrategy.isRedirected(httpget, response, context)); } @@ -81,8 +76,7 @@ public class TestDefaultRedirectStrategy { final DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); final HttpClientContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("http://localhost/"); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_MOVED_PERMANENTLY, "Redirect"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_MOVED_PERMANENTLY, "Redirect"); Assert.assertFalse(redirectStrategy.isRedirected(httpget, response, context)); response.setHeader(HttpHeaders.LOCATION, "http://localhost/blah"); Assert.assertTrue(redirectStrategy.isRedirected(httpget, response, context)); @@ -93,8 +87,7 @@ public class TestDefaultRedirectStrategy { final DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); final HttpClientContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("http://localhost/"); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_TEMPORARY_REDIRECT, "Redirect"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_TEMPORARY_REDIRECT, "Redirect"); Assert.assertFalse(redirectStrategy.isRedirected(httpget, response, context)); response.setHeader(HttpHeaders.LOCATION, "http://localhost/blah"); Assert.assertTrue(redirectStrategy.isRedirected(httpget, response, context)); @@ -105,8 +98,7 @@ public class TestDefaultRedirectStrategy { final DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); final HttpClientContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("http://localhost/"); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_SEE_OTHER, "Redirect"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_SEE_OTHER, "Redirect"); Assert.assertFalse(redirectStrategy.isRedirected(httpget, response, context)); response.setHeader(HttpHeaders.LOCATION, "http://localhost/blah"); Assert.assertTrue(redirectStrategy.isRedirected(httpget, response, context)); @@ -117,7 +109,7 @@ public class TestDefaultRedirectStrategy { final DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); final HttpClientContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("http://localhost/"); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 333, "Redirect"); + final HttpResponse response = new BasicHttpResponse(333, "Redirect"); Assert.assertFalse(redirectStrategy.isRedirected(httpget, response, context)); final HttpPost httppost = new HttpPost("http://localhost/"); Assert.assertFalse(redirectStrategy.isRedirected(httppost, response, context)); @@ -128,8 +120,7 @@ public class TestDefaultRedirectStrategy { final DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); final HttpClientContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("http://localhost/"); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_SEE_OTHER, "Redirect"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_SEE_OTHER, "Redirect"); try { redirectStrategy.isRedirected(null, response, context); Assert.fail("IllegalArgumentException expected"); @@ -147,8 +138,7 @@ public class TestDefaultRedirectStrategy { final DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); final HttpClientContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("http://localhost/"); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); response.addHeader("Location", "http://localhost/stuff"); final URI uri = redirectStrategy.getLocationURI(httpget, response, context); Assert.assertEquals(URI.create("http://localhost/stuff"), uri); @@ -159,8 +149,7 @@ public class TestDefaultRedirectStrategy { final DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); final HttpClientContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("http://localhost/"); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); redirectStrategy.getLocationURI(httpget, response, context); } @@ -169,8 +158,7 @@ public class TestDefaultRedirectStrategy { final DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); final HttpClientContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("http://localhost/"); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); response.addHeader("Location", "http://localhost/not valid"); redirectStrategy.getLocationURI(httpget, response, context); } @@ -179,22 +167,8 @@ public class TestDefaultRedirectStrategy { public void testGetLocationUriRelative() throws Exception { final DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); final HttpClientContext context = HttpClientContext.create(); - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, new HttpHost("localhost")); final HttpGet httpget = new HttpGet("http://localhost/"); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); - response.addHeader("Location", "/stuff"); - final URI uri = redirectStrategy.getLocationURI(httpget, response, context); - Assert.assertEquals(URI.create("http://localhost/stuff"), uri); - } - - @Test(expected=IllegalStateException.class) - public void testGetLocationUriRelativeMissingTargetHost() throws Exception { - final DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); - final HttpClientContext context = HttpClientContext.create(); - final HttpGet httpget = new HttpGet("http://localhost/"); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); response.addHeader("Location", "/stuff"); final URI uri = redirectStrategy.getLocationURI(httpget, response, context); Assert.assertEquals(URI.create("http://localhost/stuff"), uri); @@ -204,10 +178,8 @@ public class TestDefaultRedirectStrategy { public void testGetLocationUriRelativeWithFragment() throws Exception { final DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); final HttpClientContext context = HttpClientContext.create(); - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, new HttpHost("localhost")); final HttpGet httpget = new HttpGet("http://localhost/"); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); response.addHeader("Location", "/stuff#fragment"); final URI uri = redirectStrategy.getLocationURI(httpget, response, context); Assert.assertEquals(URI.create("http://localhost/stuff#fragment"), uri); @@ -217,10 +189,8 @@ public class TestDefaultRedirectStrategy { public void testGetLocationUriAbsoluteWithFragment() throws Exception { final DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); final HttpClientContext context = HttpClientContext.create(); - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, new HttpHost("localhost")); final HttpGet httpget = new HttpGet("http://localhost/"); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); response.addHeader("Location", "http://localhost/stuff#fragment"); final URI uri = redirectStrategy.getLocationURI(httpget, response, context); Assert.assertEquals(URI.create("http://localhost/stuff#fragment"), uri); @@ -230,10 +200,8 @@ public class TestDefaultRedirectStrategy { public void testGetLocationUriNormalized() throws Exception { final DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); final HttpClientContext context = HttpClientContext.create(); - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, new HttpHost("localhost")); final HttpGet httpget = new HttpGet("http://localhost/"); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); response.addHeader("Location", "http://localhost/././stuff/../morestuff"); final URI uri = redirectStrategy.getLocationURI(httpget, response, context); Assert.assertEquals(URI.create("http://localhost/morestuff"), uri); @@ -243,23 +211,19 @@ public class TestDefaultRedirectStrategy { public void testGetLocationUriAllowCircularRedirects() throws Exception { final DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); final HttpClientContext context = HttpClientContext.create(); - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, new HttpHost("localhost")); final RequestConfig config = RequestConfig.custom().setCircularRedirectsAllowed(true).build(); context.setRequestConfig(config); final URI uri1 = URI.create("http://localhost/stuff1"); final URI uri2 = URI.create("http://localhost/stuff2"); final URI uri3 = URI.create("http://localhost/stuff3"); final HttpGet httpget1 = new HttpGet("http://localhost/"); - final HttpResponse response1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); + final HttpResponse response1 = new BasicHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); response1.addHeader("Location", uri1.toASCIIString()); final HttpGet httpget2 = new HttpGet(uri1.toASCIIString()); - final HttpResponse response2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); + final HttpResponse response2 = new BasicHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); response2.addHeader("Location", uri2.toASCIIString()); final HttpGet httpget3 = new HttpGet(uri2.toASCIIString()); - final HttpResponse response3 = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); + final HttpResponse response3 = new BasicHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); response3.addHeader("Location", uri3.toASCIIString()); Assert.assertEquals(uri1, redirectStrategy.getLocationURI(httpget1, response1, context)); Assert.assertEquals(uri2, redirectStrategy.getLocationURI(httpget2, response2, context)); @@ -280,12 +244,10 @@ public class TestDefaultRedirectStrategy { public void testGetLocationUriDisallowCircularRedirects() throws Exception { final DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); final HttpClientContext context = HttpClientContext.create(); - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, new HttpHost("localhost")); final HttpGet httpget = new HttpGet("http://localhost/stuff"); final RequestConfig config = RequestConfig.custom().setCircularRedirectsAllowed(false).build(); context.setRequestConfig(config); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); response.addHeader("Location", "http://localhost/stuff"); final URI uri = URI.create("http://localhost/stuff"); Assert.assertEquals(uri, redirectStrategy.getLocationURI(httpget, response, context)); @@ -297,8 +259,7 @@ public class TestDefaultRedirectStrategy { final DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); final HttpClientContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("http://localhost/"); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); response.addHeader("Location", "http://localhost/stuff"); try { redirectStrategy.getLocationURI(null, response, context); @@ -320,8 +281,7 @@ public class TestDefaultRedirectStrategy { @Test public void testGetRedirectRequest() throws Exception { final DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_SEE_OTHER, "Redirect"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_SEE_OTHER, "Redirect"); response.addHeader("Location", "http://localhost/stuff"); final HttpContext context1 = new BasicHttpContext(); final HttpUriRequest redirect1 = redirectStrategy.getRedirect( @@ -340,8 +300,7 @@ public class TestDefaultRedirectStrategy { @Test public void testGetRedirectRequestForTemporaryRedirect() throws Exception { final DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_TEMPORARY_REDIRECT, "Temporary Redirect"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_TEMPORARY_REDIRECT, "Temporary Redirect"); response.addHeader("Location", "http://localhost/stuff"); final HttpContext context1 = new BasicHttpContext(); final HttpUriRequest redirect1 = redirectStrategy.getRedirect( diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/routing/TestDefaultProxyRoutePlanner.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/routing/TestDefaultProxyRoutePlanner.java index 8a3bf03e5..14c7ee1c5 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/routing/TestDefaultProxyRoutePlanner.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/routing/TestDefaultProxyRoutePlanner.java @@ -33,7 +33,6 @@ import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpRequest; -import org.apache.hc.core5.http.HttpVersion; import org.apache.hc.core5.http.message.BasicHttpRequest; import org.apache.hc.core5.http.protocol.BasicHttpContext; import org.apache.hc.core5.http.protocol.HttpContext; @@ -62,7 +61,7 @@ public class TestDefaultProxyRoutePlanner { @Test public void testDefaultProxyDirect() throws Exception { final HttpHost target = new HttpHost("somehost", 80, "http"); - final HttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); + final HttpRequest request = new BasicHttpRequest("GET", "/"); final HttpContext context = new BasicHttpContext(); final HttpRoute route = routePlanner.determineRoute(target, request, context); @@ -77,7 +76,7 @@ public class TestDefaultProxyRoutePlanner { public void testViaProxy() throws Exception { final HttpHost target = new HttpHost("somehost", 80, "http"); final HttpHost proxy = new HttpHost("custom.proxy.host", 8080); - final HttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); + final HttpRequest request = new BasicHttpRequest("GET", "/"); final HttpClientContext context = HttpClientContext.create(); context.setRequestConfig(RequestConfig.custom().setProxy(proxy).build()); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/routing/TestDefaultRoutePlanner.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/routing/TestDefaultRoutePlanner.java index b176ad024..d52e2bd44 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/routing/TestDefaultRoutePlanner.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/routing/TestDefaultRoutePlanner.java @@ -33,7 +33,6 @@ import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpRequest; -import org.apache.hc.core5.http.HttpVersion; import org.apache.hc.core5.http.ProtocolException; import org.apache.hc.core5.http.message.BasicHttpRequest; import org.apache.hc.core5.http.protocol.BasicHttpContext; @@ -61,7 +60,7 @@ public class TestDefaultRoutePlanner { @Test public void testDirect() throws Exception { final HttpHost target = new HttpHost("somehost", 80, "http"); - final HttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); + final HttpRequest request = new BasicHttpRequest("GET", "/"); final HttpContext context = new BasicHttpContext(); final HttpRoute route = routePlanner.determineRoute(target, request, context); @@ -76,7 +75,7 @@ public class TestDefaultRoutePlanner { public void testDirectDefaultPort() throws Exception { final HttpHost target = new HttpHost("somehost", -1, "https"); Mockito.when(schemePortResolver.resolve(target)).thenReturn(443); - final HttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); + final HttpRequest request = new BasicHttpRequest("GET", "/"); final HttpContext context = new BasicHttpContext(); final HttpRoute route = routePlanner.determineRoute(target, request, context); @@ -90,7 +89,7 @@ public class TestDefaultRoutePlanner { public void testViaProxy() throws Exception { final HttpHost target = new HttpHost("somehost", 80, "http"); final HttpHost proxy = new HttpHost("proxy", 8080); - final HttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); + final HttpRequest request = new BasicHttpRequest("GET", "/"); final HttpClientContext context = HttpClientContext.create(); context.setRequestConfig(RequestConfig.custom().setProxy(proxy).build()); @@ -105,7 +104,7 @@ public class TestDefaultRoutePlanner { @Test(expected= ProtocolException.class) public void testNullTarget() throws Exception { - final HttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); + final HttpRequest request = new BasicHttpRequest("GET", "/"); final HttpContext context = new BasicHttpContext(); routePlanner.determineRoute(null, request, context); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/routing/TestSystemDefaultRoutePlanner.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/routing/TestSystemDefaultRoutePlanner.java index b19a44c7c..7d6ef151f 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/routing/TestSystemDefaultRoutePlanner.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/routing/TestSystemDefaultRoutePlanner.java @@ -39,7 +39,6 @@ import org.apache.hc.client5.http.HttpRoute; import org.apache.hc.client5.http.SchemePortResolver; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpRequest; -import org.apache.hc.core5.http.HttpVersion; import org.apache.hc.core5.http.message.BasicHttpRequest; import org.apache.hc.core5.http.protocol.BasicHttpContext; import org.apache.hc.core5.http.protocol.HttpContext; @@ -69,7 +68,7 @@ public class TestSystemDefaultRoutePlanner { @Test public void testDirect() throws Exception { final HttpHost target = new HttpHost("somehost", 80, "http"); - final HttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); + final HttpRequest request = new BasicHttpRequest("GET", "/"); final HttpContext context = new BasicHttpContext(); final HttpRoute route = routePlanner.determineRoute(target, request, context); @@ -84,7 +83,7 @@ public class TestSystemDefaultRoutePlanner { public void testDirectDefaultPort() throws Exception { final HttpHost target = new HttpHost("somehost", -1, "https"); Mockito.when(schemePortResolver.resolve(target)).thenReturn(443); - final HttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); + final HttpRequest request = new BasicHttpRequest("GET", "/"); final HttpContext context = new BasicHttpContext(); final HttpRoute route = routePlanner.determineRoute(target, request, context); @@ -111,7 +110,7 @@ public class TestSystemDefaultRoutePlanner { final HttpHost target = new HttpHost("somehost", 80, "http"); final HttpRequest request = - new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); + new BasicHttpRequest("GET", "/"); final HttpContext context = new BasicHttpContext(); final HttpRoute route = routePlanner.determineRoute(target, request, context); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/MockConnPoolControl.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/MockConnPoolControl.java index c962f28bd..75497778c 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/MockConnPoolControl.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/MockConnPoolControl.java @@ -28,6 +28,7 @@ package org.apache.hc.client5.http.impl.sync; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; import org.apache.hc.client5.http.HttpRoute; import org.apache.hc.core5.pool.ConnPoolControl; @@ -92,6 +93,14 @@ public final class MockConnPoolControl implements ConnPoolControl { } } + @Override + public void closeIdle(final long idletime, final TimeUnit tunit) { + } + + @Override + public void closeExpired() { + } + public void setMaxForRoutes(final Map map) { if (map == null) { return; diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestCloseableHttpClient.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestCloseableHttpClient.java index b575aef34..feeeb862e 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestCloseableHttpClient.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestCloseableHttpClient.java @@ -29,14 +29,13 @@ package org.apache.hc.client5.http.impl.sync; import java.io.IOException; import java.io.InputStream; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpGet; -import org.apache.hc.client5.http.protocol.ClientProtocolException; -import org.apache.hc.client5.http.sync.ResponseHandler; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.HttpHost; -import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.HttpResponse; +import org.apache.hc.core5.http.io.ResponseHandler; import org.apache.hc.core5.http.protocol.HttpContext; import org.junit.Assert; import org.junit.Before; @@ -54,7 +53,7 @@ public class TestCloseableHttpClient { @Override protected CloseableHttpResponse doExecute( final HttpHost target, - final HttpRequest request, + final ClassicHttpRequest request, final HttpContext context) throws IOException { return null; } @@ -64,13 +63,15 @@ public class TestCloseableHttpClient { private NoopCloseableHttpClient client; private InputStream content; private HttpEntity entity; + private ClassicHttpResponse originResponse; private CloseableHttpResponse response; @Before public void setup() throws Exception { content = Mockito.mock(InputStream.class); entity = Mockito.mock(HttpEntity.class); - response = Mockito.mock(CloseableHttpResponse.class); + originResponse = Mockito.mock(ClassicHttpResponse.class); + response = CloseableHttpResponse.adapt(originResponse); Mockito.when(entity.getContent()).thenReturn(content); Mockito.when(entity.isStreaming()).thenReturn(Boolean.TRUE); Mockito.when(response.getEntity()).thenReturn(entity); @@ -99,23 +100,6 @@ public class TestCloseableHttpClient { (HttpContext) Mockito.isNull()); } - @Test - public void testExecuteRequestInvalidHost() throws Exception { - final HttpGet httpget = new HttpGet("http://_/stuff"); - client.execute(httpget); - - Mockito.verify(client).doExecute( - Mockito.eq(new HttpHost("_", -1, "http")), - Mockito.same(httpget), - (HttpContext) Mockito.isNull()); - } - - @Test(expected=ClientProtocolException.class) - public void testExecuteRequestInvalidHost2() throws Exception { - final HttpGet httpget = new HttpGet("http://@/stuff"); - client.execute(httpget); - } - @Test public void testExecuteRequest() throws Exception { final HttpGet httpget = new HttpGet("https://somehost:444/stuff"); @@ -166,7 +150,7 @@ public class TestCloseableHttpClient { Mockito.eq(new HttpHost("somehost", 444, "https")), Mockito.same(httpget), (HttpContext) Mockito.isNull()); - Mockito.verify(response).close(); + Mockito.verify(originResponse).close(); throw ex; } } diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestDefaultBackoffStrategy.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestDefaultBackoffStrategy.java index 7a25dba50..7a6fff712 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestDefaultBackoffStrategy.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestDefaultBackoffStrategy.java @@ -36,7 +36,6 @@ import org.apache.hc.client5.http.ConnectionPoolTimeoutException; import org.apache.hc.client5.http.sync.ConnectionBackoffStrategy; import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.HttpStatus; -import org.apache.hc.core5.http.HttpVersion; import org.apache.hc.core5.http.message.BasicHttpResponse; import org.junit.Before; import org.junit.Test; @@ -73,8 +72,7 @@ public class TestDefaultBackoffStrategy { @Test public void backsOffForServiceUnavailable() { - final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_SERVICE_UNAVAILABLE, "Service Unavailable"); + final HttpResponse resp = new BasicHttpResponse(HttpStatus.SC_SERVICE_UNAVAILABLE, "Service Unavailable"); assertTrue(impl.shouldBackoff(resp)); } @@ -84,8 +82,7 @@ public class TestDefaultBackoffStrategy { if (i == HttpStatus.SC_SERVICE_UNAVAILABLE) { continue; } - final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, - i, "Foo"); + final HttpResponse resp = new BasicHttpResponse(i, "Foo"); assertFalse(impl.shouldBackoff(resp)); } } diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestDefaultServiceUnavailableRetryStrategy.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestDefaultServiceUnavailableRetryStrategy.java index 35d78f4b8..51759639e 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestDefaultServiceUnavailableRetryStrategy.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestDefaultServiceUnavailableRetryStrategy.java @@ -31,7 +31,6 @@ import java.util.Date; import org.apache.hc.client5.http.utils.DateUtils; import org.apache.hc.core5.http.HttpHeaders; import org.apache.hc.core5.http.HttpResponse; -import org.apache.hc.core5.http.HttpVersion; import org.apache.hc.core5.http.message.BasicHttpResponse; import org.junit.Assert; import org.junit.Before; @@ -48,12 +47,12 @@ public class TestDefaultServiceUnavailableRetryStrategy { @Test public void testBasics() throws Exception { - final HttpResponse response1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 503, "Oppsie"); + final HttpResponse response1 = new BasicHttpResponse(503, "Oppsie"); Assert.assertTrue(this.impl.retryRequest(response1, 1, null)); Assert.assertTrue(this.impl.retryRequest(response1, 2, null)); Assert.assertTrue(this.impl.retryRequest(response1, 3, null)); Assert.assertFalse(this.impl.retryRequest(response1, 4, null)); - final HttpResponse response2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 500, "Big Time Oppsie"); + final HttpResponse response2 = new BasicHttpResponse(500, "Big Time Oppsie"); Assert.assertFalse(this.impl.retryRequest(response2, 1, null)); Assert.assertEquals(1234, this.impl.getRetryInterval(response1, null)); @@ -61,7 +60,7 @@ public class TestDefaultServiceUnavailableRetryStrategy { @Test public void testRetryAfterHeaderAsLong() throws Exception { - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 503, "Oppsie"); + final HttpResponse response = new BasicHttpResponse(503, "Oppsie"); response.setHeader(HttpHeaders.RETRY_AFTER, "321"); Assert.assertEquals(321000, this.impl.getRetryInterval(response, null)); @@ -70,7 +69,7 @@ public class TestDefaultServiceUnavailableRetryStrategy { @Test public void testRetryAfterHeaderAsDate() throws Exception { this.impl = new DefaultServiceUnavailableRetryStrategy(3, 1); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 503, "Oppsie"); + final HttpResponse response = new BasicHttpResponse(503, "Oppsie"); response.setHeader(HttpHeaders.RETRY_AFTER, DateUtils.formatDate(new Date(System.currentTimeMillis() + 100000L))); @@ -79,7 +78,7 @@ public class TestDefaultServiceUnavailableRetryStrategy { @Test public void testRetryAfterHeaderAsPastDate() throws Exception { - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 503, "Oppsie"); + final HttpResponse response = new BasicHttpResponse(503, "Oppsie"); response.setHeader(HttpHeaders.RETRY_AFTER, DateUtils.formatDate(new Date(System.currentTimeMillis() - 100000L))); @@ -90,7 +89,7 @@ public class TestDefaultServiceUnavailableRetryStrategy { public void testInvalidRetryAfterHeader() throws Exception { final DefaultServiceUnavailableRetryStrategy impl = new DefaultServiceUnavailableRetryStrategy(3, 1234); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 503, "Oppsie"); + final HttpResponse response = new BasicHttpResponse(503, "Oppsie"); response.setHeader(HttpHeaders.RETRY_AFTER, "Stuff"); Assert.assertEquals(1234, impl.getRetryInterval(response, null)); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestFutureRequestExecutionService.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestFutureRequestExecutionService.java index 3bd260818..bdf2a9313 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestFutureRequestExecutionService.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestFutureRequestExecutionService.java @@ -41,14 +41,14 @@ import java.util.concurrent.atomic.AtomicBoolean; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.client5.http.protocol.HttpClientContext; -import org.apache.hc.client5.http.sync.ResponseHandler; 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.HttpException; -import org.apache.hc.core5.http.HttpRequest; -import org.apache.hc.core5.http.HttpResponse; -import org.apache.hc.core5.http.bootstrap.io.HttpServer; -import org.apache.hc.core5.http.bootstrap.io.ServerBootstrap; +import org.apache.hc.core5.http.impl.io.bootstrap.HttpServer; +import org.apache.hc.core5.http.impl.io.bootstrap.ServerBootstrap; import org.apache.hc.core5.http.io.HttpRequestHandler; +import org.apache.hc.core5.http.io.ResponseHandler; import org.apache.hc.core5.http.protocol.HttpContext; import org.junit.After; import org.junit.Assert; @@ -71,7 +71,8 @@ public class TestFutureRequestExecutionService { @Override public void handle( - final HttpRequest request, final HttpResponse response, + final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { try { while(blocked.get()) { @@ -80,7 +81,7 @@ public class TestFutureRequestExecutionService { } catch (final InterruptedException e) { throw new IllegalStateException(e); } - response.setStatusCode(200); + response.setCode(200); } }).create(); @@ -187,8 +188,8 @@ public class TestFutureRequestExecutionService { private final class OkidokiHandler implements ResponseHandler { @Override public Boolean handleResponse( - final HttpResponse response) throws IOException { - return response.getStatusLine().getStatusCode() == 200; + final ClassicHttpResponse response) throws IOException { + return response.getCode() == 200; } } diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestIdleConnectionEvictor.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestIdleConnectionEvictor.java index a690302e5..5341080ea 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestIdleConnectionEvictor.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestIdleConnectionEvictor.java @@ -48,8 +48,8 @@ public class TestIdleConnectionEvictor { Thread.sleep(1000); - Mockito.verify(cm, Mockito.atLeast(1)).closeExpiredConnections(); - Mockito.verify(cm, Mockito.atLeast(1)).closeIdleConnections(3000, TimeUnit.MILLISECONDS); + Mockito.verify(cm, Mockito.atLeast(1)).closeExpired(); + Mockito.verify(cm, Mockito.atLeast(1)).closeIdle(3000, TimeUnit.MILLISECONDS); Assert.assertTrue(connectionEvictor.isRunning()); @@ -67,8 +67,8 @@ public class TestIdleConnectionEvictor { Thread.sleep(1000); - Mockito.verify(cm, Mockito.atLeast(1)).closeExpiredConnections(); - Mockito.verify(cm, Mockito.never()).closeIdleConnections(Mockito.anyLong(), Mockito.any()); + Mockito.verify(cm, Mockito.atLeast(1)).closeExpired(); + Mockito.verify(cm, Mockito.never()).closeIdle(Mockito.anyLong(), Mockito.any()); Assert.assertTrue(connectionEvictor.isRunning()); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestInternalHttpClient.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestInternalHttpClient.java index 7feb41d69..fbdb01508 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestInternalHttpClient.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestInternalHttpClient.java @@ -38,12 +38,13 @@ import org.apache.hc.client5.http.cookie.CookieSpecProvider; import org.apache.hc.client5.http.cookie.CookieStore; import org.apache.hc.client5.http.io.HttpClientConnectionManager; import org.apache.hc.client5.http.methods.HttpGet; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.ClientProtocolException; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.routing.HttpRoutePlanner; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpHost; +import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.config.Lookup; import org.junit.Assert; import org.junit.Before; @@ -95,7 +96,7 @@ public class TestInternalHttpClient { final HttpGet httpget = new HttpGet("http://somehost/stuff"); final HttpRoute route = new HttpRoute(new HttpHost("somehost", 80)); - final ArgumentCaptor argcap = ArgumentCaptor.forClass(HttpRequestWrapper.class); + final ArgumentCaptor argcap = ArgumentCaptor.forClass(HttpRequest.class); Mockito.when(routePlanner.determineRoute( Mockito.eq(new HttpHost("somehost")), argcap.capture(), @@ -104,11 +105,10 @@ public class TestInternalHttpClient { client.execute(httpget); Assert.assertNotNull(argcap.getValue()); - Assert.assertSame(httpget, argcap.getValue().getOriginal()); + Assert.assertSame(httpget, argcap.getValue()); Mockito.verify(execChain).execute( - Mockito.same(route), - Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.same(httpget)); } @@ -120,11 +120,10 @@ public class TestInternalHttpClient { Mockito.when(routePlanner.determineRoute( Mockito.eq(new HttpHost("somehost")), - Mockito.any(), + Mockito.any(), Mockito.any())).thenReturn(route); Mockito.when(execChain.execute( - Mockito.same(route), - Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.same(httpget))).thenThrow(new HttpException()); @@ -134,6 +133,13 @@ public class TestInternalHttpClient { @Test public void testExecuteDefaultContext() throws Exception { final HttpGet httpget = new HttpGet("http://somehost/stuff"); + final HttpRoute route = new HttpRoute(new HttpHost("somehost", 80)); + + Mockito.when(routePlanner.determineRoute( + Mockito.eq(new HttpHost("somehost")), + Mockito.any(), + Mockito.any())).thenReturn(route); + final HttpClientContext context = HttpClientContext.create(); client.execute(httpget, context); @@ -147,6 +153,12 @@ public class TestInternalHttpClient { @Test public void testExecuteRequestConfig() throws Exception { final HttpGet httpget = new HttpGet("http://somehost/stuff"); + final HttpRoute route = new HttpRoute(new HttpHost("somehost", 80)); + + Mockito.when(routePlanner.determineRoute( + Mockito.eq(new HttpHost("somehost")), + Mockito.any(), + Mockito.any())).thenReturn(route); final RequestConfig config = RequestConfig.custom().build(); httpget.setConfig(config); @@ -160,6 +172,13 @@ public class TestInternalHttpClient { @Test public void testExecuteLocalContext() throws Exception { final HttpGet httpget = new HttpGet("http://somehost/stuff"); + final HttpRoute route = new HttpRoute(new HttpHost("somehost", 80)); + + Mockito.when(routePlanner.determineRoute( + Mockito.eq(new HttpHost("somehost")), + Mockito.any(), + Mockito.any())).thenReturn(route); + final HttpClientContext context = HttpClientContext.create(); final Lookup localCookieSpecRegistry = Mockito.mock(Lookup.class); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestMainClientExec.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestMainClientExec.java index 22118d2c0..8de4441d1 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestMainClientExec.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestMainClientExec.java @@ -52,16 +52,17 @@ import org.apache.hc.client5.http.impl.auth.NTLMScheme; import org.apache.hc.client5.http.impl.io.ConnectionShutdownException; import org.apache.hc.client5.http.io.ConnectionRequest; import org.apache.hc.client5.http.io.HttpClientConnectionManager; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpExecutionAware; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.client5.http.methods.HttpPost; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.AuthenticationStrategy; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.protocol.NonRepeatableRequestException; import org.apache.hc.client5.http.protocol.UserTokenHandler; import org.apache.hc.core5.concurrent.Cancellable; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.ConnectionReuseStrategy; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpHeaders; @@ -69,11 +70,11 @@ import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.HttpVersion; -import org.apache.hc.core5.http.entity.EntityUtils; -import org.apache.hc.core5.http.entity.StringEntity; import org.apache.hc.core5.http.impl.io.HttpRequestExecutor; import org.apache.hc.core5.http.io.HttpClientConnection; -import org.apache.hc.core5.http.message.BasicHttpResponse; +import org.apache.hc.core5.http.io.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.StringEntity; +import org.apache.hc.core5.http.message.BasicClassicHttpResponse; import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.http.protocol.HttpProcessor; import org.junit.Assert; @@ -140,15 +141,14 @@ public class TestMainClientExec { .setConnectionRequestTimeout(345) .build(); context.setRequestConfig(config); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); + final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK"); Mockito.when(requestExecutor.execute( Mockito.same(request), Mockito.any(), Mockito.any())).thenReturn(response); - final CloseableHttpResponse finalResponse = mainClientExec.execute( - route, request, context, execAware); + final ClassicHttpResponse finalResponse = mainClientExec.execute(request, context, execAware); Mockito.verify(connManager).requestConnection(route, null); Mockito.verify(connRequest).get(345, TimeUnit.MILLISECONDS); Mockito.verify(execAware, Mockito.times(1)).setCancellable(connRequest); @@ -163,7 +163,7 @@ public class TestMainClientExec { Assert.assertSame(managedConn, context.getConnection()); Assert.assertNull(context.getUserToken()); Assert.assertNotNull(finalResponse); - Assert.assertTrue(finalResponse instanceof HttpResponseProxy); + Assert.assertTrue(finalResponse instanceof CloseableHttpResponse); } @Test @@ -174,8 +174,8 @@ public class TestMainClientExec { .setConnectionRequestTimeout(345) .build(); context.setRequestConfig(config); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); + final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK"); Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE); Mockito.when(managedConn.isStale()).thenReturn(Boolean.FALSE); @@ -191,8 +191,7 @@ public class TestMainClientExec { Mockito.same(response), Mockito.any())).thenReturn(678L); - final CloseableHttpResponse finalResponse = mainClientExec.execute( - route, request, context, execAware); + final ClassicHttpResponse finalResponse = mainClientExec.execute(request, context, execAware); Mockito.verify(connManager).requestConnection(route, null); Mockito.verify(connRequest).get(345, TimeUnit.MILLISECONDS); Mockito.verify(requestExecutor, Mockito.times(1)).execute(request, managedConn, context); @@ -200,7 +199,7 @@ public class TestMainClientExec { Mockito.verify(managedConn, Mockito.never()).close(); Assert.assertNotNull(finalResponse); - Assert.assertTrue(finalResponse instanceof HttpResponseProxy); + Assert.assertTrue(finalResponse instanceof CloseableHttpResponse); } @Test @@ -211,8 +210,8 @@ public class TestMainClientExec { .setConnectionRequestTimeout(345) .build(); context.setRequestConfig(config); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); + final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK"); Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE); Mockito.when(managedConn.isStale()).thenReturn(Boolean.FALSE); @@ -228,7 +227,7 @@ public class TestMainClientExec { Mockito.same(route), Mockito.any())).thenReturn("this and that"); - mainClientExec.execute(route, request, context, execAware); + mainClientExec.execute(request, context, execAware); Mockito.verify(connManager).requestConnection(route, null); Mockito.verify(connRequest).get(345, TimeUnit.MILLISECONDS); Mockito.verify(requestExecutor, Mockito.times(1)).execute(request, managedConn, context); @@ -246,8 +245,8 @@ public class TestMainClientExec { .setConnectionRequestTimeout(345) .build(); context.setRequestConfig(config); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); + final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK"); // The entity is streaming response.setEntity(EntityBuilder.create() .setStream(new ByteArrayInputStream(new byte[]{})) @@ -264,8 +263,7 @@ public class TestMainClientExec { Mockito.same(response), Mockito.any())).thenReturn(Boolean.FALSE); - final CloseableHttpResponse finalResponse = mainClientExec.execute( - route, request, context, execAware); + final ClassicHttpResponse finalResponse = mainClientExec.execute(request, context, execAware); Mockito.verify(connManager).requestConnection(route, null); Mockito.verify(connRequest).get(345, TimeUnit.MILLISECONDS); Mockito.verify(requestExecutor, Mockito.times(1)).execute(request, managedConn, context); @@ -277,7 +275,7 @@ public class TestMainClientExec { Mockito.verify(managedConn, Mockito.never()).close(); Assert.assertNotNull(finalResponse); - Assert.assertTrue(finalResponse instanceof HttpResponseProxy); + Assert.assertTrue(finalResponse instanceof CloseableHttpResponse); finalResponse.close(); Mockito.verify(connManager, Mockito.times(1)).releaseConnection( @@ -290,16 +288,16 @@ public class TestMainClientExec { final HttpRoute route = new HttpRoute(target); final HttpClientContext context = new HttpClientContext(); final RequestConfig config = RequestConfig.custom().setSocketTimeout(3000).build(); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); context.setRequestConfig(config); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK"); Mockito.when(managedConn.isOpen()).thenReturn(true); Mockito.when(requestExecutor.execute( Mockito.same(request), Mockito.any(), Mockito.any())).thenReturn(response); - mainClientExec.execute(route, request, context, execAware); + mainClientExec.execute(request, context, execAware); Mockito.verify(managedConn).setSocketTimeout(3000); } @@ -307,15 +305,15 @@ public class TestMainClientExec { public void testSocketTimeoutReset() throws Exception { final HttpRoute route = new HttpRoute(target); final HttpClientContext context = new HttpClientContext(); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); + final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK"); Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE); Mockito.when(requestExecutor.execute( Mockito.same(request), Mockito.any(), Mockito.any())).thenReturn(response); - mainClientExec.execute(route, request, context, execAware); + mainClientExec.execute(request, context, execAware); Mockito.verify(managedConn, Mockito.never()).setSocketTimeout(Mockito.anyInt()); } @@ -323,12 +321,12 @@ public class TestMainClientExec { public void testExecAbortedPriorToConnectionLease() throws Exception { final HttpRoute route = new HttpRoute(target); final HttpClientContext context = new HttpClientContext(); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); Mockito.when(managedConn.isOpen()).thenReturn(Boolean.FALSE); Mockito.when(execAware.isAborted()).thenReturn(Boolean.TRUE); try { - mainClientExec.execute(route, request, context, execAware); + mainClientExec.execute(request, context, execAware); } catch (final IOException ex) { Mockito.verify(connRequest, Mockito.times(1)).cancel(); throw ex; @@ -343,12 +341,12 @@ public class TestMainClientExec { .setConnectionRequestTimeout(345) .build(); context.setRequestConfig(config); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); Mockito.when(managedConn.isOpen()).thenReturn(Boolean.FALSE); Mockito.when(execAware.isAborted()).thenReturn(Boolean.FALSE, Boolean.TRUE); try { - mainClientExec.execute(route, request, context, execAware); + mainClientExec.execute(request, context, execAware); } catch (final IOException ex) { Mockito.verify(connRequest, Mockito.times(1)).get(345, TimeUnit.MILLISECONDS); Mockito.verify(execAware, Mockito.times(2)).setCancellable(Mockito.any()); @@ -370,12 +368,12 @@ public class TestMainClientExec { .setConnectionRequestTimeout(345) .build(); context.setRequestConfig(config); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); Mockito.when(managedConn.isOpen()).thenReturn(Boolean.FALSE); Mockito.when(execAware.isAborted()).thenReturn(Boolean.FALSE, Boolean.FALSE, Boolean.TRUE); try { - mainClientExec.execute(route, request, context, execAware); + mainClientExec.execute(request, context, execAware); } catch (final IOException ex) { Mockito.verify(connRequest, Mockito.times(1)).get(345, TimeUnit.MILLISECONDS); Mockito.verify(connManager, Mockito.times(1)).connect(managedConn, route, 567, context); @@ -391,25 +389,25 @@ public class TestMainClientExec { public void testExecConnectionRequestFailed() throws Exception { final HttpRoute route = new HttpRoute(target); final HttpClientContext context = new HttpClientContext(); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); Mockito.when(connRequest.get(Mockito.anyInt(), Mockito.any())) .thenThrow(new ExecutionException("Opppsie", null)); - mainClientExec.execute(route, request, context, execAware); + mainClientExec.execute(request, context, execAware); } @Test public void testExecRequestRetryOnAuthChallenge() throws Exception { final HttpRoute route = new HttpRoute(target); final HttpClientContext context = new HttpClientContext(); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); - final HttpResponse response1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 401, "Huh?"); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://foo/test"), route); + final ClassicHttpResponse response1 = new BasicClassicHttpResponse(401, "Huh?"); response1.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=test"); final InputStream instream1 = Mockito.spy(new ByteArrayInputStream(new byte[] {1, 2, 3})); response1.setEntity(EntityBuilder.create() .setStream(instream1) .build()); - final HttpResponse response2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final ClassicHttpResponse response2 = new BasicClassicHttpResponse(200, "OK"); final InputStream instream2 = Mockito.spy(new ByteArrayInputStream(new byte[] {2, 3, 4})); response2.setEntity(EntityBuilder.create() .setStream(instream2) @@ -434,27 +432,27 @@ public class TestMainClientExec { Mockito.>any(), Mockito.any())).thenReturn(Collections.singletonList(new BasicScheme())); - final CloseableHttpResponse finalResponse = mainClientExec.execute( - route, request, context, execAware); + final ClassicHttpResponse finalResponse = mainClientExec.execute( + request, context, execAware); Mockito.verify(requestExecutor, Mockito.times(2)).execute(request, managedConn, context); Mockito.verify(instream1).close(); Mockito.verify(instream2, Mockito.never()).close(); Assert.assertNotNull(finalResponse); - Assert.assertEquals(200, finalResponse.getStatusLine().getStatusCode()); + Assert.assertEquals(200, finalResponse.getCode()); } @Test public void testExecEntityEnclosingRequestRetryOnAuthChallenge() throws Exception { final HttpRoute route = new HttpRoute(target, proxy); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); - final HttpResponse response1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 401, "Huh?"); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://foo/test"), route); + final ClassicHttpResponse response1 = new BasicClassicHttpResponse(401, "Huh?"); response1.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=test"); final InputStream instream1 = Mockito.spy(new ByteArrayInputStream(new byte[] {1, 2, 3})); response1.setEntity(EntityBuilder.create() .setStream(instream1) .build()); - final HttpResponse response2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final ClassicHttpResponse response2 = new BasicClassicHttpResponse(200, "OK"); final InputStream instream2 = Mockito.spy(new ByteArrayInputStream(new byte[] {2, 3, 4})); response2.setEntity(EntityBuilder.create() .setStream(instream2) @@ -487,14 +485,14 @@ public class TestMainClientExec { Mockito.>any(), Mockito.any())).thenReturn(Collections.singletonList(new BasicScheme())); - final CloseableHttpResponse finalResponse = mainClientExec.execute( - route, request, context, execAware); + final ClassicHttpResponse finalResponse = mainClientExec.execute( + request, context, execAware); Mockito.verify(requestExecutor, Mockito.times(2)).execute(request, managedConn, context); Mockito.verify(managedConn).close(); Mockito.verify(instream2, Mockito.never()).close(); Assert.assertNotNull(finalResponse); - Assert.assertEquals(200, finalResponse.getStatusLine().getStatusCode()); + Assert.assertEquals(200, finalResponse.getCode()); Assert.assertNull(proxyAuthExchange.getAuthScheme()); } @@ -502,14 +500,14 @@ public class TestMainClientExec { public void testExecEntityEnclosingRequest() throws Exception { final HttpRoute route = new HttpRoute(target); final HttpClientContext context = new HttpClientContext(); - final HttpPost post = new HttpPost("http://bar/test"); + final HttpPost post = new HttpPost("http://foo/test"); final InputStream instream0 = new ByteArrayInputStream(new byte[] {1, 2, 3}); post.setEntity(EntityBuilder.create() .setStream(instream0) .build()); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(post, target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(post, route); - final HttpResponse response1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 401, "Huh?"); + final ClassicHttpResponse response1 = new BasicClassicHttpResponse(401, "Huh?"); response1.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=test"); final InputStream instream1 = new ByteArrayInputStream(new byte[] {1, 2, 3}); response1.setEntity(EntityBuilder.create() @@ -530,7 +528,7 @@ public class TestMainClientExec { @Override public HttpResponse answer(final InvocationOnMock invocationOnMock) throws Throwable { final Object[] args = invocationOnMock.getArguments(); - final HttpRequest requestEE = (HttpRequest) args[0]; + final ClassicHttpRequest requestEE = (ClassicHttpRequest) args[0]; requestEE.getEntity().writeTo(new ByteArrayOutputStream()); return response1; } @@ -546,36 +544,36 @@ public class TestMainClientExec { Mockito.>any(), Mockito.any())).thenReturn(Collections.singletonList(new BasicScheme())); - mainClientExec.execute(route, request, context, execAware); + mainClientExec.execute(request, context, execAware); } @Test(expected=InterruptedIOException.class) public void testExecConnectionShutDown() throws Exception { final HttpRoute route = new HttpRoute(target); final HttpClientContext context = new HttpClientContext(); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); Mockito.when(requestExecutor.execute( - Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any())).thenThrow(new ConnectionShutdownException()); - mainClientExec.execute(route, request, context, execAware); + mainClientExec.execute(request, context, execAware); } @Test(expected=RuntimeException.class) public void testExecRuntimeException() throws Exception { final HttpRoute route = new HttpRoute(target); final HttpClientContext context = new HttpClientContext(); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); Mockito.when(requestExecutor.execute( - Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any())).thenThrow(new RuntimeException("Ka-boom")); try { - mainClientExec.execute(route, request, context, execAware); + mainClientExec.execute(request, context, execAware); } catch (final Exception ex) { Mockito.verify(connManager).releaseConnection(managedConn, null, 0, TimeUnit.MILLISECONDS); @@ -587,15 +585,15 @@ public class TestMainClientExec { public void testExecHttpException() throws Exception { final HttpRoute route = new HttpRoute(target); final HttpClientContext context = new HttpClientContext(); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); Mockito.when(requestExecutor.execute( - Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any())).thenThrow(new HttpException("Ka-boom")); try { - mainClientExec.execute(route, request, context, execAware); + mainClientExec.execute(request, context, execAware); } catch (final Exception ex) { Mockito.verify(connManager).releaseConnection(managedConn, null, 0, TimeUnit.MILLISECONDS); @@ -607,15 +605,15 @@ public class TestMainClientExec { public void testExecIOException() throws Exception { final HttpRoute route = new HttpRoute(target); final HttpClientContext context = new HttpClientContext(); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); Mockito.when(requestExecutor.execute( - Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any())).thenThrow(new IOException("Ka-boom")); try { - mainClientExec.execute(route, request, context, execAware); + mainClientExec.execute(request, context, execAware); } catch (final Exception ex) { Mockito.verify(connManager).releaseConnection(managedConn, null, 0, TimeUnit.MILLISECONDS); @@ -631,7 +629,7 @@ public class TestMainClientExec { .setConnectTimeout(567) .build(); context.setRequestConfig(config); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE); @@ -649,7 +647,7 @@ public class TestMainClientExec { .setConnectTimeout(567) .build(); context.setRequestConfig(config); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE); @@ -667,12 +665,12 @@ public class TestMainClientExec { .setConnectTimeout(321) .build(); context.setRequestConfig(config); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); + final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK"); Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE); Mockito.when(requestExecutor.execute( - Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(response); @@ -680,28 +678,28 @@ public class TestMainClientExec { Mockito.verify(connManager).connect(managedConn, route, 321, context); Mockito.verify(connManager).routeComplete(managedConn, route, context); - final ArgumentCaptor reqCaptor = ArgumentCaptor.forClass(HttpRequest.class); + final ArgumentCaptor reqCaptor = ArgumentCaptor.forClass(ClassicHttpRequest.class); Mockito.verify(requestExecutor).execute( reqCaptor.capture(), Mockito.same(managedConn), Mockito.same(context)); final HttpRequest connect = reqCaptor.getValue(); Assert.assertNotNull(connect); - Assert.assertEquals("CONNECT", connect.getRequestLine().getMethod()); - Assert.assertEquals(HttpVersion.HTTP_1_1, connect.getRequestLine().getProtocolVersion()); - Assert.assertEquals("foo:80", connect.getRequestLine().getUri()); + Assert.assertEquals("CONNECT", connect.getMethod()); + Assert.assertEquals(HttpVersion.HTTP_1_1, connect.getVersion()); + Assert.assertEquals("foo:80", connect.getRequestUri()); } @Test(expected = HttpException.class) public void testEstablishRouteViaProxyTunnelUnexpectedResponse() throws Exception { final HttpRoute route = new HttpRoute(target, null, proxy, true); final HttpClientContext context = new HttpClientContext(); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 101, "Lost"); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); + final ClassicHttpResponse response = new BasicClassicHttpResponse(101, "Lost"); Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE); Mockito.when(requestExecutor.execute( - Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(response); @@ -712,20 +710,20 @@ public class TestMainClientExec { public void testEstablishRouteViaProxyTunnelFailure() throws Exception { final HttpRoute route = new HttpRoute(target, null, proxy, true); final HttpClientContext context = new HttpClientContext(); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 500, "Boom"); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); + final ClassicHttpResponse response = new BasicClassicHttpResponse(500, "Boom"); response.setEntity(new StringEntity("Ka-boom")); Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE); Mockito.when(requestExecutor.execute( - Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(response); try { mainClientExec.establishRoute(managedConn, route, request, context); } catch (final TunnelRefusedException ex) { - final HttpResponse r = ex.getResponse(); + final ClassicHttpResponse r = ex.getResponse(); Assert.assertEquals("Ka-boom", EntityUtils.toString(r.getEntity())); Mockito.verify(managedConn).close(); @@ -742,14 +740,14 @@ public class TestMainClientExec { .setConnectTimeout(567) .build(); context.setRequestConfig(config); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); - final HttpResponse response1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 407, "Huh?"); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); + final ClassicHttpResponse response1 = new BasicClassicHttpResponse(407, "Huh?"); response1.setHeader(HttpHeaders.PROXY_AUTHENTICATE, "Basic realm=test"); final InputStream instream1 = Mockito.spy(new ByteArrayInputStream(new byte[] {1, 2, 3})); response1.setEntity(EntityBuilder.create() .setStream(instream1) .build()); - final HttpResponse response2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final ClassicHttpResponse response2 = new BasicClassicHttpResponse(200, "OK"); final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials("user", "pass".toCharArray())); @@ -761,7 +759,7 @@ public class TestMainClientExec { Mockito.any(), Mockito.any())).thenReturn(Boolean.TRUE); Mockito.when(requestExecutor.execute( - Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(response1, response2); @@ -785,14 +783,14 @@ public class TestMainClientExec { .setConnectTimeout(567) .build(); context.setRequestConfig(config); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); - final HttpResponse response1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 407, "Huh?"); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); + final ClassicHttpResponse response1 = new BasicClassicHttpResponse(407, "Huh?"); response1.setHeader(HttpHeaders.PROXY_AUTHENTICATE, "Basic realm=test"); final InputStream instream1 = Mockito.spy(new ByteArrayInputStream(new byte[] {1, 2, 3})); response1.setEntity(EntityBuilder.create() .setStream(instream1) .build()); - final HttpResponse response2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final ClassicHttpResponse response2 = new BasicClassicHttpResponse(200, "OK"); final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials("user", "pass".toCharArray())); @@ -804,7 +802,7 @@ public class TestMainClientExec { Mockito.any(), Mockito.any())).thenReturn(Boolean.FALSE); Mockito.when(requestExecutor.execute( - Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(response1, response2); @@ -828,11 +826,11 @@ public class TestMainClientExec { final HttpRoute route = new HttpRoute(target, null, new HttpHost[] {proxy1, proxy2}, true, RouteInfo.TunnelType.TUNNELLED, RouteInfo.LayerType.LAYERED); final HttpClientContext context = new HttpClientContext(); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE); mainClientExec.establishRoute(managedConn, route, request, context); } -} \ No newline at end of file +} diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestMinimalClientExec.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestMinimalClientExec.java index 1b653c9c0..81b6b5c55 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestMinimalClientExec.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestMinimalClientExec.java @@ -39,21 +39,19 @@ import org.apache.hc.client5.http.entity.EntityBuilder; import org.apache.hc.client5.http.impl.io.ConnectionShutdownException; import org.apache.hc.client5.http.io.ConnectionRequest; import org.apache.hc.client5.http.io.HttpClientConnectionManager; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpExecutionAware; import org.apache.hc.client5.http.methods.HttpGet; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.core5.concurrent.Cancellable; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.ConnectionReuseStrategy; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpHost; -import org.apache.hc.core5.http.HttpRequest; -import org.apache.hc.core5.http.HttpResponse; -import org.apache.hc.core5.http.HttpVersion; import org.apache.hc.core5.http.impl.io.HttpRequestExecutor; import org.apache.hc.core5.http.io.HttpClientConnection; -import org.apache.hc.core5.http.message.BasicHttpResponse; +import org.apache.hc.core5.http.message.BasicClassicHttpResponse; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -106,15 +104,14 @@ public class TestMinimalClientExec { .setConnectionRequestTimeout(345) .build(); context.setRequestConfig(config); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); + final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK"); Mockito.when(requestExecutor.execute( Mockito.same(request), Mockito.any(), Mockito.any())).thenReturn(response); - final CloseableHttpResponse finalResponse = minimalClientExec.execute( - route, request, context, execAware); + final ClassicHttpResponse finalResponse = minimalClientExec.execute(request, context, execAware); Mockito.verify(connManager).requestConnection(route, null); Mockito.verify(connRequest).get(345, TimeUnit.MILLISECONDS); Mockito.verify(execAware, Mockito.times(1)).setCancellable(connRequest); @@ -128,7 +125,7 @@ public class TestMinimalClientExec { Assert.assertSame(managedConn, context.getConnection()); Assert.assertNotNull(finalResponse); - Assert.assertTrue(finalResponse instanceof HttpResponseProxy); + Assert.assertTrue(finalResponse instanceof CloseableHttpResponse); } @Test @@ -141,8 +138,8 @@ public class TestMinimalClientExec { .setConnectionRequestTimeout(345) .build(); context.setRequestConfig(config); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); + final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK"); Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE); Mockito.when(managedConn.isStale()).thenReturn(Boolean.FALSE); @@ -158,8 +155,7 @@ public class TestMinimalClientExec { Mockito.same(response), Mockito.any())).thenReturn(678L); - final CloseableHttpResponse finalResponse = minimalClientExec.execute( - route, request, context, execAware); + final ClassicHttpResponse finalResponse = minimalClientExec.execute(request, context, execAware); Mockito.verify(connManager).requestConnection(route, null); Mockito.verify(connRequest).get(345, TimeUnit.MILLISECONDS); Mockito.verify(requestExecutor, Mockito.times(1)).execute(request, managedConn, context); @@ -167,7 +163,7 @@ public class TestMinimalClientExec { Mockito.verify(managedConn, Mockito.never()).close(); Assert.assertNotNull(finalResponse); - Assert.assertTrue(finalResponse instanceof HttpResponseProxy); + Assert.assertTrue(finalResponse instanceof CloseableHttpResponse); } @Test @@ -180,8 +176,8 @@ public class TestMinimalClientExec { .setConnectionRequestTimeout(345) .build(); context.setRequestConfig(config); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); + final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK"); // The entity is streaming response.setEntity(EntityBuilder.create() .setStream(new ByteArrayInputStream(new byte[]{})) @@ -198,8 +194,7 @@ public class TestMinimalClientExec { Mockito.same(response), Mockito.any())).thenReturn(Boolean.FALSE); - final CloseableHttpResponse finalResponse = minimalClientExec.execute( - route, request, context, execAware); + final ClassicHttpResponse finalResponse = minimalClientExec.execute(request, context, execAware); Mockito.verify(connManager).requestConnection(route, null); Mockito.verify(connRequest).get(345, TimeUnit.MILLISECONDS); Mockito.verify(requestExecutor, Mockito.times(1)).execute(request, managedConn, context); @@ -211,7 +206,7 @@ public class TestMinimalClientExec { Mockito.verify(managedConn, Mockito.never()).close(); Assert.assertNotNull(finalResponse); - Assert.assertTrue(finalResponse instanceof HttpResponseProxy); + Assert.assertTrue(finalResponse instanceof CloseableHttpResponse); finalResponse.close(); Mockito.verify(connManager, Mockito.times(1)).releaseConnection( @@ -224,16 +219,16 @@ public class TestMinimalClientExec { final HttpRoute route = new HttpRoute(target); final HttpClientContext context = new HttpClientContext(); final RequestConfig config = RequestConfig.custom().setSocketTimeout(3000).build(); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); context.setRequestConfig(config); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK"); Mockito.when(managedConn.isOpen()).thenReturn(true); Mockito.when(requestExecutor.execute( Mockito.same(request), Mockito.any(), Mockito.any())).thenReturn(response); - minimalClientExec.execute(route, request, context, execAware); + minimalClientExec.execute(request, context, execAware); Mockito.verify(managedConn).setSocketTimeout(3000); } @@ -241,15 +236,15 @@ public class TestMinimalClientExec { public void testSocketTimeoutReset() throws Exception { final HttpRoute route = new HttpRoute(target); final HttpClientContext context = new HttpClientContext(); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); + final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK"); Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE); Mockito.when(requestExecutor.execute( Mockito.same(request), Mockito.any(), Mockito.any())).thenReturn(response); - minimalClientExec.execute(route, request, context, execAware); + minimalClientExec.execute(request, context, execAware); Mockito.verify(managedConn, Mockito.never()).setSocketTimeout(Mockito.anyInt()); } @@ -257,12 +252,12 @@ public class TestMinimalClientExec { public void testExecAbortedPriorToConnectionLease() throws Exception { final HttpRoute route = new HttpRoute(target); final HttpClientContext context = new HttpClientContext(); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); Mockito.when(managedConn.isOpen()).thenReturn(Boolean.FALSE); Mockito.when(execAware.isAborted()).thenReturn(Boolean.TRUE); try { - minimalClientExec.execute(route, request, context, execAware); + minimalClientExec.execute(request, context, execAware); } catch (final IOException ex) { Mockito.verify(connRequest, Mockito.times(1)).cancel(); throw ex; @@ -273,40 +268,40 @@ public class TestMinimalClientExec { public void testExecConnectionRequestFailed() throws Exception { final HttpRoute route = new HttpRoute(target); final HttpClientContext context = new HttpClientContext(); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); Mockito.when(connRequest.get(Mockito.anyInt(), Mockito.any())) .thenThrow(new ExecutionException("Opppsie", null)); - minimalClientExec.execute(route, request, context, execAware); + minimalClientExec.execute(request, context, execAware); } @Test(expected=InterruptedIOException.class) public void testExecConnectionShutDown() throws Exception { final HttpRoute route = new HttpRoute(target); final HttpClientContext context = new HttpClientContext(); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); Mockito.when(requestExecutor.execute( - Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any())).thenThrow(new ConnectionShutdownException()); - minimalClientExec.execute(route, request, context, execAware); + minimalClientExec.execute(request, context, execAware); } @Test(expected=RuntimeException.class) public void testExecRuntimeException() throws Exception { final HttpRoute route = new HttpRoute(target); final HttpClientContext context = new HttpClientContext(); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); Mockito.when(requestExecutor.execute( - Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any())).thenThrow(new RuntimeException("Ka-boom")); try { - minimalClientExec.execute(route, request, context, execAware); + minimalClientExec.execute(request, context, execAware); } catch (final Exception ex) { Mockito.verify(connManager).releaseConnection(managedConn, null, 0, TimeUnit.MILLISECONDS); @@ -318,15 +313,15 @@ public class TestMinimalClientExec { public void testExecHttpException() throws Exception { final HttpRoute route = new HttpRoute(target); final HttpClientContext context = new HttpClientContext(); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); Mockito.when(requestExecutor.execute( - Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any())).thenThrow(new HttpException("Ka-boom")); try { - minimalClientExec.execute(route, request, context, execAware); + minimalClientExec.execute(request, context, execAware); } catch (final Exception ex) { Mockito.verify(connManager).releaseConnection(managedConn, null, 0, TimeUnit.MILLISECONDS); @@ -338,15 +333,15 @@ public class TestMinimalClientExec { public void testExecIOException() throws Exception { final HttpRoute route = new HttpRoute(target); final HttpClientContext context = new HttpClientContext(); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); Mockito.when(requestExecutor.execute( - Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any())).thenThrow(new IOException("Ka-boom")); try { - minimalClientExec.execute(route, request, context, execAware); + minimalClientExec.execute(request, context, execAware); } catch (final Exception ex) { Mockito.verify(connManager).releaseConnection(managedConn, null, 0, TimeUnit.MILLISECONDS); @@ -358,19 +353,19 @@ public class TestMinimalClientExec { public void absoluteUriIsRewrittenToRelativeBeforeBeingPassedInRequestLine() throws Exception { final HttpRoute route = new HttpRoute(target); final HttpClientContext context = new HttpClientContext(); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"), target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("http://bar/test"), route); - final HttpResponse response = Mockito.mock(HttpResponse.class); + final ClassicHttpResponse response = Mockito.mock(ClassicHttpResponse.class); Mockito.when(requestExecutor.execute( - Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(response); - minimalClientExec.execute(route, request, context, execAware); + minimalClientExec.execute(request, context, execAware); - final ArgumentCaptor reqCaptor = ArgumentCaptor.forClass(HttpRequest.class); + final ArgumentCaptor reqCaptor = ArgumentCaptor.forClass(ClassicHttpRequest.class); Mockito.verify(requestExecutor).execute(reqCaptor.capture(), Mockito.any(), Mockito.any()); - Assert.assertEquals("/test", reqCaptor.getValue().getRequestLine().getUri()); + Assert.assertEquals("/test", reqCaptor.getValue().getRequestUri()); } } diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestNullBackoffStrategy.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestNullBackoffStrategy.java index 27cd9f6c1..578442064 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestNullBackoffStrategy.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestNullBackoffStrategy.java @@ -30,7 +30,6 @@ import static org.junit.Assert.assertFalse; import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.HttpStatus; -import org.apache.hc.core5.http.HttpVersion; import org.apache.hc.core5.http.message.BasicHttpResponse; import org.junit.Before; import org.junit.Test; @@ -52,8 +51,7 @@ public class TestNullBackoffStrategy { @Test public void doesNotBackoffForResponses() { - final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_SERVICE_UNAVAILABLE, "Service Unavailable"); + final HttpResponse resp = new BasicHttpResponse(HttpStatus.SC_SERVICE_UNAVAILABLE, "Service Unavailable"); assertFalse(impl.shouldBackoff(resp)); } } diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestProtocolExec.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestProtocolExec.java index f6924e552..b1f494184 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestProtocolExec.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestProtocolExec.java @@ -33,14 +33,14 @@ import org.apache.hc.client5.http.HttpRoute; import org.apache.hc.client5.http.auth.AuthScope; import org.apache.hc.client5.http.auth.Credentials; import org.apache.hc.client5.http.auth.CredentialsProvider; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpExecutionAware; import org.apache.hc.client5.http.methods.HttpGet; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.HttpClientContext; +import org.apache.hc.core5.http.ClassicHttpResponse; +import org.apache.hc.core5.http.EntityDetails; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpHost; -import org.apache.hc.core5.http.message.BasicHttpRequest; import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.http.protocol.HttpProcessor; import org.junit.Assert; @@ -62,133 +62,54 @@ public class TestProtocolExec { private ProtocolExec protocolExec; private HttpHost target; - private HttpHost proxy; @Before public void setup() throws Exception { MockitoAnnotations.initMocks(this); protocolExec = new ProtocolExec(requestExecutor, httpProcessor); target = new HttpHost("foo", 80); - proxy = new HttpHost("bar", 8888); } @Test public void testFundamentals() throws Exception { final HttpRoute route = new HttpRoute(target); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("/test"), target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("/test"), route); final HttpClientContext context = HttpClientContext.create(); - final CloseableHttpResponse response = Mockito.mock(CloseableHttpResponse.class); + final ClassicHttpResponse response = Mockito.mock(ClassicHttpResponse.class); Mockito.when(requestExecutor.execute( - Mockito.eq(route), - Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(response); - protocolExec.execute(route, request, context, execAware); + protocolExec.execute(request, context, execAware); - Mockito.verify(httpProcessor).process(request, context); - Mockito.verify(requestExecutor).execute(route, request, context, execAware); - Mockito.verify(httpProcessor).process(response, context); + Mockito.verify(httpProcessor).process(request, null, context); + Mockito.verify(requestExecutor).execute(request, context, execAware); + Mockito.verify(httpProcessor).process(response, null, context); - Assert.assertEquals(new HttpHost("foo", 80), context.getTargetHost()); - Assert.assertEquals(target, context.getTargetHost()); Assert.assertEquals(route, context.getHttpRoute()); Assert.assertSame(request, context.getRequest()); Assert.assertSame(response, context.getResponse()); } - @Test - public void testRewriteAbsoluteRequestURI() throws Exception { - final HttpRoute route = new HttpRoute(target); - final HttpRequestWrapper request = HttpRequestWrapper.wrap( - new HttpGet("http://foo/test"), target); - protocolExec.rewriteRequestURI(request, route); - Assert.assertEquals(new URI("/test"), request.getURI()); - } - - @Test - public void testRewriteEmptyRequestURI() throws Exception { - final HttpRoute route = new HttpRoute(target); - final HttpRequestWrapper request = HttpRequestWrapper.wrap( - new HttpGet(""), target); - protocolExec.rewriteRequestURI(request, route); - Assert.assertEquals(new URI("/"), request.getURI()); - } - - @Test - public void testRewriteAbsoluteRequestURIViaPRoxy() throws Exception { - final HttpRoute route = new HttpRoute(target, proxy); - final HttpRequestWrapper request = HttpRequestWrapper.wrap( - new HttpGet("http://foo/test"), target); - protocolExec.rewriteRequestURI(request, route); - Assert.assertEquals(new URI("http://foo/test"), request.getURI()); - } - - @Test - public void testRewriteRelativeRequestURIViaPRoxy() throws Exception { - final HttpRoute route = new HttpRoute(target, proxy); - final HttpRequestWrapper request = HttpRequestWrapper.wrap( - new HttpGet("/test"), target); - protocolExec.rewriteRequestURI(request, route); - Assert.assertEquals(new URI("http://foo:80/test"), request.getURI()); - } - - @Test - public void testHostHeaderUriRequest() throws Exception { - final HttpRoute route = new HttpRoute(target); - final HttpRequestWrapper request = HttpRequestWrapper.wrap( - new HttpGet("http://bar/test"), target); - final HttpClientContext context = HttpClientContext.create(); - protocolExec.execute(route, request, context, execAware); - // ProtocolExect should have extracted the host from request URI - Assert.assertEquals(new HttpHost("bar", -1, "http"), context.getTargetHost()); - } - - @Test - public void testHostHeaderWhenNonUriRequest() throws Exception { - final HttpRoute route = new HttpRoute(target); - final HttpRequestWrapper request = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "http://bar/test"), target); - final HttpClientContext context = HttpClientContext.create(); - protocolExec.execute(route, request, context, execAware); - // ProtocolExect should have extracted the host from request URI - Assert.assertEquals(new HttpHost("bar", -1, "http"), context.getTargetHost()); - } - - @Test - public void testHostHeaderWhenNonUriRequestAndInvalidUri() throws Exception { - final HttpRoute route = new HttpRoute(target); - final HttpRequestWrapper request = HttpRequestWrapper.wrap( - new BasicHttpRequest("GET", "http://bar/test|"), target); - final HttpClientContext context = HttpClientContext.create(); - protocolExec.execute(route, request, context, execAware); - // ProtocolExect should have fall back to physical host as request URI - // is not parseable - Assert.assertEquals(new HttpHost("foo", 80, "http"), context.getTargetHost()); - } - - @Test - public void testHostHeaderImplicitHost() throws Exception { - final HttpHost somehost = new HttpHost("somehost", 8080); - final HttpRoute route = new HttpRoute(somehost); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("/test"), somehost); - final HttpClientContext context = HttpClientContext.create(); - protocolExec.execute(route, request, context, execAware); - Assert.assertEquals(somehost, context.getTargetHost()); - } - @Test public void testUserInfoInRequestURI() throws Exception { final HttpRoute route = new HttpRoute(new HttpHost("somehost", 8080)); - final HttpRequestWrapper request = HttpRequestWrapper.wrap( - new HttpGet("http://somefella:secret@bar/test"), target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt( + new HttpGet("http://somefella:secret@bar/test"), route); final HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(new BasicCredentialsProvider()); - protocolExec.execute(route, request, context, execAware); - Assert.assertEquals(new URI("/test"), request.getURI()); - Assert.assertEquals(new HttpHost("bar", -1), context.getTargetHost()); + + final ClassicHttpResponse response = Mockito.mock(ClassicHttpResponse.class); + Mockito.when(requestExecutor.execute( + Mockito.any(), + Mockito.any(), + Mockito.any())).thenReturn(response); + + protocolExec.execute(request, context, execAware); + Assert.assertEquals(new URI("http://bar/test"), request.getUri()); final CredentialsProvider credentialsProvider = context.getCredentialsProvider(); final Credentials creds = credentialsProvider.getCredentials(new AuthScope("bar", -1, null), null); Assert.assertNotNull(creds); @@ -198,20 +119,19 @@ public class TestProtocolExec { @Test(expected = HttpException.class) public void testPostProcessHttpException() throws Exception { final HttpRoute route = new HttpRoute(target); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("/test"), target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("/test"), route); final HttpClientContext context = HttpClientContext.create(); - final CloseableHttpResponse response = Mockito.mock(CloseableHttpResponse.class); + final ClassicHttpResponse response = Mockito.mock(ClassicHttpResponse.class); Mockito.when(requestExecutor.execute( - Mockito.eq(route), - Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(response); Mockito.doThrow(new HttpException("Ooopsie")).when(httpProcessor).process( - Mockito.same(response), Mockito.any()); + Mockito.same(response), Mockito.isNull(EntityDetails.class), Mockito.any()); try { - protocolExec.execute(route, request, context, execAware); + protocolExec.execute(request, context, execAware); } catch (final Exception ex) { Mockito.verify(response).close(); throw ex; @@ -221,19 +141,18 @@ public class TestProtocolExec { @Test(expected = IOException.class) public void testPostProcessIOException() throws Exception { final HttpRoute route = new HttpRoute(target); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("/test"), target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("/test"), route); final HttpClientContext context = HttpClientContext.create(); - final CloseableHttpResponse response = Mockito.mock(CloseableHttpResponse.class); + final ClassicHttpResponse response = Mockito.mock(ClassicHttpResponse.class); Mockito.when(requestExecutor.execute( - Mockito.eq(route), - Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(response); Mockito.doThrow(new IOException("Ooopsie")).when(httpProcessor).process( - Mockito.same(response), Mockito.any()); + Mockito.same(response), Mockito.isNull(EntityDetails.class), Mockito.any()); try { - protocolExec.execute(route, request, context, execAware); + protocolExec.execute(request, context, execAware); } catch (final Exception ex) { Mockito.verify(response).close(); throw ex; @@ -243,19 +162,18 @@ public class TestProtocolExec { @Test(expected = RuntimeException.class) public void testPostProcessRuntimeException() throws Exception { final HttpRoute route = new HttpRoute(target); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("/test"), target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("/test"), route); final HttpClientContext context = HttpClientContext.create(); - final CloseableHttpResponse response = Mockito.mock(CloseableHttpResponse.class); + final ClassicHttpResponse response = Mockito.mock(ClassicHttpResponse.class); Mockito.when(requestExecutor.execute( - Mockito.eq(route), - Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(response); Mockito.doThrow(new RuntimeException("Ooopsie")).when(httpProcessor).process( - Mockito.same(response), Mockito.any()); + Mockito.same(response), Mockito.isNull(EntityDetails.class), Mockito.any()); try { - protocolExec.execute(route, request, context, execAware); + protocolExec.execute(request, context, execAware); } catch (final Exception ex) { Mockito.verify(response).close(); throw ex; diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestRedirectExec.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestRedirectExec.java index 2c7c28876..4ee65b567 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestRedirectExec.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestRedirectExec.java @@ -36,15 +36,14 @@ import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.entity.EntityBuilder; import org.apache.hc.client5.http.impl.auth.BasicScheme; import org.apache.hc.client5.http.impl.auth.NTLMScheme; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpExecutionAware; import org.apache.hc.client5.http.methods.HttpGet; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.protocol.RedirectException; import org.apache.hc.client5.http.protocol.RedirectStrategy; import org.apache.hc.client5.http.routing.HttpRoutePlanner; -import org.apache.hc.core5.http.Header; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpHost; @@ -87,18 +86,16 @@ public class TestRedirectExec { public void testFundamentals() throws Exception { final HttpRoute route = new HttpRoute(target); final HttpGet get = new HttpGet("/test"); - get.addHeader("header", "this"); - get.addHeader("header", "that"); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(get, target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(get, route); final HttpClientContext context = HttpClientContext.create(); - final CloseableHttpResponse response1 = Mockito.mock(CloseableHttpResponse.class); + final ClassicHttpResponse response1 = Mockito.mock(ClassicHttpResponse.class); final InputStream instream1 = Mockito.spy(new ByteArrayInputStream(new byte[] {1, 2, 3})); final HttpEntity entity1 = EntityBuilder.create() .setStream(instream1) .build(); Mockito.when(response1.getEntity()).thenReturn(entity1); - final CloseableHttpResponse response2 = Mockito.mock(CloseableHttpResponse.class); + final ClassicHttpResponse response2 = Mockito.mock(ClassicHttpResponse.class); final InputStream instream2 = Mockito.spy(new ByteArrayInputStream(new byte[] {1, 2, 3})); final HttpEntity entity2 = EntityBuilder.create() .setStream(instream2) @@ -107,12 +104,10 @@ public class TestRedirectExec { final HttpGet redirect = new HttpGet("http://localhost:80/redirect"); Mockito.when(requestExecutor.execute( - Mockito.eq(route), Mockito.same(request), Mockito.any(), Mockito.any())).thenReturn(response1); Mockito.when(requestExecutor.execute( - Mockito.eq(route), HttpRequestWrapperMatcher.same(redirect), Mockito.any(), Mockito.any())).thenReturn(response2); @@ -126,29 +121,22 @@ public class TestRedirectExec { Mockito.any())).thenReturn(redirect); Mockito.when(httpRoutePlanner.determineRoute( Mockito.eq(target), - Mockito.any(), + Mockito.any(), Mockito.any())).thenReturn(route); - redirectExec.execute(route, request, context, execAware); + redirectExec.execute(request, context, execAware); - final ArgumentCaptor reqCaptor = ArgumentCaptor.forClass( - HttpRequestWrapper.class); + final ArgumentCaptor reqCaptor = ArgumentCaptor.forClass( + RoutedHttpRequest.class); Mockito.verify(requestExecutor, Mockito.times(2)).execute( - Mockito.eq(route), reqCaptor.capture(), Mockito.same(context), Mockito.same(execAware)); - final List allValues = reqCaptor.getAllValues(); + final List allValues = reqCaptor.getAllValues(); Assert.assertNotNull(allValues); Assert.assertEquals(2, allValues.size()); Assert.assertSame(request, allValues.get(0)); - final HttpRequestWrapper redirectWrapper = allValues.get(1); - final Header[] headers = redirectWrapper.getHeaders("header"); - Assert.assertNotNull(headers); - Assert.assertEquals(2, headers.length); - Assert.assertEquals("this", headers[0].getValue()); - Assert.assertEquals("that", headers[1].getValue()); Mockito.verify(response1, Mockito.times(1)).close(); Mockito.verify(instream1, Mockito.times(1)).close(); @@ -160,7 +148,7 @@ public class TestRedirectExec { public void testMaxRedirect() throws Exception { final HttpRoute route = new HttpRoute(target); final HttpGet get = new HttpGet("/test"); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(get, target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(get, route); final HttpClientContext context = HttpClientContext.create(); final RequestConfig config = RequestConfig.custom() .setRedirectsEnabled(true) @@ -168,47 +156,44 @@ public class TestRedirectExec { .build(); context.setRequestConfig(config); - final CloseableHttpResponse response1 = Mockito.mock(CloseableHttpResponse.class); + final ClassicHttpResponse response1 = Mockito.mock(ClassicHttpResponse.class); final HttpGet redirect = new HttpGet("http://localhost:80/redirect"); Mockito.when(requestExecutor.execute( - Mockito.eq(route), - Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(response1); Mockito.when(redirectStrategy.isRedirected( - Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(Boolean.TRUE); Mockito.when(redirectStrategy.getRedirect( - Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(redirect); Mockito.when(httpRoutePlanner.determineRoute( Mockito.eq(target), - Mockito.any(), + Mockito.any(), Mockito.any())).thenReturn(route); - redirectExec.execute(route, request, context, execAware); + redirectExec.execute(request, context, execAware); } @Test(expected = HttpException.class) public void testRelativeRedirect() throws Exception { final HttpRoute route = new HttpRoute(target); final HttpGet get = new HttpGet("/test"); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(get, target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(get, route); final HttpClientContext context = HttpClientContext.create(); - final CloseableHttpResponse response1 = Mockito.mock(CloseableHttpResponse.class); - final CloseableHttpResponse response2 = Mockito.mock(CloseableHttpResponse.class); + final ClassicHttpResponse response1 = Mockito.mock(ClassicHttpResponse.class); + final ClassicHttpResponse response2 = Mockito.mock(ClassicHttpResponse.class); final HttpGet redirect = new HttpGet("/redirect"); Mockito.when(requestExecutor.execute( - Mockito.eq(route), Mockito.same(request), Mockito.any(), Mockito.any())).thenReturn(response1); Mockito.when(requestExecutor.execute( - Mockito.eq(route), HttpRequestWrapperMatcher.same(redirect), Mockito.any(), Mockito.any())).thenReturn(response2); @@ -222,10 +207,10 @@ public class TestRedirectExec { Mockito.any())).thenReturn(redirect); Mockito.when(httpRoutePlanner.determineRoute( Mockito.eq(target), - Mockito.any(), + Mockito.any(), Mockito.any())).thenReturn(route); - redirectExec.execute(route, request, context, execAware); + redirectExec.execute(request, context, execAware); } @Test @@ -234,7 +219,7 @@ public class TestRedirectExec { final HttpHost proxy = new HttpHost("proxy"); final HttpRoute route = new HttpRoute(target, proxy); final HttpGet get = new HttpGet("/test"); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(get, target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(get, route); final HttpClientContext context = HttpClientContext.create(); final AuthExchange targetAuthExchange = new AuthExchange(); @@ -246,16 +231,15 @@ public class TestRedirectExec { context.setAuthExchange(target, targetAuthExchange); context.setAuthExchange(proxy, proxyAuthExchange); - final CloseableHttpResponse response1 = Mockito.mock(CloseableHttpResponse.class); - final CloseableHttpResponse response2 = Mockito.mock(CloseableHttpResponse.class); - final HttpGet redirect = new HttpGet("http://otherhost/redirect"); + final ClassicHttpResponse response1 = Mockito.mock(ClassicHttpResponse.class); + final ClassicHttpResponse response2 = Mockito.mock(ClassicHttpResponse.class); + final HttpHost otherHost = new HttpHost("otherhost", 8888); + final HttpGet redirect = new HttpGet("http://otherhost:8888/redirect"); Mockito.when(requestExecutor.execute( - Mockito.eq(route), Mockito.same(request), Mockito.any(), Mockito.any())).thenReturn(response1); Mockito.when(requestExecutor.execute( - Mockito.eq(route), HttpRequestWrapperMatcher.same(redirect), Mockito.any(), Mockito.any())).thenReturn(response2); @@ -269,10 +253,14 @@ public class TestRedirectExec { Mockito.any())).thenReturn(redirect); Mockito.when(httpRoutePlanner.determineRoute( Mockito.eq(target), - Mockito.any(), - Mockito.any())).thenReturn(new HttpRoute(new HttpHost("otherhost", 80))); + Mockito.any(), + Mockito.any())).thenReturn(new HttpRoute(target)); + Mockito.when(httpRoutePlanner.determineRoute( + Mockito.eq(otherHost), + Mockito.any(), + Mockito.any())).thenReturn(new HttpRoute(otherHost)); - redirectExec.execute(route, request, context, execAware); + redirectExec.execute(request, context, execAware); final AuthExchange authExchange1 = context.getAuthExchange(target); Assert.assertNotNull(authExchange1); @@ -288,12 +276,11 @@ public class TestRedirectExec { public void testRedirectRuntimeException() throws Exception { final HttpRoute route = new HttpRoute(target); final HttpGet get = new HttpGet("/test"); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(get, target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(get, route); final HttpClientContext context = HttpClientContext.create(); - final CloseableHttpResponse response1 = Mockito.mock(CloseableHttpResponse.class); + final ClassicHttpResponse response1 = Mockito.mock(ClassicHttpResponse.class); Mockito.when(requestExecutor.execute( - Mockito.eq(route), Mockito.same(request), Mockito.any(), Mockito.any())).thenReturn(response1); @@ -307,7 +294,7 @@ public class TestRedirectExec { Mockito.any())); try { - redirectExec.execute(route, request, context, execAware); + redirectExec.execute(request, context, execAware); } catch (final Exception ex) { Mockito.verify(response1).close(); throw ex; @@ -318,17 +305,16 @@ public class TestRedirectExec { public void testRedirectProtocolException() throws Exception { final HttpRoute route = new HttpRoute(target); final HttpGet get = new HttpGet("/test"); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(get, target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(get, route); final HttpClientContext context = HttpClientContext.create(); - final CloseableHttpResponse response1 = Mockito.mock(CloseableHttpResponse.class); + final ClassicHttpResponse response1 = Mockito.mock(ClassicHttpResponse.class); final InputStream instream1 = Mockito.spy(new ByteArrayInputStream(new byte[] {1, 2, 3})); final HttpEntity entity1 = EntityBuilder.create() .setStream(instream1) .build(); Mockito.when(response1.getEntity()).thenReturn(entity1); Mockito.when(requestExecutor.execute( - Mockito.eq(route), Mockito.same(request), Mockito.any(), Mockito.any())).thenReturn(response1); @@ -342,7 +328,7 @@ public class TestRedirectExec { Mockito.any()); try { - redirectExec.execute(route, request, context, execAware); + redirectExec.execute(request, context, execAware); } catch (final Exception ex) { Mockito.verify(instream1).close(); Mockito.verify(response1).close(); @@ -350,7 +336,7 @@ public class TestRedirectExec { } } - static class HttpRequestWrapperMatcher extends ArgumentMatcher { + static class HttpRequestWrapperMatcher extends ArgumentMatcher { private final HttpRequest original; @@ -360,11 +346,11 @@ public class TestRedirectExec { } @Override public boolean matches(final Object obj) { - final HttpRequestWrapper wrapper = (HttpRequestWrapper) obj; + final RoutedHttpRequest wrapper = (RoutedHttpRequest) obj; return original == wrapper.getOriginal(); } - static HttpRequestWrapper same(final HttpRequest original) { + static RoutedHttpRequest same(final HttpRequest original) { return Matchers.argThat(new HttpRequestWrapperMatcher(original)); } diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestResponseEntityWrapper.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestResponseEntityWrapper.java index 99c06041d..83a738b66 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestResponseEntityWrapper.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestResponseEntityWrapper.java @@ -32,7 +32,7 @@ import java.io.OutputStream; import java.net.SocketException; import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.EntityUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Test; diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestRetryExec.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestRetryExec.java index 8bd71e2b6..fd807600b 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestRetryExec.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestRetryExec.java @@ -35,10 +35,11 @@ import org.apache.hc.client5.http.entity.EntityBuilder; import org.apache.hc.client5.http.methods.HttpExecutionAware; import org.apache.hc.client5.http.methods.HttpGet; import org.apache.hc.client5.http.methods.HttpPost; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.protocol.NonRepeatableRequestException; import org.apache.hc.client5.http.sync.HttpRequestRetryHandler; +import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpRequest; @@ -78,11 +79,10 @@ public class TestRetryExec { final HttpGet get = new HttpGet("/test"); get.addHeader("header", "this"); get.addHeader("header", "that"); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(get, target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(get, route); final HttpClientContext context = HttpClientContext.create(); Mockito.when(requestExecutor.execute( - Mockito.eq(route), Mockito.same(request), Mockito.any(), Mockito.any())).thenAnswer(new Answer() { @@ -90,7 +90,7 @@ public class TestRetryExec { @Override public Object answer(final InvocationOnMock invocationOnMock) throws Throwable { final Object[] args = invocationOnMock.getArguments(); - final HttpRequestWrapper wrapper = (HttpRequestWrapper) args[1]; + final RoutedHttpRequest wrapper = (RoutedHttpRequest) args[0]; final Header[] headers = wrapper.getAllHeaders(); Assert.assertEquals(2, headers.length); Assert.assertEquals("this", headers[0].getValue()); @@ -106,10 +106,9 @@ public class TestRetryExec { Mockito.eq(1), Mockito.any())).thenReturn(Boolean.TRUE); try { - retryExec.execute(route, request, context, execAware); + retryExec.execute(request, context, execAware); } catch (final IOException ex) { Mockito.verify(requestExecutor, Mockito.times(2)).execute( - Mockito.eq(route), Mockito.same(request), Mockito.same(context), Mockito.same(execAware)); @@ -121,21 +120,19 @@ public class TestRetryExec { public void testAbortedRequest() throws Exception { final HttpRoute route = new HttpRoute(target); final HttpGet get = new HttpGet("/test"); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(get, target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(get, route); final HttpClientContext context = HttpClientContext.create(); Mockito.when(requestExecutor.execute( - Mockito.eq(route), Mockito.same(request), Mockito.any(), Mockito.any())).thenThrow(new IOException("Ka-boom")); Mockito.when(execAware.isAborted()).thenReturn(Boolean.TRUE); try { - retryExec.execute(route, request, context, execAware); + retryExec.execute(request, context, execAware); } catch (final IOException ex) { Mockito.verify(requestExecutor, Mockito.times(1)).execute( - Mockito.eq(route), Mockito.same(request), Mockito.same(context), Mockito.same(execAware)); @@ -156,11 +153,10 @@ public class TestRetryExec { post.setEntity(EntityBuilder.create() .setStream(new ByteArrayInputStream(new byte[]{})) .build()); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(post, target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(post, route); final HttpClientContext context = HttpClientContext.create(); Mockito.when(requestExecutor.execute( - Mockito.eq(route), Mockito.same(request), Mockito.any(), Mockito.any())).thenAnswer(new Answer() { @@ -168,7 +164,7 @@ public class TestRetryExec { @Override public Object answer(final InvocationOnMock invocationOnMock) throws Throwable { final Object[] args = invocationOnMock.getArguments(); - final HttpRequest req = (HttpRequest) args[1]; + final ClassicHttpRequest req = (ClassicHttpRequest) args[0]; req.getEntity().writeTo(new ByteArrayOutputStream()); throw new IOException("Ka-boom"); } @@ -180,10 +176,9 @@ public class TestRetryExec { Mockito.eq(1), Mockito.any())).thenReturn(Boolean.TRUE); try { - retryExec.execute(route, request, context, execAware); + retryExec.execute(request, context, execAware); } catch (final IOException ex) { Mockito.verify(requestExecutor, Mockito.times(1)).execute( - Mockito.eq(route), Mockito.same(request), Mockito.same(context), Mockito.same(execAware)); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestServiceUnavailableRetryExec.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestServiceUnavailableRetryExec.java index 5430eb564..c28a86589 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestServiceUnavailableRetryExec.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/sync/TestServiceUnavailableRetryExec.java @@ -27,12 +27,12 @@ package org.apache.hc.client5.http.impl.sync; import org.apache.hc.client5.http.HttpRoute; -import org.apache.hc.client5.http.methods.CloseableHttpResponse; import org.apache.hc.client5.http.methods.HttpExecutionAware; import org.apache.hc.client5.http.methods.HttpGet; -import org.apache.hc.client5.http.methods.HttpRequestWrapper; +import org.apache.hc.client5.http.methods.RoutedHttpRequest; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.sync.ServiceUnavailableRetryStrategy; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.protocol.HttpContext; @@ -66,13 +66,12 @@ public class TestServiceUnavailableRetryExec { public void testFundamentals() throws Exception { final HttpRoute route = new HttpRoute(target); final HttpGet get = new HttpGet("/test"); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(get, target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(get, route); final HttpClientContext context = HttpClientContext.create(); - final CloseableHttpResponse response = Mockito.mock(CloseableHttpResponse.class); + final ClassicHttpResponse response = Mockito.mock(ClassicHttpResponse.class); Mockito.when(requestExecutor.execute( - Mockito.eq(route), Mockito.same(request), Mockito.any(), Mockito.any())).thenReturn(response); @@ -84,10 +83,9 @@ public class TestServiceUnavailableRetryExec { Mockito.any(), Mockito.any())).thenReturn(0L); - retryExec.execute(route, request, context, execAware); + retryExec.execute(request, context, execAware); Mockito.verify(requestExecutor, Mockito.times(2)).execute( - Mockito.eq(route), Mockito.same(request), Mockito.same(context), Mockito.same(execAware)); @@ -97,13 +95,12 @@ public class TestServiceUnavailableRetryExec { @Test(expected = RuntimeException.class) public void testStrategyRuntimeException() throws Exception { final HttpRoute route = new HttpRoute(target); - final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("/test"), target); + final RoutedHttpRequest request = RoutedHttpRequest.adapt(new HttpGet("/test"), route); final HttpClientContext context = HttpClientContext.create(); - final CloseableHttpResponse response = Mockito.mock(CloseableHttpResponse.class); + final ClassicHttpResponse response = Mockito.mock(ClassicHttpResponse.class); Mockito.when(requestExecutor.execute( - Mockito.eq(route), - Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(response); Mockito.doThrow(new RuntimeException("Ooopsie")).when(retryStrategy).retryRequest( @@ -111,7 +108,7 @@ public class TestServiceUnavailableRetryExec { Mockito.anyInt(), Mockito.any()); try { - retryExec.execute(route, request, context, execAware); + retryExec.execute(request, context, execAware); } catch (final Exception ex) { Mockito.verify(response).close(); throw ex; diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/io/TestEofSensorInputStream.java b/httpclient5/src/test/java/org/apache/hc/client5/http/io/TestEofSensorInputStream.java deleted file mode 100644 index 19786eac8..000000000 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/io/TestEofSensorInputStream.java +++ /dev/null @@ -1,228 +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 - * . - * - */ -package org.apache.hc.client5.http.io; - -import java.io.IOException; -import java.io.InputStream; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; - -@SuppressWarnings({"boxing","static-access"}) // test code -public class TestEofSensorInputStream { - - private InputStream instream; - private EofSensorWatcher eofwatcher; - private EofSensorInputStream eofstream; - - @Before - public void setup() throws Exception { - instream = Mockito.mock(InputStream.class); - eofwatcher = Mockito.mock(EofSensorWatcher.class); - eofstream = new EofSensorInputStream(instream, eofwatcher); - } - - @Test - public void testClose() throws Exception { - Mockito.when(eofwatcher.streamClosed(Mockito.any())).thenReturn(Boolean.TRUE); - - eofstream.close(); - - Assert.assertTrue(eofstream.isSelfClosed()); - Assert.assertNull(eofstream.getWrappedStream()); - - Mockito.verify(instream, Mockito.times(1)).close(); - Mockito.verify(eofwatcher).streamClosed(instream); - - eofstream.close(); - } - - @Test - public void testCloseIOError() throws Exception { - Mockito.when(eofwatcher.streamClosed(Mockito.any())).thenThrow(new IOException()); - - try { - eofstream.close(); - Assert.fail("IOException expected"); - } catch (final IOException ex) { - } - Assert.assertTrue(eofstream.isSelfClosed()); - Assert.assertNull(eofstream.getWrappedStream()); - - Mockito.verify(eofwatcher).streamClosed(instream); - } - - @Test - public void testReleaseConnection() throws Exception { - Mockito.when(eofwatcher.streamClosed(Mockito.any())).thenReturn(Boolean.TRUE); - - eofstream.releaseConnection(); - - Assert.assertTrue(eofstream.isSelfClosed()); - Assert.assertNull(eofstream.getWrappedStream()); - - Mockito.verify(instream, Mockito.times(1)).close(); - Mockito.verify(eofwatcher).streamClosed(instream); - - eofstream.releaseConnection(); - } - - @Test - public void testAbortConnection() throws Exception { - Mockito.when(eofwatcher.streamAbort(Mockito.any())).thenReturn(Boolean.TRUE); - - eofstream.abortConnection(); - - Assert.assertTrue(eofstream.isSelfClosed()); - Assert.assertNull(eofstream.getWrappedStream()); - - Mockito.verify(instream, Mockito.times(1)).close(); - Mockito.verify(eofwatcher).streamAbort(instream); - - eofstream.abortConnection(); - } - - @Test - public void testAbortConnectionIOError() throws Exception { - Mockito.when(eofwatcher.streamAbort(Mockito.any())).thenThrow(new IOException()); - - try { - eofstream.abortConnection(); - Assert.fail("IOException expected"); - } catch (final IOException ex) { - } - Assert.assertTrue(eofstream.isSelfClosed()); - Assert.assertNull(eofstream.getWrappedStream()); - - Mockito.verify(eofwatcher).streamAbort(instream); - } - - @Test - public void testRead() throws Exception { - Mockito.when(eofwatcher.eofDetected(Mockito.any())).thenReturn(Boolean.TRUE); - Mockito.when(instream.read()).thenReturn(0, -1); - - Assert.assertEquals(0, eofstream.read()); - - Assert.assertFalse(eofstream.isSelfClosed()); - Assert.assertNotNull(eofstream.getWrappedStream()); - - Mockito.verify(eofwatcher, Mockito.never()).eofDetected(instream); - - Assert.assertEquals(-1, eofstream.read()); - - Assert.assertFalse(eofstream.isSelfClosed()); - Assert.assertNull(eofstream.getWrappedStream()); - - Mockito.verify(instream, Mockito.times(1)).close(); - Mockito.verify(eofwatcher).eofDetected(instream); - - Assert.assertEquals(-1, eofstream.read()); - } - - @Test - public void testReadIOError() throws Exception { - Mockito.when(eofwatcher.eofDetected(Mockito.any())).thenReturn(Boolean.TRUE); - Mockito.when(instream.read()).thenThrow(new IOException()); - - try { - eofstream.read(); - Assert.fail("IOException expected"); - } catch (final IOException ex) { - } - Assert.assertFalse(eofstream.isSelfClosed()); - Assert.assertNull(eofstream.getWrappedStream()); - - Mockito.verify(eofwatcher).streamAbort(instream); - } - - @Test - public void testReadByteArray() throws Exception { - Mockito.when(eofwatcher.eofDetected(Mockito.any())).thenReturn(Boolean.TRUE); - Mockito.when(instream.read(Mockito.any(), Mockito.anyInt(), Mockito.anyInt())) - .thenReturn(1, -1); - - final byte[] tmp = new byte[1]; - - Assert.assertEquals(1, eofstream.read(tmp)); - - Assert.assertFalse(eofstream.isSelfClosed()); - Assert.assertNotNull(eofstream.getWrappedStream()); - - Mockito.verify(eofwatcher, Mockito.never()).eofDetected(instream); - - Assert.assertEquals(-1, eofstream.read(tmp)); - - Assert.assertFalse(eofstream.isSelfClosed()); - Assert.assertNull(eofstream.getWrappedStream()); - - Mockito.verify(instream, Mockito.times(1)).close(); - Mockito.verify(eofwatcher).eofDetected(instream); - - Assert.assertEquals(-1, eofstream.read(tmp)); - } - - @Test - public void testReadByteArrayIOError() throws Exception { - Mockito.when(eofwatcher.eofDetected(Mockito.any())).thenReturn(Boolean.TRUE); - Mockito.when(instream.read(Mockito.any(), Mockito.anyInt(), Mockito.anyInt())) - .thenThrow(new IOException()); - - final byte[] tmp = new byte[1]; - try { - eofstream.read(tmp); - Assert.fail("IOException expected"); - } catch (final IOException ex) { - } - Assert.assertFalse(eofstream.isSelfClosed()); - Assert.assertNull(eofstream.getWrappedStream()); - - Mockito.verify(eofwatcher).streamAbort(instream); - } - - @Test - public void testReadAfterAbort() throws Exception { - Mockito.when(eofwatcher.streamAbort(Mockito.any())).thenReturn(Boolean.TRUE); - - eofstream.abortConnection(); - - try { - eofstream.read(); - Assert.fail("IOException expected"); - } catch (final IOException ex) { - } - final byte[] tmp = new byte[1]; - try { - eofstream.read(tmp); - Assert.fail("IOException expected"); - } catch (final IOException ex) { - } - } - -} diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/localserver/EchoHandler.java b/httpclient5/src/test/java/org/apache/hc/client5/http/localserver/EchoHandler.java index 1f32f2d58..55ae9b9ec 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/localserver/EchoHandler.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/localserver/EchoHandler.java @@ -30,15 +30,15 @@ package org.apache.hc.client5.http.localserver; import java.io.IOException; import java.util.Locale; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.HttpException; -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.MethodNotSupportedException; -import org.apache.hc.core5.http.entity.ByteArrayEntity; -import org.apache.hc.core5.http.entity.EntityUtils; import org.apache.hc.core5.http.io.HttpRequestHandler; +import org.apache.hc.core5.http.io.entity.ByteArrayEntity; +import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.http.protocol.HttpContext; /** @@ -58,12 +58,12 @@ public class EchoHandler implements HttpRequestHandler { * @throws IOException in case of an IO problem */ @Override - public void handle(final HttpRequest request, - final HttpResponse response, + public void handle(final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { - final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ROOT); + final String method = request.getMethod().toUpperCase(Locale.ROOT); if (!"GET".equals(method) && !"POST".equals(method) && !"PUT".equals(method) @@ -89,7 +89,7 @@ public class EchoHandler implements HttpRequestHandler { } entity = bae; - response.setStatusCode(HttpStatus.SC_OK); + response.setCode(HttpStatus.SC_OK); response.setEntity(entity); } diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/localserver/LocalServerTestBase.java b/httpclient5/src/test/java/org/apache/hc/client5/http/localserver/LocalServerTestBase.java index 3a2761795..74f82f88c 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/localserver/LocalServerTestBase.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/localserver/LocalServerTestBase.java @@ -33,9 +33,9 @@ import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager; import org.apache.hc.client5.http.impl.sync.CloseableHttpClient; import org.apache.hc.client5.http.impl.sync.HttpClientBuilder; import org.apache.hc.core5.http.HttpHost; -import org.apache.hc.core5.http.bootstrap.io.HttpServer; -import org.apache.hc.core5.http.bootstrap.io.ServerBootstrap; import org.apache.hc.core5.http.config.SocketConfig; +import org.apache.hc.core5.http.impl.io.bootstrap.HttpServer; +import org.apache.hc.core5.http.impl.io.bootstrap.ServerBootstrap; import org.junit.After; import org.junit.Before; @@ -46,8 +46,6 @@ public abstract class LocalServerTestBase { public enum ProtocolScheme { http, https }; - public static final String ORIGIN = "TEST/1.1"; - protected final ProtocolScheme scheme; protected ServerBootstrap serverBootstrap; @@ -75,7 +73,6 @@ public abstract class LocalServerTestBase { .build(); this.serverBootstrap = ServerBootstrap.bootstrap() .setSocketConfig(socketConfig) - .setServerInfo(ORIGIN) .registerHandler("/echo/*", new EchoHandler()) .registerHandler("/random/*", new RandomHandler()); if (this.scheme.equals(ProtocolScheme.https)) { diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/localserver/RandomHandler.java b/httpclient5/src/test/java/org/apache/hc/client5/http/localserver/RandomHandler.java index 256f990bc..d1f3f128d 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/localserver/RandomHandler.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/localserver/RandomHandler.java @@ -33,13 +33,13 @@ import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.util.Locale; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpException; -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.MethodNotSupportedException; -import org.apache.hc.core5.http.entity.AbstractHttpEntity; import org.apache.hc.core5.http.io.HttpRequestHandler; +import org.apache.hc.core5.http.io.entity.AbstractHttpEntity; import org.apache.hc.core5.http.protocol.HttpContext; /** @@ -63,18 +63,18 @@ public class RandomHandler implements HttpRequestHandler { * @throws IOException in case of an IO problem */ @Override - public void handle(final HttpRequest request, - final HttpResponse response, + public void handle(final ClassicHttpRequest request, + final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { - final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ROOT); + final String method = request.getMethod().toUpperCase(Locale.ROOT); if (!"GET".equals(method) && !"HEAD".equals(method)) { throw new MethodNotSupportedException (method + " not supported by " + getClass().getName()); } - final String uri = request.getRequestLine().getUri(); + final String uri = request.getRequestUri(); final int slash = uri.lastIndexOf('/'); int length = -1; if (slash < uri.length()-1) { @@ -83,11 +83,11 @@ public class RandomHandler implements HttpRequestHandler { length = Integer.parseInt(uri.substring(slash+1)); if (length < 0) { - response.setStatusCode(HttpStatus.SC_BAD_REQUEST); + response.setCode(HttpStatus.SC_BAD_REQUEST); response.setReasonPhrase("LENGTH " + length); } } catch (final NumberFormatException nfx) { - response.setStatusCode(HttpStatus.SC_BAD_REQUEST); + response.setCode(HttpStatus.SC_BAD_REQUEST); response.setReasonPhrase(nfx.toString()); } } else { @@ -97,7 +97,7 @@ public class RandomHandler implements HttpRequestHandler { if (length >= 0) { - response.setStatusCode(HttpStatus.SC_OK); + response.setCode(HttpStatus.SC_OK); if (!"HEAD".equals(method)) { final RandomEntity entity = new RandomEntity(length); @@ -217,9 +217,12 @@ public class RandomHandler implements HttpRequestHandler { } out.close(); - } // writeTo + } - } // class RandomEntity + @Override + public void close() throws IOException { + } + } -} // class RandomHandler +} diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/localserver/RequestBasicAuth.java b/httpclient5/src/test/java/org/apache/hc/client5/http/localserver/RequestBasicAuth.java index 753b8fa60..7b9dda656 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/localserver/RequestBasicAuth.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/localserver/RequestBasicAuth.java @@ -29,6 +29,7 @@ package org.apache.hc.client5.http.localserver; import java.io.IOException; +import org.apache.hc.core5.http.EntityDetails; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.HttpRequestInterceptor; @@ -46,6 +47,7 @@ public class RequestBasicAuth implements HttpRequestInterceptor { @Override public void process( final HttpRequest request, + final EntityDetails entityDetails, final HttpContext context) throws HttpException, IOException { context.setAttribute("creds", this.authTokenExtractor.extract(request)); } diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/localserver/ResponseBasicUnauthorized.java b/httpclient5/src/test/java/org/apache/hc/client5/http/localserver/ResponseBasicUnauthorized.java index 7f47854f2..c0adf6844 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/localserver/ResponseBasicUnauthorized.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/localserver/ResponseBasicUnauthorized.java @@ -29,6 +29,7 @@ package org.apache.hc.client5.http.localserver; import java.io.IOException; +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.HttpResponse; @@ -41,8 +42,9 @@ public class ResponseBasicUnauthorized implements HttpResponseInterceptor { @Override public void process( final HttpResponse response, + final EntityDetails entityDetails, final HttpContext context) throws HttpException, IOException { - if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { + if (response.getCode() == HttpStatus.SC_UNAUTHORIZED) { if (!response.containsHeader(HttpHeaders.WWW_AUTHENTICATE)) { response.addHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"test realm\""); } diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/methods/TestHttpOptions.java b/httpclient5/src/test/java/org/apache/hc/client5/http/methods/TestHttpOptions.java index 9985a0354..a0f986216 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/methods/TestHttpOptions.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/methods/TestHttpOptions.java @@ -29,9 +29,7 @@ package org.apache.hc.client5.http.methods; import java.util.Set; -import org.apache.hc.core5.http.ProtocolVersion; import org.apache.hc.core5.http.message.BasicHttpResponse; -import org.apache.hc.core5.http.message.BasicStatusLine; import org.junit.Assert; import org.junit.Test; @@ -39,13 +37,11 @@ public class TestHttpOptions { @Test public void testMultipleAllows() { - final ProtocolVersion proto = new ProtocolVersion("HTTP", 1, 1); - final BasicStatusLine line = new BasicStatusLine(proto, 200, "test reason"); - final BasicHttpResponse resp = new BasicHttpResponse(line); + final BasicHttpResponse resp = new BasicHttpResponse(200, "test reason"); resp.addHeader("Allow", "POST"); resp.addHeader("Allow", "GET"); - final HttpOptions opt = new HttpOptions(); + final HttpOptions opt = new HttpOptions("*"); final Set methodsName = opt.getAllowedMethods(resp); Assert.assertTrue(methodsName.contains("POST")); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/methods/TestHttpRequestBase.java b/httpclient5/src/test/java/org/apache/hc/client5/http/methods/TestHttpRequestBase.java index e7804f038..a7c55905e 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/methods/TestHttpRequestBase.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/methods/TestHttpRequestBase.java @@ -27,7 +27,8 @@ package org.apache.hc.client5.http.methods; -import org.apache.hc.core5.http.HttpVersion; +import java.net.URI; + import org.junit.Assert; import org.junit.Test; @@ -36,15 +37,14 @@ public class TestHttpRequestBase { @Test public void testBasicProperties() throws Exception { final HttpGet httpget = new HttpGet("http://host/path"); - Assert.assertEquals("GET", httpget.getRequestLine().getMethod()); - Assert.assertEquals("http://host/path", httpget.getRequestLine().getUri()); - Assert.assertEquals(HttpVersion.HTTP_1_1, httpget.getRequestLine().getProtocolVersion()); + Assert.assertEquals("GET", httpget.getMethod()); + Assert.assertEquals(new URI("http://host/path"), httpget.getUri()); } @Test public void testEmptyURI() throws Exception { final HttpGet httpget = new HttpGet(""); - Assert.assertEquals("/", httpget.getRequestLine().getUri()); + Assert.assertEquals(new URI("/"), httpget.getUri()); } } diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/methods/TestRequestBuilder.java b/httpclient5/src/test/java/org/apache/hc/client5/http/methods/TestRequestBuilder.java index 38da79555..f71fbd60b 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/methods/TestRequestBuilder.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/methods/TestRequestBuilder.java @@ -31,15 +31,14 @@ import java.net.URI; import java.util.List; import org.apache.hc.client5.http.config.RequestConfig; +import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.HttpVersion; import org.apache.hc.core5.http.NameValuePair; -import org.apache.hc.core5.http.entity.BasicHttpEntity; -import org.apache.hc.core5.http.entity.ContentType; -import org.apache.hc.core5.http.entity.EntityUtils; -import org.apache.hc.core5.http.entity.StringEntity; +import org.apache.hc.core5.http.io.entity.BasicHttpEntity; +import org.apache.hc.core5.http.io.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.StringEntity; import org.apache.hc.core5.http.message.BasicHeader; import org.apache.hc.core5.http.message.BasicNameValuePair; import org.junit.Assert; @@ -52,8 +51,7 @@ public class TestRequestBuilder { final HttpUriRequest request = RequestBuilder.get().build(); Assert.assertNotNull(request); Assert.assertEquals("GET", request.getMethod()); - Assert.assertEquals(URI.create("/"), request.getURI()); - Assert.assertEquals(HttpVersion.HTTP_1_1, request.getProtocolVersion()); + Assert.assertEquals(URI.create("/"), request.getUri()); } @Test @@ -61,8 +59,7 @@ public class TestRequestBuilder { final HttpUriRequest request = RequestBuilder.create("Whatever").build(); Assert.assertNotNull(request); Assert.assertEquals("Whatever", request.getMethod()); - Assert.assertEquals(URI.create("/"), request.getURI()); - Assert.assertEquals(HttpVersion.HTTP_1_1, request.getProtocolVersion()); + Assert.assertEquals(URI.create("/"), request.getUri()); } @Test @@ -71,8 +68,7 @@ public class TestRequestBuilder { final HttpUriRequest request = RequestBuilder.post().setEntity(entity).build(); Assert.assertNotNull(request); Assert.assertEquals("POST", request.getMethod()); - Assert.assertEquals(URI.create("/"), request.getURI()); - Assert.assertEquals(HttpVersion.HTTP_1_1, request.getProtocolVersion()); + Assert.assertEquals(URI.create("/"), request.getUri()); Assert.assertSame(entity, request.getEntity()); } @@ -82,8 +78,7 @@ public class TestRequestBuilder { final HttpUriRequest request = RequestBuilder.get().setEntity(entity).build(); Assert.assertNotNull(request); Assert.assertEquals("GET", request.getMethod()); - Assert.assertEquals(URI.create("/"), request.getURI()); - Assert.assertEquals(HttpVersion.HTTP_1_1, request.getProtocolVersion()); + Assert.assertEquals(URI.create("/"), request.getUri()); Assert.assertSame(entity, request.getEntity()); } @@ -93,7 +88,7 @@ public class TestRequestBuilder { .addParameter("p1", "this") .addParameter("p2", "that") .build(); - Assert.assertEquals(new URI("/?p1=this&p2=that"), request.getURI()); + Assert.assertEquals(new URI("/?p1=this&p2=that"), request.getUri()); } @Test @@ -102,7 +97,7 @@ public class TestRequestBuilder { .addParameter("p1", "this") .addParameters(new BasicNameValuePair("p2", "that")) .build(); - Assert.assertEquals(new URI("/?p1=this&p2=that"), request.getURI()); + Assert.assertEquals(new URI("/?p1=this&p2=that"), request.getUri()); } @Test @@ -113,7 +108,7 @@ public class TestRequestBuilder { .build(); final HttpEntity entity = request.getEntity(); Assert.assertNotNull(entity); - Assert.assertEquals(new URI("/"), request.getURI()); + Assert.assertEquals(new URI("/"), request.getUri()); Assert.assertEquals("p1=this&p2=that", EntityUtils.toString(entity)); } @@ -125,7 +120,7 @@ public class TestRequestBuilder { .addParameter("p2", "that") .setEntity(new StringEntity("blah")) .build(); - Assert.assertEquals(new URI("http://targethost/?blah&p1=this&p2=that"), request.getURI()); + Assert.assertEquals(new URI("http://targethost/?blah&p1=this&p2=that"), request.getUri()); } @Test @@ -142,12 +137,12 @@ public class TestRequestBuilder { .build(); Assert.assertNotNull(request); Assert.assertEquals("PUT", request.getMethod()); - Assert.assertEquals(URI.create("/stuff"), request.getURI()); - Assert.assertEquals(HttpVersion.HTTP_1_0, request.getProtocolVersion()); + Assert.assertEquals(URI.create("/stuff"), request.getUri()); + Assert.assertEquals(HttpVersion.HTTP_1_0, request.getVersion()); final HttpUriRequest copy = RequestBuilder.copy(request).setUri("/other-stuff").build(); Assert.assertEquals("PUT", copy.getMethod()); - Assert.assertEquals(URI.create("/other-stuff"), copy.getURI()); + Assert.assertEquals(URI.create("/other-stuff"), copy.getUri()); Assert.assertSame(entity, copy.getEntity()); Assert.assertTrue(copy instanceof Configurable); Assert.assertSame(config, ((Configurable) copy).getConfig()); @@ -202,9 +197,9 @@ public class TestRequestBuilder { public void testCopyAndSetUri() throws Exception { final URI uri1 = URI.create("http://host1.com/path?param=something"); final URI uri2 = URI.create("http://host2.com/path?param=somethingdifferent"); - final HttpRequest request1 = new HttpGet(uri1); + final HttpGet request1 = new HttpGet(uri1); final HttpUriRequest request2 = RequestBuilder.copy(request1).setUri(uri2).build(); - Assert.assertEquals(request2.getURI(), uri2); + Assert.assertEquals(request2.getUri(), uri2); } @Test diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestRequestAcceptEncoding.java b/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestRequestAcceptEncoding.java index 101f971d3..7b163a21a 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestRequestAcceptEncoding.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestRequestAcceptEncoding.java @@ -43,7 +43,7 @@ public class TestRequestAcceptEncoding { final HttpContext context = new BasicHttpContext(); final HttpRequestInterceptor interceptor = new RequestAcceptEncoding(); - interceptor.process(request, context); + interceptor.process(request, null, context); final Header header = request.getFirstHeader("Accept-Encoding"); Assert.assertNotNull(header); Assert.assertEquals("gzip,deflate", header.getValue()); @@ -56,7 +56,7 @@ public class TestRequestAcceptEncoding { final HttpContext context = new BasicHttpContext(); final HttpRequestInterceptor interceptor = new RequestAcceptEncoding(); - interceptor.process(request, context); + interceptor.process(request, null, context); final Header header = request.getFirstHeader("Accept-Encoding"); Assert.assertNotNull(header); Assert.assertEquals("stuff", header.getValue()); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestRequestAddCookies.java b/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestRequestAddCookies.java index 056a3ab30..1c6305e3c 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestRequestAddCookies.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestRequestAddCookies.java @@ -90,14 +90,14 @@ public class TestRequestAddCookies { public void testRequestParameterCheck() throws Exception { final HttpClientContext context = HttpClientContext.create(); final HttpRequestInterceptor interceptor = new RequestAddCookies(); - interceptor.process(null, context); + interceptor.process(null, null, context); } @Test(expected=IllegalArgumentException.class) public void testContextParameterCheck() throws Exception { final HttpRequest request = new BasicHttpRequest("GET", "/"); final HttpRequestInterceptor interceptor = new RequestAddCookies(); - interceptor.process(request, null); + interceptor.process(request, null, null); } @Test @@ -107,13 +107,12 @@ public class TestRequestAddCookies { final HttpRoute route = new HttpRoute(this.target, null, false); final HttpClientContext context = HttpClientContext.create(); - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target); context.setAttribute(HttpClientContext.HTTP_ROUTE, route); context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore); context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry); final HttpRequestInterceptor interceptor = new RequestAddCookies(); - interceptor.process(request, context); + interceptor.process(request, null, context); final Header[] headers = request.getHeaders("Cookie"); Assert.assertNotNull(headers); @@ -135,13 +134,12 @@ public class TestRequestAddCookies { final HttpRoute route = new HttpRoute(this.target, null, false); final HttpClientContext context = HttpClientContext.create(); - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target); context.setAttribute(HttpClientContext.HTTP_ROUTE, route); context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore); context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry); final HttpRequestInterceptor interceptor = new RequestAddCookies(); - interceptor.process(request, context); + interceptor.process(request, null, context); final Header[] headers = request.getHeaders("Cookie"); Assert.assertNotNull(headers); @@ -155,13 +153,12 @@ public class TestRequestAddCookies { final HttpRoute route = new HttpRoute(this.target, null, false); final HttpClientContext context = HttpClientContext.create(); - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target); context.setAttribute(HttpClientContext.HTTP_ROUTE, route); context.setAttribute(HttpClientContext.COOKIE_STORE, null); context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry); final HttpRequestInterceptor interceptor = new RequestAddCookies(); - interceptor.process(request, context); + interceptor.process(request, null, context); final Header[] headers = request.getHeaders("Cookie"); Assert.assertNotNull(headers); @@ -175,33 +172,12 @@ public class TestRequestAddCookies { final HttpRoute route = new HttpRoute(this.target, null, false); final HttpClientContext context = HttpClientContext.create(); - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target); context.setAttribute(HttpClientContext.HTTP_ROUTE, route); context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore); context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, null); final HttpRequestInterceptor interceptor = new RequestAddCookies(); - interceptor.process(request, context); - - final Header[] headers = request.getHeaders("Cookie"); - Assert.assertNotNull(headers); - Assert.assertEquals(0, headers.length); - } - - @Test - public void testNoTargetHost() throws Exception { - final HttpRequest request = new BasicHttpRequest("GET", "/"); - - final HttpRoute route = new HttpRoute(this.target, null, false); - - final HttpClientContext context = HttpClientContext.create(); - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, null); - context.setAttribute(HttpClientContext.HTTP_ROUTE, route); - context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore); - context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry); - - final HttpRequestInterceptor interceptor = new RequestAddCookies(); - interceptor.process(request, context); + interceptor.process(request, null, context); final Header[] headers = request.getHeaders("Cookie"); Assert.assertNotNull(headers); @@ -213,13 +189,12 @@ public class TestRequestAddCookies { final HttpRequest request = new BasicHttpRequest("GET", "/"); final HttpClientContext context = HttpClientContext.create(); - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target); context.setAttribute(HttpCoreContext.HTTP_CONNECTION, null); context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore); context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry); final HttpRequestInterceptor interceptor = new RequestAddCookies(); - interceptor.process(request, context); + interceptor.process(request, null, context); final Header[] headers = request.getHeaders("Cookie"); Assert.assertNotNull(headers); @@ -234,14 +209,13 @@ public class TestRequestAddCookies { final HttpRoute route = new HttpRoute(this.target, null, false); final HttpClientContext context = HttpClientContext.create(); - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target); context.setAttribute(HttpClientContext.HTTP_ROUTE, route); context.setAttribute(HttpClientContext.REQUEST_CONFIG, config); context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore); context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry); final HttpRequestInterceptor interceptor = new RequestAddCookies(); - interceptor.process(request, context); + interceptor.process(request, null, context); final CookieSpec cookieSpec = context.getCookieSpec(); Assert.assertTrue(cookieSpec instanceof RFC6265StrictSpec); @@ -259,13 +233,12 @@ public class TestRequestAddCookies { final HttpRoute route = new HttpRoute(this.target, null, false); final HttpClientContext context = HttpClientContext.create(); - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target); context.setAttribute(HttpClientContext.HTTP_ROUTE, route); context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore); context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry); final HttpRequestInterceptor interceptor = new RequestAddCookies(); - interceptor.process(request, context); + interceptor.process(request, null, context); } @Test @@ -276,13 +249,12 @@ public class TestRequestAddCookies { final HttpRoute route = new HttpRoute(new HttpHost("localhost.local", 1234), null, false); final HttpClientContext context = HttpClientContext.create(); - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target); context.setAttribute(HttpClientContext.HTTP_ROUTE, route); context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore); context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry); final HttpRequestInterceptor interceptor = new RequestAddCookies(); - interceptor.process(request, context); + interceptor.process(request, null, context); final CookieOrigin cookieOrigin = context.getCookieOrigin(); Assert.assertNotNull(cookieOrigin); @@ -301,13 +273,12 @@ public class TestRequestAddCookies { new HttpHost("localhost.local", 80), null, new HttpHost("localhost", 8888), false); final HttpClientContext context = HttpClientContext.create(); - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target); context.setAttribute(HttpClientContext.HTTP_ROUTE, route); context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore); context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry); final HttpRequestInterceptor interceptor = new RequestAddCookies(); - interceptor.process(request, context); + interceptor.process(request, null, context); final CookieOrigin cookieOrigin = context.getCookieOrigin(); Assert.assertNotNull(cookieOrigin); @@ -327,13 +298,12 @@ public class TestRequestAddCookies { new HttpHost("localhost", 8888), true, TunnelType.TUNNELLED, LayerType.LAYERED); final HttpClientContext context = HttpClientContext.create(); - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target); context.setAttribute(HttpClientContext.HTTP_ROUTE, route); context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore); context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry); final HttpRequestInterceptor interceptor = new RequestAddCookies(); - interceptor.process(request, context); + interceptor.process(request, null, context); final CookieOrigin cookieOrigin = context.getCookieOrigin(); Assert.assertNotNull(cookieOrigin); @@ -360,7 +330,6 @@ public class TestRequestAddCookies { final HttpRoute route = new HttpRoute(this.target, null, false); final HttpClientContext context = HttpClientContext.create(); - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target); context.setAttribute(HttpClientContext.HTTP_ROUTE, route); context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore); context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry); @@ -369,7 +338,7 @@ public class TestRequestAddCookies { Thread.sleep(200); final HttpRequestInterceptor interceptor = new RequestAddCookies(); - interceptor.process(request, context); + interceptor.process(request, null, context); final Header[] headers = request.getHeaders("Cookie"); Assert.assertNotNull(headers); @@ -392,13 +361,12 @@ public class TestRequestAddCookies { final HttpRoute route = new HttpRoute(this.target, null, false); final HttpClientContext context = HttpClientContext.create(); - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target); context.setAttribute(HttpClientContext.HTTP_ROUTE, route); context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore); context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry); final HttpRequestInterceptor interceptor = new RequestAddCookies(); - interceptor.process(request, context); + interceptor.process(request, null, context); final Header[] headers = request.getHeaders("Cookie"); Assert.assertNotNull(headers); @@ -428,13 +396,12 @@ public class TestRequestAddCookies { final HttpRoute route = new HttpRoute(this.target, null, false); final HttpClientContext context = HttpClientContext.create(); - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target); context.setAttribute(HttpClientContext.HTTP_ROUTE, route); context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore); context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry); final HttpRequestInterceptor interceptor = new RequestAddCookies(); - interceptor.process(request, context); + interceptor.process(request, null, context); final Header[] headers1 = request.getHeaders("Cookie"); Assert.assertNotNull(headers1); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestRequestClientConnControl.java b/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestRequestClientConnControl.java index 716836ee1..0411c77f1 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestRequestClientConnControl.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestRequestClientConnControl.java @@ -45,7 +45,7 @@ public class TestRequestClientConnControl { public void testRequestParameterCheck() throws Exception { final HttpClientContext context = HttpClientContext.create(); final HttpRequestInterceptor interceptor = new RequestClientConnControl(); - interceptor.process(null, context); + interceptor.process(null, null, context); } @Test @@ -54,7 +54,7 @@ public class TestRequestClientConnControl { final HttpClientContext context = HttpClientContext.create(); final HttpRequestInterceptor interceptor = new RequestClientConnControl(); - interceptor.process(request, context); + interceptor.process(request, null, context); final Header header1 = request.getFirstHeader("Proxy-Connection"); Assert.assertNotNull(header1); Assert.assertEquals(HeaderElements.KEEP_ALIVE, header1.getValue()); @@ -73,7 +73,7 @@ public class TestRequestClientConnControl { context.setAttribute(HttpClientContext.HTTP_ROUTE, route); final HttpRequestInterceptor interceptor = new RequestClientConnControl(); - interceptor.process(request, context); + interceptor.process(request, null, context); final Header header1 = request.getFirstHeader(HttpHeaders.CONNECTION); Assert.assertNotNull(header1); @@ -95,7 +95,7 @@ public class TestRequestClientConnControl { context.setAttribute(HttpClientContext.HTTP_ROUTE, route); final HttpRequestInterceptor interceptor = new RequestClientConnControl(); - interceptor.process(request, context); + interceptor.process(request, null, context); final Header header1 = request.getFirstHeader(HttpHeaders.CONNECTION); Assert.assertNotNull(header1); @@ -117,7 +117,7 @@ public class TestRequestClientConnControl { context.setAttribute(HttpClientContext.HTTP_ROUTE, route); final HttpRequestInterceptor interceptor = new RequestClientConnControl(); - interceptor.process(request, context); + interceptor.process(request, null, context); final Header header1 = request.getFirstHeader("Proxy-Connection"); Assert.assertNotNull(header1); @@ -140,7 +140,7 @@ public class TestRequestClientConnControl { context.setAttribute(HttpClientContext.HTTP_ROUTE, route); final HttpRequestInterceptor interceptor = new RequestClientConnControl(); - interceptor.process(request, context); + interceptor.process(request, null, context); final Header header1 = request.getFirstHeader(HttpHeaders.CONNECTION); Assert.assertNotNull(header1); @@ -163,7 +163,7 @@ public class TestRequestClientConnControl { context.setAttribute(HttpClientContext.HTTP_ROUTE, route); final HttpRequestInterceptor interceptor = new RequestClientConnControl(); - interceptor.process(request, context); + interceptor.process(request, null, context); final Header header1 = request.getFirstHeader("Proxy-Connection"); Assert.assertNotNull(header1); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestRequestDefaultHeaders.java b/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestRequestDefaultHeaders.java index 86aad6a97..490453b45 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestRequestDefaultHeaders.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestRequestDefaultHeaders.java @@ -45,7 +45,7 @@ public class TestRequestDefaultHeaders { public void testRequestParameterCheck() throws Exception { final HttpContext context = new BasicHttpContext(); final HttpRequestInterceptor interceptor = new RequestDefaultHeaders(); - interceptor.process(null, context); + interceptor.process(null, null, context); } @Test @@ -56,7 +56,7 @@ public class TestRequestDefaultHeaders { final HttpContext context = new BasicHttpContext(); final HttpRequestInterceptor interceptor = new RequestDefaultHeaders(defheaders); - interceptor.process(request, context); + interceptor.process(request, null, context); final Header header1 = request.getFirstHeader("custom"); Assert.assertNull(header1); } @@ -70,7 +70,7 @@ public class TestRequestDefaultHeaders { final HttpContext context = new BasicHttpContext(); final HttpRequestInterceptor interceptor = new RequestDefaultHeaders(defheaders); - interceptor.process(request, context); + interceptor.process(request, null, context); final Header[] headers = request.getHeaders("custom"); Assert.assertNotNull(headers); Assert.assertEquals(1, headers.length); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestRequestExpectContinue.java b/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestRequestExpectContinue.java index bf4b83b53..a75e42af4 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestRequestExpectContinue.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestRequestExpectContinue.java @@ -30,12 +30,13 @@ package org.apache.hc.client5.http.protocol; import java.nio.charset.StandardCharsets; import org.apache.hc.client5.http.config.RequestConfig; +import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HeaderElements; import org.apache.hc.core5.http.HttpHeaders; import org.apache.hc.core5.http.HttpVersion; -import org.apache.hc.core5.http.entity.StringEntity; -import org.apache.hc.core5.http.message.BasicHttpRequest; +import org.apache.hc.core5.http.io.entity.StringEntity; +import org.apache.hc.core5.http.message.BasicClassicHttpRequest; import org.apache.hc.core5.http.protocol.BasicHttpContext; import org.apache.hc.core5.http.protocol.HttpContext; import org.junit.Assert; @@ -48,12 +49,12 @@ public class TestRequestExpectContinue { final HttpClientContext context = HttpClientContext.create(); final RequestConfig config = RequestConfig.custom().setExpectContinueEnabled(true).build(); context.setAttribute(HttpClientContext.REQUEST_CONFIG, config); - final BasicHttpRequest request = new BasicHttpRequest("POST", "/"); + final ClassicHttpRequest request = new BasicClassicHttpRequest("POST", "/"); final String s = "whatever"; final StringEntity entity = new StringEntity(s, StandardCharsets.US_ASCII); request.setEntity(entity); final RequestExpectContinue interceptor = new RequestExpectContinue(); - interceptor.process(request, context); + interceptor.process(request, request.getEntity(), context); final Header header = request.getFirstHeader(HttpHeaders.EXPECT); Assert.assertNotNull(header); Assert.assertEquals(HeaderElements.CONTINUE, header.getValue()); @@ -64,12 +65,12 @@ public class TestRequestExpectContinue { final HttpContext context = new BasicHttpContext(null); final RequestConfig config = RequestConfig.custom().setExpectContinueEnabled(false).build(); context.setAttribute(HttpClientContext.REQUEST_CONFIG, config); - final BasicHttpRequest request = new BasicHttpRequest("POST", "/"); + final ClassicHttpRequest request = new BasicClassicHttpRequest("POST", "/"); final String s = "whatever"; final StringEntity entity = new StringEntity(s, StandardCharsets.US_ASCII); request.setEntity(entity); final RequestExpectContinue interceptor = new RequestExpectContinue(); - interceptor.process(request, context); + interceptor.process(request, null, context); final Header header = request.getFirstHeader(HeaderElements.CONTINUE); Assert.assertNull(header); } @@ -79,13 +80,13 @@ public class TestRequestExpectContinue { final HttpContext context = new BasicHttpContext(null); final RequestConfig config = RequestConfig.custom().setExpectContinueEnabled(true).build(); context.setAttribute(HttpClientContext.REQUEST_CONFIG, config); - final BasicHttpRequest request = new BasicHttpRequest( - "POST", "/", HttpVersion.HTTP_1_0); + final ClassicHttpRequest request = new BasicClassicHttpRequest("POST", "/"); + request.setVersion(HttpVersion.HTTP_1_0); final String s = "whatever"; final StringEntity entity = new StringEntity(s, StandardCharsets.US_ASCII); request.setEntity(entity); final RequestExpectContinue interceptor = new RequestExpectContinue(); - interceptor.process(request, context); + interceptor.process(request, null, context); final Header header = request.getFirstHeader(HeaderElements.CONTINUE); Assert.assertNull(header); } @@ -95,12 +96,12 @@ public class TestRequestExpectContinue { final HttpContext context = new BasicHttpContext(null); final RequestConfig config = RequestConfig.custom().setExpectContinueEnabled(true).build(); context.setAttribute(HttpClientContext.REQUEST_CONFIG, config); - final BasicHttpRequest request = new BasicHttpRequest("POST", "/"); + final ClassicHttpRequest request = new BasicClassicHttpRequest("POST", "/"); final String s = ""; final StringEntity entity = new StringEntity(s, StandardCharsets.US_ASCII); request.setEntity(entity); final RequestExpectContinue interceptor = new RequestExpectContinue(); - interceptor.process(request, context); + interceptor.process(request, null, context); final Header header = request.getFirstHeader(HeaderElements.CONTINUE); Assert.assertNull(header); } @@ -109,7 +110,7 @@ public class TestRequestExpectContinue { public void testRequestExpectContinueInvalidInput() throws Exception { final RequestExpectContinue interceptor = new RequestExpectContinue(); try { - interceptor.process(null, null); + interceptor.process(null, null, null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected @@ -119,9 +120,9 @@ public class TestRequestExpectContinue { @Test public void testRequestExpectContinueIgnoreNonenclosingRequests() throws Exception { final HttpContext context = new BasicHttpContext(null); - final BasicHttpRequest request = new BasicHttpRequest("POST", "/"); + final ClassicHttpRequest request = new BasicClassicHttpRequest("POST", "/"); final RequestExpectContinue interceptor = new RequestExpectContinue(); - interceptor.process(request, context); + interceptor.process(request, null, context); Assert.assertEquals(0, request.getAllHeaders().length); } diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestResponseContentEncoding.java b/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestResponseContentEncoding.java index 89b6a4025..a3ca764ba 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestResponseContentEncoding.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestResponseContentEncoding.java @@ -29,40 +29,41 @@ package org.apache.hc.client5.http.protocol; import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.entity.DecompressingEntity; import org.apache.hc.client5.http.entity.GzipDecompressingEntity; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.HttpException; -import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.HttpResponseInterceptor; -import org.apache.hc.core5.http.HttpVersion; -import org.apache.hc.core5.http.entity.StringEntity; -import org.apache.hc.core5.http.message.BasicHttpResponse; +import org.apache.hc.core5.http.io.entity.StringEntity; +import org.apache.hc.core5.http.message.BasicClassicHttpResponse; import org.apache.hc.core5.http.protocol.BasicHttpContext; import org.apache.hc.core5.http.protocol.HttpContext; import org.junit.Assert; +import org.junit.Ignore; import org.junit.Test; +@Ignore public class TestResponseContentEncoding { @Test public void testContentEncodingNoEntity() throws Exception { - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK"); final HttpContext context = new BasicHttpContext(); final HttpResponseInterceptor interceptor = new ResponseContentEncoding(); - interceptor.process(response, context); + interceptor.process(response, response.getEntity(), context); final HttpEntity entity = response.getEntity(); Assert.assertNull(entity); } @Test public void testNoContentEncoding() throws Exception { - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK"); final StringEntity original = new StringEntity("plain stuff"); response.setEntity(original); final HttpContext context = new BasicHttpContext(); final HttpResponseInterceptor interceptor = new ResponseContentEncoding(); - interceptor.process(response, context); + interceptor.process(response, response.getEntity(), context); final HttpEntity entity = response.getEntity(); Assert.assertNotNull(entity); Assert.assertTrue(entity instanceof StringEntity); @@ -70,14 +71,14 @@ public class TestResponseContentEncoding { @Test public void testGzipContentEncoding() throws Exception { - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK"); final StringEntity original = new StringEntity("encoded stuff"); original.setContentEncoding("GZip"); response.setEntity(original); final HttpContext context = new BasicHttpContext(); final HttpResponseInterceptor interceptor = new ResponseContentEncoding(); - interceptor.process(response, context); + interceptor.process(response, response.getEntity(), context); final HttpEntity entity = response.getEntity(); Assert.assertNotNull(entity); Assert.assertTrue(entity instanceof DecompressingEntity); @@ -85,14 +86,14 @@ public class TestResponseContentEncoding { @Test public void testGzipContentEncodingZeroLength() throws Exception { - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK"); final StringEntity original = new StringEntity(""); original.setContentEncoding("GZip"); response.setEntity(original); final HttpContext context = new BasicHttpContext(); final HttpResponseInterceptor interceptor = new ResponseContentEncoding(); - interceptor.process(response, context); + interceptor.process(response, response.getEntity(), context); final HttpEntity entity = response.getEntity(); Assert.assertNotNull(entity); Assert.assertTrue(entity instanceof StringEntity); @@ -100,14 +101,14 @@ public class TestResponseContentEncoding { @Test public void testXGzipContentEncoding() throws Exception { - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK"); final StringEntity original = new StringEntity("encoded stuff"); original.setContentEncoding("x-gzip"); response.setEntity(original); final HttpContext context = new BasicHttpContext(); final HttpResponseInterceptor interceptor = new ResponseContentEncoding(); - interceptor.process(response, context); + interceptor.process(response, response.getEntity(), context); final HttpEntity entity = response.getEntity(); Assert.assertNotNull(entity); Assert.assertTrue(entity instanceof DecompressingEntity); @@ -115,14 +116,14 @@ public class TestResponseContentEncoding { @Test public void testDeflateContentEncoding() throws Exception { - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK"); final StringEntity original = new StringEntity("encoded stuff"); original.setContentEncoding("deFlaTe"); response.setEntity(original); final HttpContext context = new BasicHttpContext(); final HttpResponseInterceptor interceptor = new ResponseContentEncoding(); - interceptor.process(response, context); + interceptor.process(response, response.getEntity(), context); final HttpEntity entity = response.getEntity(); Assert.assertNotNull(entity); Assert.assertTrue(entity instanceof DecompressingEntity); @@ -130,14 +131,14 @@ public class TestResponseContentEncoding { @Test public void testIdentityContentEncoding() throws Exception { - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK"); final StringEntity original = new StringEntity("encoded stuff"); original.setContentEncoding("identity"); response.setEntity(original); final HttpContext context = new BasicHttpContext(); final HttpResponseInterceptor interceptor = new ResponseContentEncoding(); - interceptor.process(response, context); + interceptor.process(response, response.getEntity(), context); final HttpEntity entity = response.getEntity(); Assert.assertNotNull(entity); Assert.assertTrue(entity instanceof StringEntity); @@ -145,19 +146,19 @@ public class TestResponseContentEncoding { @Test(expected=HttpException.class) public void testUnknownContentEncoding() throws Exception { - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK"); final StringEntity original = new StringEntity("encoded stuff"); original.setContentEncoding("whatever"); response.setEntity(original); final HttpContext context = new BasicHttpContext(); final HttpResponseInterceptor interceptor = new ResponseContentEncoding(false); - interceptor.process(response, context); + interceptor.process(response, response.getEntity(), context); } @Test public void testContentEncodingRequestParameter() throws Exception { - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK"); final StringEntity original = new StringEntity("encoded stuff"); original.setContentEncoding("GZip"); response.setEntity(original); @@ -170,7 +171,7 @@ public class TestResponseContentEncoding { context.setAttribute(HttpClientContext.REQUEST_CONFIG, config); final HttpResponseInterceptor interceptor = new ResponseContentEncoding(); - interceptor.process(response, context); + interceptor.process(response, response.getEntity(), context); final HttpEntity entity = response.getEntity(); Assert.assertNotNull(entity); Assert.assertFalse(entity instanceof GzipDecompressingEntity); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestResponseProcessCookies.java b/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestResponseProcessCookies.java index 8a3ea6bef..ed4daa521 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestResponseProcessCookies.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/protocol/TestResponseProcessCookies.java @@ -36,7 +36,6 @@ import org.apache.hc.client5.http.cookie.CookieStore; import org.apache.hc.client5.http.impl.cookie.RFC6265LaxSpec; import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.HttpResponseInterceptor; -import org.apache.hc.core5.http.HttpVersion; import org.apache.hc.core5.http.message.BasicHttpResponse; import org.junit.Assert; import org.junit.Before; @@ -59,19 +58,19 @@ public class TestResponseProcessCookies { public void testResponseParameterCheck() throws Exception { final HttpClientContext context = HttpClientContext.create(); final HttpResponseInterceptor interceptor = new ResponseProcessCookies(); - interceptor.process(null, context); + interceptor.process(null, null, context); } @Test(expected=IllegalArgumentException.class) public void testContextParameterCheck() throws Exception { - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final HttpResponse response = new BasicHttpResponse(200, "OK"); final HttpResponseInterceptor interceptor = new ResponseProcessCookies(); - interceptor.process(response, null); + interceptor.process(response, null, null); } @Test public void testParseCookies() throws Exception { - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final HttpResponse response = new BasicHttpResponse(200, "OK"); response.addHeader("Set-Cookie", "name1=value1"); final HttpClientContext context = HttpClientContext.create(); @@ -80,7 +79,7 @@ public class TestResponseProcessCookies { context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore); final HttpResponseInterceptor interceptor = new ResponseProcessCookies(); - interceptor.process(response, context); + interceptor.process(response, null, context); final List cookies = this.cookieStore.getCookies(); Assert.assertNotNull(cookies); @@ -94,7 +93,7 @@ public class TestResponseProcessCookies { @Test public void testNoCookieOrigin() throws Exception { - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final HttpResponse response = new BasicHttpResponse(200, "OK"); response.addHeader("Set-Cookie", "name1=value1"); final HttpClientContext context = HttpClientContext.create(); @@ -103,7 +102,7 @@ public class TestResponseProcessCookies { context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore); final HttpResponseInterceptor interceptor = new ResponseProcessCookies(); - interceptor.process(response, context); + interceptor.process(response, null, context); final List cookies = this.cookieStore.getCookies(); Assert.assertNotNull(cookies); @@ -112,7 +111,7 @@ public class TestResponseProcessCookies { @Test public void testNoCookieSpec() throws Exception { - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final HttpResponse response = new BasicHttpResponse(200, "OK"); response.addHeader("Set-Cookie", "name1=value1"); final HttpClientContext context = HttpClientContext.create(); @@ -121,7 +120,7 @@ public class TestResponseProcessCookies { context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore); final HttpResponseInterceptor interceptor = new ResponseProcessCookies(); - interceptor.process(response, context); + interceptor.process(response, null, context); final List cookies = this.cookieStore.getCookies(); Assert.assertNotNull(cookies); @@ -130,7 +129,7 @@ public class TestResponseProcessCookies { @Test public void testNoCookieStore() throws Exception { - final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); + final HttpResponse response = new BasicHttpResponse(200, "OK"); response.addHeader("Set-Cookie", "name1=value1"); final HttpClientContext context = HttpClientContext.create(); @@ -139,7 +138,7 @@ public class TestResponseProcessCookies { context.setAttribute(HttpClientContext.COOKIE_STORE, null); final HttpResponseInterceptor interceptor = new ResponseProcessCookies(); - interceptor.process(response, context); + interceptor.process(response, null, context); final List cookies = this.cookieStore.getCookies(); Assert.assertNotNull(cookies); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/ssl/TestSSLSocketFactory.java b/httpclient5/src/test/java/org/apache/hc/client5/http/ssl/TestSSLSocketFactory.java index 62e23723d..a87727a09 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/ssl/TestSSLSocketFactory.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/ssl/TestSSLSocketFactory.java @@ -41,12 +41,11 @@ import javax.net.ssl.SSLServerSocket; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocket; -import org.apache.hc.client5.http.localserver.LocalServerTestBase; import org.apache.hc.client5.http.localserver.SSLTestContexts; import org.apache.hc.core5.http.HttpHost; -import org.apache.hc.core5.http.bootstrap.io.HttpServer; -import org.apache.hc.core5.http.bootstrap.io.SSLServerSetupHandler; -import org.apache.hc.core5.http.bootstrap.io.ServerBootstrap; +import org.apache.hc.core5.http.impl.io.bootstrap.HttpServer; +import org.apache.hc.core5.http.impl.io.bootstrap.SSLServerSetupHandler; +import org.apache.hc.core5.http.impl.io.bootstrap.ServerBootstrap; import org.apache.hc.core5.http.protocol.BasicHttpContext; import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.ssl.SSLContexts; @@ -88,7 +87,6 @@ public class TestSSLSocketFactory { @Test public void testBasicSSL() throws Exception { this.server = ServerBootstrap.bootstrap() - .setServerInfo(LocalServerTestBase.ORIGIN) .setSslContext(SSLTestContexts.createServerSSLContext()) .create(); this.server.start(); @@ -111,7 +109,6 @@ public class TestSSLSocketFactory { @Test public void testBasicDefaultHostnameVerifier() throws Exception { this.server = ServerBootstrap.bootstrap() - .setServerInfo(LocalServerTestBase.ORIGIN) .setSslContext(SSLTestContexts.createServerSSLContext()) .create(); this.server.start(); @@ -132,7 +129,6 @@ public class TestSSLSocketFactory { @Test public void testClientAuthSSL() throws Exception { this.server = ServerBootstrap.bootstrap() - .setServerInfo(LocalServerTestBase.ORIGIN) .setSslContext(SSLTestContexts.createServerSSLContext()) .create(); this.server.start(); @@ -155,7 +151,6 @@ public class TestSSLSocketFactory { @Test(expected=IOException.class) public void testClientAuthSSLFailure() throws Exception { this.server = ServerBootstrap.bootstrap() - .setServerInfo(LocalServerTestBase.ORIGIN) .setSslContext(SSLTestContexts.createServerSSLContext()) .setSslSetupHandler(new SSLServerSetupHandler() { @@ -186,7 +181,6 @@ public class TestSSLSocketFactory { @Test(expected=SSLException.class) public void testSSLTrustVerification() throws Exception { this.server = ServerBootstrap.bootstrap() - .setServerInfo(LocalServerTestBase.ORIGIN) .setSslContext(SSLTestContexts.createServerSSLContext()) .create(); this.server.start(); @@ -208,7 +202,6 @@ public class TestSSLSocketFactory { @Test public void testSSLTrustVerificationOverride() throws Exception { this.server = ServerBootstrap.bootstrap() - .setServerInfo(LocalServerTestBase.ORIGIN) .setSslContext(SSLTestContexts.createServerSSLContext()) .create(); this.server.start(); @@ -241,7 +234,6 @@ public class TestSSLSocketFactory { @Test public void testTLSOnly() throws Exception { this.server = ServerBootstrap.bootstrap() - .setServerInfo(LocalServerTestBase.ORIGIN) .setSslContext(SSLTestContexts.createServerSSLContext()) .setSslSetupHandler(new SSLServerSetupHandler() { @@ -268,7 +260,6 @@ public class TestSSLSocketFactory { @Test(expected=IOException.class) public void testSSLDisabledByDefault() throws Exception { this.server = ServerBootstrap.bootstrap() - .setServerInfo(LocalServerTestBase.ORIGIN) .setSslContext(SSLTestContexts.createServerSSLContext()) .setSslSetupHandler(new SSLServerSetupHandler() { diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/utils/TestInetAddressUtils.java b/httpclient5/src/test/java/org/apache/hc/client5/http/utils/TestInetAddressUtils.java deleted file mode 100644 index 84f8b1c95..000000000 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/utils/TestInetAddressUtils.java +++ /dev/null @@ -1,100 +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 - * . - * - */ - -package org.apache.hc.client5.http.utils; - -import org.junit.Assert; -import org.junit.Test; - -/** - * Unit tests for InetAddressUtils. - */ -public class TestInetAddressUtils { - - @Test - public void testValidIPv4Address() { - Assert.assertTrue(InetAddressUtils.isIPv4Address("127.0.0.1")); - Assert.assertTrue(InetAddressUtils.isIPv4Address("192.168.0.0")); - Assert.assertTrue(InetAddressUtils.isIPv4Address("255.255.255.255")); - } - - @Test - public void testInvalidIPv4Address() { - Assert.assertFalse(InetAddressUtils.isIPv4Address(" 127.0.0.1 ")); // Blanks not allowed - Assert.assertFalse(InetAddressUtils.isIPv4Address("g.ar.ba.ge")); - Assert.assertFalse(InetAddressUtils.isIPv4Address("192.168.0")); - Assert.assertFalse(InetAddressUtils.isIPv4Address("256.255.255.255")); - Assert.assertFalse(InetAddressUtils.isIPv4Address("0.168.0.0")); //IP address that starts with zero not allowed - } - - @Test - public void testValidIPv6Address() { - Assert.assertTrue(InetAddressUtils.isIPv6StdAddress("2001:0db8:0000:0000:0000:0000:1428:57ab")); - Assert.assertTrue(InetAddressUtils.isIPv6StdAddress("2001:db8:0:0:0:0:1428:57ab")); - Assert.assertTrue(InetAddressUtils.isIPv6StdAddress("0:0:0:0:0:0:0:0")); - Assert.assertTrue(InetAddressUtils.isIPv6StdAddress("0:0:0:0:0:0:0:1")); - Assert.assertTrue(InetAddressUtils.isIPv6HexCompressedAddress("2001:0db8:0:0::1428:57ab")); - Assert.assertTrue(InetAddressUtils.isIPv6HexCompressedAddress("2001:0db8::1428:57ab")); - Assert.assertTrue(InetAddressUtils.isIPv6HexCompressedAddress("2001:db8::1428:57ab")); - Assert.assertTrue(InetAddressUtils.isIPv6HexCompressedAddress("::1")); - Assert.assertTrue(InetAddressUtils.isIPv6HexCompressedAddress("::")); // http://tools.ietf.org/html/rfc4291#section-2.2 - } - - @Test - public void testInvalidIPv6Address() { - Assert.assertFalse(InetAddressUtils.isIPv6Address("2001:0db8:0000:garb:age0:0000:1428:57ab")); - Assert.assertFalse(InetAddressUtils.isIPv6Address("2001:0gb8:0000:0000:0000:0000:1428:57ab")); - Assert.assertFalse(InetAddressUtils.isIPv6StdAddress("0:0:0:0:0:0:0:0:0")); // Too many - Assert.assertFalse(InetAddressUtils.isIPv6StdAddress("0:0:0:0:0:0:0")); // Too few - Assert.assertFalse(InetAddressUtils.isIPv6HexCompressedAddress(":1")); - Assert.assertFalse(InetAddressUtils.isIPv6Address("2001:0db8::0000::57ab")); // Cannot have two contractions - Assert.assertFalse(InetAddressUtils.isIPv6HexCompressedAddress("1:2:3:4:5:6:7::9")); // too many fields before :: - Assert.assertFalse(InetAddressUtils.isIPv6HexCompressedAddress("1::3:4:5:6:7:8:9")); // too many fields after :: - Assert.assertFalse(InetAddressUtils.isIPv6HexCompressedAddress("::3:4:5:6:7:8:9")); // too many fields after :: - Assert.assertFalse(InetAddressUtils.isIPv6Address("")); // empty - } - - @Test - // Test HTTPCLIENT-1319 - public void testInvalidIPv6AddressIncorrectGroupCount() { - Assert.assertFalse(InetAddressUtils.isIPv6HexCompressedAddress("1:2::4:5:6:7:8:9")); // too many fields in total - Assert.assertFalse(InetAddressUtils.isIPv6HexCompressedAddress("1:2:3:4:5:6::8:9")); // too many fields in total - } - - @Test - public void testValidIPv4MappedIPv6Address() { - Assert.assertTrue(InetAddressUtils.isIPv4MappedIPv64Address("::FFFF:1.2.3.4")); - Assert.assertTrue(InetAddressUtils.isIPv4MappedIPv64Address("::ffff:255.255.255.255")); - } - - @Test - public void testInValidIPv4MappedIPv6Address() { - Assert.assertFalse(InetAddressUtils.isIPv4MappedIPv64Address("2001:0db8:0000:0000:0000:0000:1428:57ab")); - Assert.assertFalse(InetAddressUtils.isIPv4MappedIPv64Address("::ffff:1:2:3:4")); - } - -} diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/utils/TestRequestBuilder.java b/httpclient5/src/test/java/org/apache/hc/client5/http/utils/TestRequestBuilder.java index 26edc0ee1..e244d45f2 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/utils/TestRequestBuilder.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/utils/TestRequestBuilder.java @@ -61,7 +61,7 @@ public class TestRequestBuilder { final String uriExpected = String.format("https://somehost.com/stuff?parameter1=value1¶meter2=%s¶meter3=%s", encodedData1, encodedData2); final HttpUriRequest request = requestBuilder.build(); - Assert.assertEquals(uriExpected, request.getURI().toString()); + Assert.assertEquals(uriExpected, request.getUri().toString()); } private NameValuePair[] createParameters() { diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/utils/TestURIBuilder.java b/httpclient5/src/test/java/org/apache/hc/client5/http/utils/TestURIBuilder.java deleted file mode 100644 index cf67f760e..000000000 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/utils/TestURIBuilder.java +++ /dev/null @@ -1,295 +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 - * . - * - */ -package org.apache.hc.client5.http.utils; - -import java.net.URI; -import java.net.URLEncoder; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; - -import org.apache.hc.core5.http.NameValuePair; -import org.apache.hc.core5.http.message.BasicNameValuePair; -import org.junit.Assert; -import org.junit.Test; - -public class TestURIBuilder { - - @Test - public void testHierarchicalUri() throws Exception { - final URI uri = new URI("http", "stuff", "localhost", 80, "/some stuff", "param=stuff", "fragment"); - final URIBuilder uribuilder = new URIBuilder(uri); - final URI result = uribuilder.build(); - Assert.assertEquals(new URI("http://stuff@localhost:80/some%20stuff?param=stuff#fragment"), result); - } - - @Test - public void testMutationToRelativeUri() throws Exception { - final URI uri = new URI("http://stuff@localhost:80/stuff?param=stuff#fragment"); - final URIBuilder uribuilder = new URIBuilder(uri).setHost(null); - final URI result = uribuilder.build(); - Assert.assertEquals(new URI("http:///stuff?param=stuff#fragment"), result); - } - - @Test - public void testMutationRemoveFragment() throws Exception { - final URI uri = new URI("http://stuff@localhost:80/stuff?param=stuff#fragment"); - final URI result = new URIBuilder(uri).setFragment(null).build(); - Assert.assertEquals(new URI("http://stuff@localhost:80/stuff?param=stuff"), result); - } - - @Test - public void testMutationRemoveUserInfo() throws Exception { - final URI uri = new URI("http://stuff@localhost:80/stuff?param=stuff#fragment"); - final URI result = new URIBuilder(uri).setUserInfo(null).build(); - Assert.assertEquals(new URI("http://localhost:80/stuff?param=stuff#fragment"), result); - } - - @Test - public void testMutationRemovePort() throws Exception { - final URI uri = new URI("http://stuff@localhost:80/stuff?param=stuff#fragment"); - final URI result = new URIBuilder(uri).setPort(-1).build(); - Assert.assertEquals(new URI("http://stuff@localhost/stuff?param=stuff#fragment"), result); - } - - @Test - public void testOpaqueUri() throws Exception { - final URI uri = new URI("stuff", "some-stuff", "fragment"); - final URIBuilder uribuilder = new URIBuilder(uri); - final URI result = uribuilder.build(); - Assert.assertEquals(uri, result); - } - - @Test - public void testOpaqueUriMutation() throws Exception { - final URI uri = new URI("stuff", "some-stuff", "fragment"); - final URIBuilder uribuilder = new URIBuilder(uri).setCustomQuery("param1¶m2=stuff").setFragment(null); - Assert.assertEquals(new URI("stuff:?param1¶m2=stuff"), uribuilder.build()); - } - - @Test - public void testHierarchicalUriMutation() throws Exception { - final URIBuilder uribuilder = new URIBuilder("/").setScheme("http").setHost("localhost").setPort(80).setPath("/stuff"); - Assert.assertEquals(new URI("http://localhost:80/stuff"), uribuilder.build()); - } - - @Test - public void testEmpty() throws Exception { - final URIBuilder uribuilder = new URIBuilder(); - final URI result = uribuilder.build(); - Assert.assertEquals(new URI(""), result); - } - - @Test - public void testSetUserInfo() throws Exception { - final URI uri = new URI("http", null, "localhost", 80, "/", "param=stuff", null); - final URIBuilder uribuilder = new URIBuilder(uri).setUserInfo("user", "password"); - final URI result = uribuilder.build(); - Assert.assertEquals(new URI("http://user:password@localhost:80/?param=stuff"), result); - } - - @Test - public void testRemoveParameters() throws Exception { - final URI uri = new URI("http", null, "localhost", 80, "/", "param=stuff", null); - final URIBuilder uribuilder = new URIBuilder(uri).removeQuery(); - final URI result = uribuilder.build(); - Assert.assertEquals(new URI("http://localhost:80/"), result); - } - - @Test - public void testSetParameter() throws Exception { - final URI uri = new URI("http", null, "localhost", 80, "/", "param=stuff&blah&blah", null); - final URIBuilder uribuilder = new URIBuilder(uri).setParameter("param", "some other stuff") - .setParameter("blah", "blah"); - final URI result = uribuilder.build(); - Assert.assertEquals(new URI("http://localhost:80/?param=some+other+stuff&blah=blah"), result); - } - - @Test - public void testParameterWithSpecialChar() throws Exception { - final URI uri = new URI("http", null, "localhost", 80, "/", "param=stuff", null); - final URIBuilder uribuilder = new URIBuilder(uri).addParameter("param", "1 + 1 = 2") - .addParameter("param", "blah&blah"); - final URI result = uribuilder.build(); - Assert.assertEquals(new URI("http://localhost:80/?param=stuff¶m=1+%2B+1+%3D+2&" + - "param=blah%26blah"), result); - } - - @Test - public void testAddParameter() throws Exception { - final URI uri = new URI("http", null, "localhost", 80, "/", "param=stuff&blah&blah", null); - final URIBuilder uribuilder = new URIBuilder(uri).addParameter("param", "some other stuff") - .addParameter("blah", "blah"); - final URI result = uribuilder.build(); - Assert.assertEquals(new URI("http://localhost:80/?param=stuff&blah&blah&" + - "param=some+other+stuff&blah=blah"), result); - } - - @Test - public void testQueryEncoding() throws Exception { - final URI uri1 = new URI("https://somehost.com/stuff?client_id=1234567890" + - "&redirect_uri=https%3A%2F%2Fsomehost.com%2Fblah+blah%2F"); - final URI uri2 = new URIBuilder("https://somehost.com/stuff") - .addParameter("client_id","1234567890") - .addParameter("redirect_uri","https://somehost.com/blah blah/").build(); - Assert.assertEquals(uri1, uri2); - } - - @Test - public void testQueryAndParameterEncoding() throws Exception { - final URI uri1 = new URI("https://somehost.com/stuff?param1=12345¶m2=67890"); - final URI uri2 = new URIBuilder("https://somehost.com/stuff") - .setCustomQuery("this&that") - .addParameter("param1","12345") - .addParameter("param2","67890").build(); - Assert.assertEquals(uri1, uri2); - } - - @Test - public void testPathEncoding() throws Exception { - final URI uri1 = new URI("https://somehost.com/some%20path%20with%20blanks/"); - final URI uri2 = new URIBuilder() - .setScheme("https") - .setHost("somehost.com") - .setPath("/some path with blanks/") - .build(); - Assert.assertEquals(uri1, uri2); - } - - @Test - public void testAgainstURI() throws Exception { - // Check that the URI generated by URI builder agrees with that generated by using URI directly - final String scheme="https"; - final String host="localhost"; - final String specials="/abcd!$&*()_-+.,=:;'~@[]?<>|#^%\"{}\\\u00a3`\u00ac\u00a6xyz"; // N.B. excludes space - final URI uri = new URI(scheme, specials, host, 80, specials, specials, specials); - - final URI bld = new URIBuilder() - .setScheme(scheme) - .setHost(host) - .setUserInfo(specials) - .setPath(specials) - .setCustomQuery(specials) - .setFragment(specials) - .build(); - - Assert.assertEquals(uri.getHost(), bld.getHost()); - - Assert.assertEquals(uri.getUserInfo(), bld.getUserInfo()); - - Assert.assertEquals(uri.getPath(), bld.getPath()); - - Assert.assertEquals(uri.getQuery(), bld.getQuery()); - - Assert.assertEquals(uri.getFragment(), bld.getFragment()); - - } - - @Test - public void testAgainstURIEncoded() throws Exception { - // Check that the encoded URI generated by URI builder agrees with that generated by using URI directly - final String scheme="https"; - final String host="localhost"; - final String specials="/ abcd!$&*()_-+.,=:;'~<>/@[]|#^%\"{}\\`xyz"; // N.B. excludes \u00a3\u00ac\u00a6 - final URI uri = new URI(scheme, specials, host, 80, specials, specials, specials); - - final URI bld = new URIBuilder() - .setScheme(scheme) - .setHost(host) - .setUserInfo(specials) - .setPath(specials) - .setCustomQuery(specials) - .setFragment(specials) - .build(); - - Assert.assertEquals(uri.getHost(), bld.getHost()); - - Assert.assertEquals(uri.getRawUserInfo(), bld.getRawUserInfo()); - - Assert.assertEquals(uri.getRawPath(), bld.getRawPath()); - - Assert.assertEquals(uri.getRawQuery(), bld.getRawQuery()); - - Assert.assertEquals(uri.getRawFragment(), bld.getRawFragment()); - - } - - @Test - public void testBuildAddParametersUTF8() throws Exception { - assertAddParameters(StandardCharsets.UTF_8); - } - - @Test - public void testBuildAddParametersISO88591() throws Exception { - assertAddParameters(StandardCharsets.ISO_8859_1); - } - - public void assertAddParameters(final Charset charset) throws Exception { - final URI uri = new URIBuilder("https://somehost.com/stuff") - .setCharset(charset) - .addParameters(createParameters()).build(); - - assertBuild(charset, uri); - } - - @Test - public void testBuildSetParametersUTF8() throws Exception { - assertSetParameters(StandardCharsets.UTF_8); - } - - @Test - public void testBuildSetParametersISO88591() throws Exception { - assertSetParameters(StandardCharsets.ISO_8859_1); - } - - public void assertSetParameters(final Charset charset) throws Exception { - final URI uri = new URIBuilder("https://somehost.com/stuff") - .setCharset(charset) - .setParameters(createParameters()).build(); - - assertBuild(charset, uri); - } - - public void assertBuild(final Charset charset, final URI uri) throws Exception { - final String encodedData1 = URLEncoder.encode("\"1\u00aa position\"", charset.displayName()); - final String encodedData2 = URLEncoder.encode("Jos\u00e9 Abra\u00e3o", charset.displayName()); - - final String uriExpected = String.format("https://somehost.com/stuff?parameter1=value1¶meter2=%s¶meter3=%s", encodedData1, encodedData2); - - Assert.assertEquals(uriExpected, uri.toString()); - } - - private List createParameters() { - final List parameters = new ArrayList<>(); - parameters.add(new BasicNameValuePair("parameter1", "value1")); - parameters.add(new BasicNameValuePair("parameter2", "\"1\u00aa position\"")); - parameters.add(new BasicNameValuePair("parameter3", "Jos\u00e9 Abra\u00e3o")); - return parameters; - } - -} diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/utils/TestURIUtils.java b/httpclient5/src/test/java/org/apache/hc/client5/http/utils/TestURIUtils.java index 0f90f4093..ec7daa4fe 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/utils/TestURIUtils.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/utils/TestURIUtils.java @@ -29,8 +29,8 @@ package org.apache.hc.client5.http.utils; import java.net.URI; import java.util.Arrays; -import org.apache.hc.client5.http.HttpRoute; import org.apache.hc.core5.http.HttpHost; +import org.apache.hc.core5.net.URIBuilder; import org.junit.Assert; import org.junit.Test; @@ -101,34 +101,6 @@ public class TestURIUtils { URI.create("http://thishost:80/stuff#crap"), target, true).toString()); } - @Test - public void testRewriteForRoute() throws Exception { - - final HttpHost target1 = new HttpHost("foo", 80); - final HttpHost target2 = new HttpHost("foo", 443, "https"); - final HttpHost proxy = new HttpHost("bar", 8888); - - // Direct route - Assert.assertEquals(new URI("/test"), URIUtils - .rewriteURIForRoute(new URI("http://foo/test"), new HttpRoute(target1))); - - // Direct route - Assert.assertEquals(new URI("/"), URIUtils - .rewriteURIForRoute(new URI(""), new HttpRoute(target1))); - - // Via proxy - Assert.assertEquals(new URI("http://foo/test"), URIUtils - .rewriteURIForRoute(new URI("http://foo/test"), new HttpRoute(target1, proxy))); - - // Via proxy - Assert.assertEquals(new URI("http://foo:80/test"), URIUtils - .rewriteURIForRoute(new URI("/test"), new HttpRoute(target1, proxy))); - - // Via proxy tunnel - Assert.assertEquals(new URI("/test"), URIUtils - .rewriteURIForRoute(new URI("https://foo:443/test"), new HttpRoute(target2, null, proxy, true))); - } - @Test public void testNormalization() { Assert.assertEquals("example://a/b/c/%7Bfoo%7D", URIUtils.resolve(this.baseURI, "eXAMPLE://a/./b/../b/%63/%7bfoo%7d").toString()); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/utils/TestURLEncodedUtils.java b/httpclient5/src/test/java/org/apache/hc/client5/http/utils/TestURLEncodedUtils.java deleted file mode 100644 index 08dba3ce1..000000000 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/utils/TestURLEncodedUtils.java +++ /dev/null @@ -1,412 +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 - * . - * - */ - -package org.apache.hc.client5.http.utils; - -import java.net.URI; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; - -import org.apache.hc.core5.http.NameValuePair; -import org.apache.hc.core5.http.entity.ContentType; -import org.apache.hc.core5.http.entity.StringEntity; -import org.apache.hc.core5.http.message.BasicNameValuePair; -import org.junit.Assert; -import org.junit.Test; - -public class TestURLEncodedUtils { - - @Test - public void testParseURLCodedContent() throws Exception { - List result; - - result = parse(""); - Assert.assertTrue(result.isEmpty()); - - result = parse("Name0"); - Assert.assertEquals(1, result.size()); - assertNameValuePair(result.get(0), "Name0", null); - - result = parse("Name1=Value1"); - Assert.assertEquals(1, result.size()); - assertNameValuePair(result.get(0), "Name1", "Value1"); - - result = parse("Name2="); - Assert.assertEquals(1, result.size()); - assertNameValuePair(result.get(0), "Name2", ""); - - result = parse("Name3"); - Assert.assertEquals(1, result.size()); - assertNameValuePair(result.get(0), "Name3", null); - - result = parse("Name4=Value%204%21"); - Assert.assertEquals(1, result.size()); - assertNameValuePair(result.get(0), "Name4", "Value 4!"); - - result = parse("Name4=Value%2B4%21"); - Assert.assertEquals(1, result.size()); - assertNameValuePair(result.get(0), "Name4", "Value+4!"); - - result = parse("Name4=Value%204%21%20%214"); - Assert.assertEquals(1, result.size()); - assertNameValuePair(result.get(0), "Name4", "Value 4! !4"); - - result = parse("Name5=aaa&Name6=bbb"); - Assert.assertEquals(2, result.size()); - assertNameValuePair(result.get(0), "Name5", "aaa"); - assertNameValuePair(result.get(1), "Name6", "bbb"); - - result = parse("Name7=aaa&Name7=b%2Cb&Name7=ccc"); - Assert.assertEquals(3, result.size()); - assertNameValuePair(result.get(0), "Name7", "aaa"); - assertNameValuePair(result.get(1), "Name7", "b,b"); - assertNameValuePair(result.get(2), "Name7", "ccc"); - - result = parse("Name8=xx%2C%20%20yy%20%20%2Czz"); - Assert.assertEquals(1, result.size()); - assertNameValuePair(result.get(0), "Name8", "xx, yy ,zz"); - - result = parse("price=10%20%E2%82%AC"); - Assert.assertEquals(1, result.size()); - assertNameValuePair(result.get(0), "price", "10 \u20AC"); - } - - @Test - public void testParseURLCodedContentString() throws Exception { - List result; - - result = parseString(""); - Assert.assertTrue(result.isEmpty()); - - result = parseString("Name0"); - Assert.assertEquals(1, result.size()); - assertNameValuePair(result.get(0), "Name0", null); - - result = parseString("Name1=Value1"); - Assert.assertEquals(1, result.size()); - assertNameValuePair(result.get(0), "Name1", "Value1"); - - result = parseString("Name2="); - Assert.assertEquals(1, result.size()); - assertNameValuePair(result.get(0), "Name2", ""); - - result = parseString("Name3"); - Assert.assertEquals(1, result.size()); - assertNameValuePair(result.get(0), "Name3", null); - - result = parseString("Name4=Value%204%21"); - Assert.assertEquals(1, result.size()); - assertNameValuePair(result.get(0), "Name4", "Value 4!"); - - result = parseString("Name4=Value%2B4%21"); - Assert.assertEquals(1, result.size()); - assertNameValuePair(result.get(0), "Name4", "Value+4!"); - - result = parseString("Name4=Value%204%21%20%214"); - Assert.assertEquals(1, result.size()); - assertNameValuePair(result.get(0), "Name4", "Value 4! !4"); - - result = parseString("Name5=aaa&Name6=bbb"); - Assert.assertEquals(2, result.size()); - assertNameValuePair(result.get(0), "Name5", "aaa"); - assertNameValuePair(result.get(1), "Name6", "bbb"); - - result = parseString("Name7=aaa&Name7=b%2Cb&Name7=ccc"); - Assert.assertEquals(3, result.size()); - assertNameValuePair(result.get(0), "Name7", "aaa"); - assertNameValuePair(result.get(1), "Name7", "b,b"); - assertNameValuePair(result.get(2), "Name7", "ccc"); - - result = parseString("Name8=xx%2C%20%20yy%20%20%2Czz"); - Assert.assertEquals(1, result.size()); - assertNameValuePair(result.get(0), "Name8", "xx, yy ,zz"); - - result = parseString("price=10%20%E2%82%AC"); - Assert.assertEquals(1, result.size()); - assertNameValuePair(result.get(0), "price", "10 \u20AC"); - } - - @Test - public void testParseInvalidURLCodedContent() throws Exception { - List result; - - result = parse("name=%"); - Assert.assertEquals(1, result.size()); - assertNameValuePair(result.get(0), "name", "%"); - - result = parse("name=%a"); - Assert.assertEquals(1, result.size()); - assertNameValuePair(result.get(0), "name", "%a"); - - result = parse("name=%wa%20"); - Assert.assertEquals(1, result.size()); - assertNameValuePair(result.get(0), "name", "%wa "); - } - - @Test - public void testParseEntity() throws Exception { - final StringEntity entity = new StringEntity("Name1=Value1"); - - entity.setContentType(URLEncodedUtils.CONTENT_TYPE); - final List result = URLEncodedUtils.parse(entity); - Assert.assertEquals(1, result.size()); - assertNameValuePair(result.get(0), "Name1", "Value1"); - - entity.setContentType("text/test"); - Assert.assertTrue(URLEncodedUtils.parse(entity).isEmpty()); - } - - private static final int SWISS_GERMAN_HELLO [] = { - 0x47, 0x72, 0xFC, 0x65, 0x7A, 0x69, 0x5F, 0x7A, 0xE4, 0x6D, 0xE4 - }; - - private static final int RUSSIAN_HELLO [] = { - 0x412, 0x441, 0x435, 0x43C, 0x5F, 0x43F, 0x440, 0x438, - 0x432, 0x435, 0x442 - }; - - private static String constructString(final int [] unicodeChars) { - final StringBuilder buffer = new StringBuilder(); - if (unicodeChars != null) { - for (final int unicodeChar : unicodeChars) { - buffer.append((char)unicodeChar); - } - } - return buffer.toString(); - } - - @Test - public void testParseUTF8Entity() throws Exception { - final String ru_hello = constructString(RUSSIAN_HELLO); - final String ch_hello = constructString(SWISS_GERMAN_HELLO); - final List parameters = new ArrayList<>(); - parameters.add(new BasicNameValuePair("russian", ru_hello)); - parameters.add(new BasicNameValuePair("swiss", ch_hello)); - - final String s = URLEncodedUtils.format(parameters, StandardCharsets.UTF_8); - - Assert.assertEquals("russian=%D0%92%D1%81%D0%B5%D0%BC_%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82" + - "&swiss=Gr%C3%BCezi_z%C3%A4m%C3%A4", s); - - final StringEntity entity = new StringEntity(s, ContentType.create( - URLEncodedUtils.CONTENT_TYPE, StandardCharsets.UTF_8)); - final List result = URLEncodedUtils.parse(entity); - Assert.assertEquals(2, result.size()); - assertNameValuePair(result.get(0), "russian", ru_hello); - assertNameValuePair(result.get(1), "swiss", ch_hello); - } - - @Test - public void testParseUTF8Ampersand1String() throws Exception { - final String ru_hello = constructString(RUSSIAN_HELLO); - final String ch_hello = constructString(SWISS_GERMAN_HELLO); - final List parameters = new ArrayList<>(); - parameters.add(new BasicNameValuePair("russian", ru_hello)); - parameters.add(new BasicNameValuePair("swiss", ch_hello)); - - final String s = URLEncodedUtils.format(parameters, StandardCharsets.UTF_8); - - final List result = URLEncodedUtils.parse(s, StandardCharsets.UTF_8); - Assert.assertEquals(2, result.size()); - assertNameValuePair(result.get(0), "russian", ru_hello); - assertNameValuePair(result.get(1), "swiss", ch_hello); - } - - @Test - public void testParseUTF8Ampersand2String() throws Exception { - testParseUTF8String('&'); - } - - @Test - public void testParseUTF8SemicolonString() throws Exception { - testParseUTF8String(';'); - } - - private void testParseUTF8String(final char parameterSeparator) throws Exception { - final String ru_hello = constructString(RUSSIAN_HELLO); - final String ch_hello = constructString(SWISS_GERMAN_HELLO); - final List parameters = new ArrayList<>(); - parameters.add(new BasicNameValuePair("russian", ru_hello)); - parameters.add(new BasicNameValuePair("swiss", ch_hello)); - - final String s = URLEncodedUtils.format(parameters, parameterSeparator, StandardCharsets.UTF_8); - - final List result1 = URLEncodedUtils.parse(s, StandardCharsets.UTF_8); - Assert.assertEquals(2, result1.size()); - assertNameValuePair(result1.get(0), "russian", ru_hello); - assertNameValuePair(result1.get(1), "swiss", ch_hello); - - final List result2 = URLEncodedUtils.parse(s, StandardCharsets.UTF_8, parameterSeparator); - Assert.assertEquals(2, result2.size()); - assertNameValuePair(result2.get(0), "russian", ru_hello); - assertNameValuePair(result2.get(1), "swiss", ch_hello); - } - - @Test - public void testParseEntityDefaultContentType() throws Exception { - final String ch_hello = constructString(SWISS_GERMAN_HELLO); - final String us_hello = "hi there"; - final List parameters = new ArrayList<>(); - parameters.add(new BasicNameValuePair("english", us_hello)); - parameters.add(new BasicNameValuePair("swiss", ch_hello)); - - final String s = URLEncodedUtils.format(parameters, StandardCharsets.ISO_8859_1); - - Assert.assertEquals("english=hi+there&swiss=Gr%FCezi_z%E4m%E4", s); - - final StringEntity entity = new StringEntity(s, ContentType.create( - URLEncodedUtils.CONTENT_TYPE, StandardCharsets.ISO_8859_1)); - final List result = URLEncodedUtils.parse(entity); - Assert.assertEquals(2, result.size()); - assertNameValuePair(result.get(0), "english", us_hello); - assertNameValuePair(result.get(1), "swiss", ch_hello); - } - - @Test - public void testIsEncoded() throws Exception { - final StringEntity entity = new StringEntity("..."); - - entity.setContentType(URLEncodedUtils.CONTENT_TYPE); - Assert.assertTrue(URLEncodedUtils.isEncoded(entity)); - - entity.setContentType(URLEncodedUtils.CONTENT_TYPE + "; charset=US-ASCII"); - Assert.assertTrue(URLEncodedUtils.isEncoded(entity)); - - entity.setContentType("text/test"); - Assert.assertFalse(URLEncodedUtils.isEncoded(entity)); - } - - @Test - public void testFormat() throws Exception { - final List params = new ArrayList<>(); - Assert.assertEquals(0, URLEncodedUtils.format(params, StandardCharsets.US_ASCII).length()); - - params.clear(); - params.add(new BasicNameValuePair("Name0", null)); - Assert.assertEquals("Name0", URLEncodedUtils.format(params, StandardCharsets.US_ASCII)); - - params.clear(); - params.add(new BasicNameValuePair("Name1", "Value1")); - Assert.assertEquals("Name1=Value1", URLEncodedUtils.format(params, StandardCharsets.US_ASCII)); - - params.clear(); - params.add(new BasicNameValuePair("Name2", "")); - Assert.assertEquals("Name2=", URLEncodedUtils.format(params, StandardCharsets.US_ASCII)); - - params.clear(); - params.add(new BasicNameValuePair("Name4", "Value 4&")); - Assert.assertEquals("Name4=Value+4%26", URLEncodedUtils.format(params, StandardCharsets.US_ASCII)); - - params.clear(); - params.add(new BasicNameValuePair("Name4", "Value+4&")); - Assert.assertEquals("Name4=Value%2B4%26", URLEncodedUtils.format(params, StandardCharsets.US_ASCII)); - - params.clear(); - params.add(new BasicNameValuePair("Name4", "Value 4& =4")); - Assert.assertEquals("Name4=Value+4%26+%3D4", URLEncodedUtils.format(params, StandardCharsets.US_ASCII)); - - params.clear(); - params.add(new BasicNameValuePair("Name5", "aaa")); - params.add(new BasicNameValuePair("Name6", "bbb")); - Assert.assertEquals("Name5=aaa&Name6=bbb", URLEncodedUtils.format(params, StandardCharsets.US_ASCII)); - - params.clear(); - params.add(new BasicNameValuePair("Name7", "aaa")); - params.add(new BasicNameValuePair("Name7", "b,b")); - params.add(new BasicNameValuePair("Name7", "ccc")); - Assert.assertEquals("Name7=aaa&Name7=b%2Cb&Name7=ccc", URLEncodedUtils.format(params, StandardCharsets.US_ASCII)); - Assert.assertEquals("Name7=aaa&Name7=b%2Cb&Name7=ccc", URLEncodedUtils.format(params, '&', StandardCharsets.US_ASCII)); - Assert.assertEquals("Name7=aaa;Name7=b%2Cb;Name7=ccc", URLEncodedUtils.format(params, ';', StandardCharsets.US_ASCII)); - - params.clear(); - params.add(new BasicNameValuePair("Name8", "xx, yy ,zz")); - Assert.assertEquals("Name8=xx%2C++yy++%2Czz", URLEncodedUtils.format(params, StandardCharsets.US_ASCII)); - } - - @Test - public void testFormatString() throws Exception { // as above, using String - final List params = new ArrayList<>(); - Assert.assertEquals(0, URLEncodedUtils.format(params, StandardCharsets.US_ASCII).length()); - - params.clear(); - params.add(new BasicNameValuePair("Name0", null)); - Assert.assertEquals("Name0", URLEncodedUtils.format(params, StandardCharsets.US_ASCII)); - - params.clear(); - params.add(new BasicNameValuePair("Name1", "Value1")); - Assert.assertEquals("Name1=Value1", URLEncodedUtils.format(params, StandardCharsets.US_ASCII)); - - params.clear(); - params.add(new BasicNameValuePair("Name2", "")); - Assert.assertEquals("Name2=", URLEncodedUtils.format(params, StandardCharsets.US_ASCII)); - - params.clear(); - params.add(new BasicNameValuePair("Name4", "Value 4&")); - Assert.assertEquals("Name4=Value+4%26", URLEncodedUtils.format(params, StandardCharsets.US_ASCII)); - - params.clear(); - params.add(new BasicNameValuePair("Name4", "Value+4&")); - Assert.assertEquals("Name4=Value%2B4%26", URLEncodedUtils.format(params, StandardCharsets.US_ASCII)); - - params.clear(); - params.add(new BasicNameValuePair("Name4", "Value 4& =4")); - Assert.assertEquals("Name4=Value+4%26+%3D4", URLEncodedUtils.format(params, StandardCharsets.US_ASCII)); - - params.clear(); - params.add(new BasicNameValuePair("Name5", "aaa")); - params.add(new BasicNameValuePair("Name6", "bbb")); - Assert.assertEquals("Name5=aaa&Name6=bbb", URLEncodedUtils.format(params, StandardCharsets.US_ASCII)); - - params.clear(); - params.add(new BasicNameValuePair("Name7", "aaa")); - params.add(new BasicNameValuePair("Name7", "b,b")); - params.add(new BasicNameValuePair("Name7", "ccc")); - Assert.assertEquals("Name7=aaa&Name7=b%2Cb&Name7=ccc", URLEncodedUtils.format(params, StandardCharsets.US_ASCII)); - - params.clear(); - params.add(new BasicNameValuePair("Name8", "xx, yy ,zz")); - Assert.assertEquals("Name8=xx%2C++yy++%2Czz", URLEncodedUtils.format(params, StandardCharsets.US_ASCII)); - } - - private List parse (final String params) { - return URLEncodedUtils.parse(params, StandardCharsets.UTF_8); - } - - private List parseString (final String uri) throws Exception { - return URLEncodedUtils.parse(new URI("?"+uri), StandardCharsets.UTF_8); - } - - private static void assertNameValuePair ( - final NameValuePair parameter, - final String expectedName, - final String expectedValue) { - Assert.assertEquals(parameter.getName(), expectedName); - Assert.assertEquals(parameter.getValue(), expectedValue); - } - -} diff --git a/httpclient5/src/test/resources/log4j2-debug.xml.template b/httpclient5/src/test/resources/log4j2-debug.xml.template new file mode 100644 index 000000000..610d4d7a7 --- /dev/null +++ b/httpclient5/src/test/resources/log4j2-debug.xml.template @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index 7460490ae..0bfb2f739 100644 --- a/pom.xml +++ b/pom.xml @@ -67,7 +67,7 @@ 1.7 1.7 - 5.0-alpha1 + 5.0-alpha2 2.7 1.10 2.6.11 @@ -75,7 +75,7 @@ 1.7.13 4.12 2.5.2 - 1.8.5 + 1.10.19 4.2.1 1 0.12