From 5acfce106111508438e2deeb41bd3ba160194c42 Mon Sep 17 00:00:00 2001 From: cleverchuk Date: Wed, 2 Oct 2024 14:31:17 -0400 Subject: [PATCH] NH-86008: remove dead code --- .../tracelytics/agent/FrameworkRecorder.java | 238 --- .../joboe/AgentHostInfoReader.java | 829 --------- .../tracelytics/monitor/SystemCollector.java | 28 - .../tracelytics/monitor/SystemMonitor.java | 115 -- .../monitor/SystemMonitorController.java | 103 - .../monitor/SystemMonitorFactory.java | 7 - .../monitor/SystemMonitorFactoryImpl.java | 71 - .../monitor/SystemMonitorWithFrequency.java | 126 -- .../monitor/SystemMonitorWithInterval.java | 47 - .../tracelytics/monitor/SystemReporter.java | 33 - .../monitor/SystemReporterException.java | 12 - .../framework/FrameworkInfoCollector.java | 41 - .../framework/FrameworkInfoMonitor.java | 26 - .../framework/FrameworkInfoReporter.java | 69 - .../jmx/processor/AttributeProcessor.java | 107 -- .../processor/AttributeProcessorLocator.java | 55 - .../processor/CpuLoadAttributeProcessor.java | 122 -- .../processor/GenericAttributeProcessor.java | 45 - .../processor/OptionalAttributeProcessor.java | 58 - .../AbstractMetricsEntryCollector.java | 17 - .../metrics/CustomMetricsCollector.java | 200 -- .../monitor/metrics/JMXCollector.java | 315 ---- .../tracelytics/monitor/metrics/JMXScope.java | 55 - .../monitor/metrics/MetricsCategory.java | 10 - .../monitor/metrics/MetricsCollector.java | 80 - .../monitor/metrics/MetricsMonitor.java | 72 - .../monitor/metrics/MetricsReporter.java | 172 -- .../monitor/metrics/SpanMetricsCollector.java | 53 - .../metrics/SystemMetricsCollector.java | 65 - .../TraceDecisionMetricsCollector.java | 59 - .../TracingReporterMetricsCollector.java | 29 - .../agent/FrameworkRecorderTest.java | 77 - .../joboe/AgentHostInfoReaderTest.java | 58 - .../joboe/DockerInfoReaderTest.java | 40 - .../java/com/tracelytics/joboe/SuSE-release | 3 - .../joboe/TestSubmitRejectionRpcClient.java | 33 - .../java/com/tracelytics/joboe/debian_version | 1 - .../com/tracelytics/joboe/docker-cgroup-ce | 13 - .../com/tracelytics/joboe/docker-cgroup-ecs | 13 - .../com/tracelytics/joboe/docker-cgroup-empty | 0 .../tracelytics/joboe/docker-cgroup-invalid | 1 - .../joboe/docker-cgroup-non-docker | 10 - .../tracelytics/joboe/docker-cgroup-standard | 11 - .../joboe/docker-cgroup-standard-2 | 11 - .../java/com/tracelytics/joboe/gentoo-release | 1 - .../java/com/tracelytics/joboe/lsb-release | 4 - .../java/com/tracelytics/joboe/redhat-release | 1 - .../com/tracelytics/joboe/slackware-version | 1 - .../com/tracelytics/joboe/system-release-cpe | 1 - .../histogram/HdrHistrogramAdapterTest.java | 59 - .../histogram/MockHistogramAdapter.java | 122 -- .../monitor/SystemMonitorControllerTest.java | 12 - .../monitor/SystemMonitorFactoryTest.java | 49 - .../SystemMonitorWithFrequencyTest.java | 94 - .../framework/FrameworkInfoReporterTest.java | 61 - .../metrics/CustomMetricsCollectorTest.java | 166 -- .../monitor/metrics/JMXCollectorTest.java | 464 ----- .../monitor/metrics/MetricsCollectorTest.java | 144 -- .../monitor/metrics/MetricsMonitorTest.java | 62 - .../monitor/metrics/MetricsReportTest.java | 304 --- .../metrics/SpanMetricsCollectorTest.java | 57 - .../metrics/SystemMetricsCollectorTest.java | 27 - .../http/ConnectionClosedException.java | 50 - .../apache/http/ConnectionReuseStrategy.java | 72 - .../tracelytics/ext/apache/http/Consts.java | 51 - .../apache/http/ContentTooLongException.java | 50 - .../ext/apache/http/ExceptionLogger.java | 53 - .../ext/apache/http/FormattedHeader.java | 60 - .../tracelytics/ext/apache/http/Header.java | 74 - .../ext/apache/http/HeaderElement.java | 108 -- .../apache/http/HeaderElementIterator.java | 58 - .../ext/apache/http/HeaderIterator.java | 57 - .../ext/apache/http/HttpClientConnection.java | 102 - .../ext/apache/http/HttpConnection.java | 105 -- .../apache/http/HttpConnectionFactory.java | 42 - .../apache/http/HttpConnectionMetrics.java | 77 - .../ext/apache/http/HttpEntity.java | 199 -- .../http/HttpEntityEnclosingRequest.java | 60 - .../ext/apache/http/HttpException.java | 67 - .../ext/apache/http/HttpHeaders.java | 206 -- .../tracelytics/ext/apache/http/HttpHost.java | 338 ---- .../ext/apache/http/HttpInetConnection.java | 47 - .../ext/apache/http/HttpMessage.java | 210 --- .../ext/apache/http/HttpRequest.java | 53 - .../ext/apache/http/HttpRequestFactory.java | 43 - .../apache/http/HttpRequestInterceptor.java | 68 - .../ext/apache/http/HttpResponse.java | 155 -- .../ext/apache/http/HttpResponseFactory.java | 67 - .../apache/http/HttpResponseInterceptor.java | 68 - .../ext/apache/http/HttpServerConnection.java | 88 - .../ext/apache/http/HttpStatus.java | 176 -- .../ext/apache/http/HttpVersion.java | 110 -- .../http/MalformedChunkCodingException.java | 57 - .../http/MessageConstraintException.java | 57 - .../http/MethodNotSupportedException.java | 59 - .../ext/apache/http/NameValuePair.java | 47 - .../apache/http/NoHttpResponseException.java | 50 - .../ext/apache/http/ParseException.java | 61 - .../ext/apache/http/ProtocolException.java | 67 - .../ext/apache/http/ProtocolVersion.java | 265 --- .../ext/apache/http/ReasonPhraseCatalog.java | 51 - .../ext/apache/http/RequestLine.java | 49 - .../ext/apache/http/StatusLine.java | 52 - .../ext/apache/http/TokenIterator.java | 60 - .../apache/http/TruncatedChunkException.java | 48 - .../http/UnsupportedHttpVersionException.java | 57 - .../apache/http/annotation/Experimental.java | 42 - .../ext/apache/http/annotation/GuardedBy.java | 80 - .../ext/apache/http/annotation/Immutable.java | 59 - .../apache/http/annotation/NotThreadSafe.java | 50 - .../ext/apache/http/annotation/Obsolete.java | 43 - .../apache/http/annotation/ThreadSafe.java | 51 - .../apache/http/annotation/package-info.java | 35 - .../ext/apache/http/auth/AUTH.java | 64 - .../ext/apache/http/auth/AuthOption.java | 63 - .../apache/http/auth/AuthProtocolState.java | 33 - .../ext/apache/http/auth/AuthScheme.java | 130 -- .../apache/http/auth/AuthSchemeFactory.java | 51 - .../apache/http/auth/AuthSchemeProvider.java | 46 - .../apache/http/auth/AuthSchemeRegistry.java | 157 -- .../ext/apache/http/auth/AuthScope.java | 328 ---- .../ext/apache/http/auth/AuthState.java | 235 --- .../http/auth/AuthenticationException.java | 70 - .../apache/http/auth/BasicUserPrincipal.java | 90 - .../ext/apache/http/auth/ChallengeState.java | 38 - .../http/auth/ContextAwareAuthScheme.java | 62 - .../ext/apache/http/auth/Credentials.java | 44 - .../auth/InvalidCredentialsException.java | 69 - .../apache/http/auth/KerberosCredentials.java | 69 - .../auth/MalformedChallengeException.java | 70 - .../ext/apache/http/auth/NTCredentials.java | 179 -- .../ext/apache/http/auth/NTUserPrincipal.java | 114 -- .../auth/UsernamePasswordCredentials.java | 122 -- .../ext/apache/http/auth/package-info.java | 31 - .../apache/http/auth/params/AuthPNames.java | 74 - .../apache/http/auth/params/package-info.java | 32 - .../ext/apache/http/client/AuthCache.java | 50 - .../http/client/AuthenticationStrategy.java | 131 -- .../apache/http/client/BackoffManager.java | 54 - .../client/CircularRedirectException.java | 68 - .../http/client/ClientProtocolException.java | 61 - .../client/ConnectionBackoffStrategy.java | 64 - .../ext/apache/http/client/CookieStore.java | 71 - .../http/client/CredentialsProvider.java | 71 - .../ext/apache/http/client/HttpClient.java | 263 --- .../http/client/HttpRequestRetryHandler.java | 60 - .../http/client/HttpResponseException.java | 52 - .../client/NonRepeatableRequestException.java | 72 - .../apache/http/client/RedirectException.java | 69 - .../apache/http/client/RedirectStrategy.java | 82 - .../apache/http/client/ResponseHandler.java | 54 - .../ServiceUnavailableRetryStrategy.java | 60 - .../apache/http/client/UserTokenHandler.java | 59 - .../http/client/config/AuthSchemes.java | 74 - .../http/client/config/CookieSpecs.java | 89 - .../http/client/config/RequestConfig.java | 505 ----- .../http/client/config/package-info.java | 31 - .../client/entity/DecompressingEntity.java | 114 -- .../entity/DeflateDecompressingEntity.java | 70 - .../client/entity/DeflateInputStream.java | 229 --- .../http/client/entity/EntityBuilder.java | 343 ---- .../client/entity/GzipCompressingEntity.java | 113 -- .../entity/GzipDecompressingEntity.java | 61 - .../client/entity/InputStreamFactory.java | 41 - .../entity/LazyDecompressingInputStream.java | 104 -- .../client/entity/UrlEncodedFormEntity.java | 108 -- .../http/client/entity/package-info.java | 31 - .../client/methods/AbortableHttpRequest.java | 82 - .../AbstractExecutionAwareRequest.java | 139 -- .../client/methods/CloseableHttpResponse.java | 40 - .../http/client/methods/Configurable.java | 44 - .../http/client/methods/HttpDelete.java | 77 - .../HttpEntityEnclosingRequestBase.java | 80 - .../client/methods/HttpExecutionAware.java | 48 - .../apache/http/client/methods/HttpGet.java | 77 - .../apache/http/client/methods/HttpHead.java | 80 - .../http/client/methods/HttpOptions.java | 100 - .../apache/http/client/methods/HttpPatch.java | 77 - .../apache/http/client/methods/HttpPost.java | 84 - .../apache/http/client/methods/HttpPut.java | 76 - .../http/client/methods/HttpRequestBase.java | 130 -- .../client/methods/HttpRequestWrapper.java | 208 --- .../apache/http/client/methods/HttpTrace.java | 79 - .../http/client/methods/HttpUriRequest.java | 85 - .../http/client/methods/RequestBuilder.java | 544 ------ .../http/client/methods/package-info.java | 31 - .../ext/apache/http/client/package-info.java | 31 - .../http/client/params/AllClientPNames.java | 65 - .../http/client/params/ClientPNames.java | 133 -- .../client/params/HttpClientParamConfig.java | 89 - .../http/client/params/package-info.java | 32 - .../client/protocol/HttpClientContext.java | 250 --- .../protocol/RequestAcceptEncoding.java | 85 - .../client/protocol/RequestAddCookies.java | 207 --- .../client/protocol/RequestAuthCache.java | 148 -- .../protocol/RequestClientConnControl.java | 93 - .../protocol/RequestDefaultHeaders.java | 91 - .../protocol/RequestExpectContinue.java | 85 - .../protocol/ResponseContentEncoding.java | 139 -- .../protocol/ResponseProcessCookies.java | 159 -- .../http/client/protocol/package-info.java | 31 - .../apache/http/client/utils/CloneUtils.java | 86 - .../apache/http/client/utils/DateUtils.java | 250 --- .../http/client/utils/HttpClientUtils.java | 150 -- .../apache/http/client/utils/URIBuilder.java | 513 ----- .../apache/http/client/utils/URIUtils.java | 466 ----- .../http/client/utils/URLEncodedUtils.java | 680 ------- .../http/client/utils/package-info.java | 31 - .../apache/http/concurrent/BasicFuture.java | 160 -- .../apache/http/concurrent/Cancellable.java | 39 - .../http/concurrent/FutureCallback.java | 44 - .../apache/http/concurrent/package-info.java | 31 - .../apache/http/config/ConnectionConfig.java | 192 -- .../ext/apache/http/config/Lookup.java | 40 - .../http/config/MessageConstraints.java | 118 -- .../ext/apache/http/config/Registry.java | 64 - .../apache/http/config/RegistryBuilder.java | 72 - .../ext/apache/http/config/SocketConfig.java | 293 --- .../ext/apache/http/config/package-info.java | 31 - .../http/conn/ClientConnectionManager.java | 117 -- .../http/conn/ClientConnectionRequest.java | 74 - .../http/conn/ConnectTimeoutException.java | 94 - .../conn/ConnectionKeepAliveStrategy.java | 66 - .../conn/ConnectionPoolTimeoutException.java | 60 - .../http/conn/ConnectionReleaseTrigger.java | 70 - .../apache/http/conn/ConnectionRequest.java | 69 - .../ext/apache/http/conn/DnsResolver.java | 54 - .../http/conn/EofSensorInputStream.java | 292 --- .../apache/http/conn/EofSensorWatcher.java | 96 - .../conn/HttpClientConnectionManager.java | 183 -- .../conn/HttpClientConnectionOperator.java | 61 - .../http/conn/HttpConnectionFactory.java | 41 - .../http/conn/HttpHostConnectException.java | 82 - .../http/conn/HttpInetSocketAddress.java | 65 - .../http/conn/HttpRoutedConnection.java | 83 - .../http/conn/ManagedClientConnection.java | 236 --- .../conn/ManagedHttpClientConnection.java | 80 - .../apache/http/conn/SchemePortResolver.java | 43 - .../http/conn/UnsupportedSchemeException.java | 51 - .../ext/apache/http/conn/package-info.java | 31 - .../conn/params/ConnConnectionPNames.java | 64 - .../http/conn/params/ConnManagerPNames.java | 67 - .../http/conn/params/ConnRoutePNames.java | 79 - .../apache/http/conn/params/package-info.java | 32 - .../http/conn/routing/BasicRouteDirector.java | 182 -- .../apache/http/conn/routing/HttpRoute.java | 366 ---- .../http/conn/routing/HttpRouteDirector.java | 74 - .../http/conn/routing/HttpRoutePlanner.java | 68 - .../apache/http/conn/routing/RouteInfo.java | 162 -- .../http/conn/routing/RouteTracker.java | 376 ---- .../http/conn/routing/package-info.java | 31 - .../scheme/LayeredSchemeSocketFactory.java | 68 - .../conn/scheme/LayeredSocketFactory.java | 69 - .../scheme/LayeredSocketFactoryAdaptor.java | 54 - .../ext/apache/http/conn/scheme/Scheme.java | 261 --- .../scheme/SchemeLayeredSocketFactory.java | 69 - .../SchemeLayeredSocketFactoryAdaptor.java | 58 - .../SchemeLayeredSocketFactoryAdaptor2.java | 79 - .../http/conn/scheme/SchemeRegistry.java | 168 -- .../http/conn/scheme/SchemeSocketFactory.java | 132 -- .../scheme/SchemeSocketFactoryAdaptor.java | 104 -- .../http/conn/scheme/SocketFactory.java | 129 -- .../conn/scheme/SocketFactoryAdaptor.java | 101 - .../apache/http/conn/scheme/package-info.java | 32 - .../conn/socket/ConnectionSocketFactory.java | 80 - .../LayeredConnectionSocketFactory.java | 63 - .../socket/PlainConnectionSocketFactory.java | 85 - .../apache/http/conn/socket/package-info.java | 31 - .../http/conn/ssl/AbstractVerifier.java | 268 --- .../conn/ssl/AllowAllHostnameVerifier.java | 60 - .../ssl/BrowserCompatHostnameVerifier.java | 69 - .../conn/ssl/DefaultHostnameVerifier.java | 297 --- .../http/conn/ssl/NoopHostnameVerifier.java | 56 - .../conn/ssl/SSLConnectionSocketFactory.java | 476 ----- .../conn/ssl/SSLInitializationException.java | 37 - .../http/conn/ssl/StrictHostnameVerifier.java | 75 - .../conn/ssl/TrustSelfSignedStrategy.java | 48 - .../apache/http/conn/ssl/TrustStrategy.java | 38 - .../http/conn/ssl/X509HostnameVerifier.java | 88 - .../apache/http/conn/ssl/package-info.java | 31 - .../http/conn/util/InetAddressUtils.java | 124 -- .../http/conn/util/PublicSuffixList.java | 63 - .../conn/util/PublicSuffixListParser.java | 114 -- .../http/conn/util/PublicSuffixMatcher.java | 121 -- .../conn/util/PublicSuffixMatcherLoader.java | 104 -- .../apache/http/conn/util/package-info.java | 31 - .../ext/apache/http/cookie/ClientCookie.java | 69 - .../cookie/CommonCookieAttributeHandler.java | 40 - .../ext/apache/http/cookie/Cookie.java | 148 -- .../http/cookie/CookieAttributeHandler.java | 73 - .../http/cookie/CookieIdentityComparator.java | 81 - .../ext/apache/http/cookie/CookieOrigin.java | 95 - .../http/cookie/CookiePathComparator.java | 84 - .../http/cookie/CookiePriorityComparator.java | 70 - .../CookieRestrictionViolationException.java | 61 - .../ext/apache/http/cookie/CookieSpec.java | 114 -- .../apache/http/cookie/CookieSpecFactory.java | 51 - .../http/cookie/CookieSpecProvider.java | 46 - .../http/cookie/CookieSpecRegistry.java | 169 -- .../http/cookie/MalformedCookieException.java | 71 - .../ext/apache/http/cookie/SM.java | 43 - .../ext/apache/http/cookie/SetCookie.java | 116 -- .../ext/apache/http/cookie/SetCookie2.java | 68 - .../ext/apache/http/cookie/package-info.java | 31 - .../http/cookie/params/CookieSpecPNames.java | 65 - .../http/cookie/params/package-info.java | 32 - .../http/entity/AbstractHttpEntity.java | 221 --- .../apache/http/entity/BasicHttpEntity.java | 131 -- .../http/entity/BufferedHttpEntity.java | 125 -- .../apache/http/entity/ByteArrayEntity.java | 136 -- .../http/entity/ContentLengthStrategy.java | 57 - .../apache/http/entity/ContentProducer.java | 44 - .../ext/apache/http/entity/ContentType.java | 419 ----- .../apache/http/entity/EntityTemplate.java | 81 - .../ext/apache/http/entity/FileEntity.java | 126 -- .../apache/http/entity/HttpEntityWrapper.java | 114 -- .../apache/http/entity/InputStreamEntity.java | 160 -- .../http/entity/SerializableEntity.java | 131 -- .../ext/apache/http/entity/StringEntity.java | 188 -- .../ext/apache/http/entity/package-info.java | 31 - .../impl/AbstractHttpClientConnection.java | 324 ---- .../impl/AbstractHttpServerConnection.java | 311 ---- .../apache/http/impl/BHttpConnectionBase.java | 404 ---- .../ext/apache/http/impl/ConnSupport.java | 75 - .../impl/DefaultBHttpClientConnection.java | 188 -- .../DefaultBHttpClientConnectionFactory.java | 104 -- .../impl/DefaultBHttpServerConnection.java | 179 -- .../DefaultBHttpServerConnectionFactory.java | 104 -- .../impl/DefaultConnectionReuseStrategy.java | 190 -- .../impl/DefaultHttpClientConnection.java | 70 - .../http/impl/DefaultHttpRequestFactory.java | 111 -- .../http/impl/DefaultHttpResponseFactory.java | 111 -- .../impl/DefaultHttpServerConnection.java | 71 - .../http/impl/EnglishReasonPhraseCatalog.java | 225 --- .../http/impl/HttpConnectionMetricsImpl.java | 154 -- .../http/impl/NoConnectionReuseStrategy.java | 54 - .../http/impl/SocketHttpClientConnection.java | 284 --- .../http/impl/SocketHttpServerConnection.java | 272 --- .../apache/http/impl/auth/AuthSchemeBase.java | 172 -- .../apache/http/impl/auth/BasicScheme.java | 227 --- .../http/impl/auth/BasicSchemeFactory.java | 74 - .../apache/http/impl/auth/DigestScheme.java | 500 ----- .../http/impl/auth/DigestSchemeFactory.java | 74 - .../apache/http/impl/auth/GGSSchemeBase.java | 281 --- .../http/impl/auth/HttpAuthenticator.java | 245 --- .../http/impl/auth/HttpEntityDigester.java | 75 - .../apache/http/impl/auth/KerberosScheme.java | 133 -- .../http/impl/auth/KerberosSchemeFactory.java | 87 - .../ext/apache/http/impl/auth/NTLMEngine.java | 70 - .../http/impl/auth/NTLMEngineException.java | 68 - .../apache/http/impl/auth/NTLMEngineImpl.java | 1655 ----------------- .../ext/apache/http/impl/auth/NTLMScheme.java | 171 -- .../http/impl/auth/NTLMSchemeFactory.java | 59 - .../apache/http/impl/auth/RFC2617Scheme.java | 176 -- .../apache/http/impl/auth/SPNegoScheme.java | 134 -- .../http/impl/auth/SPNegoSchemeFactory.java | 87 - .../UnsupportedDigestAlgorithmException.java | 69 - .../apache/http/impl/auth/package-info.java | 32 - .../http/impl/bootstrap/HttpServer.java | 179 -- .../http/impl/bootstrap/RequestListener.java | 106 -- .../impl/bootstrap/SSLServerSetupHandler.java | 45 - .../http/impl/bootstrap/ServerBootstrap.java | 412 ---- .../impl/bootstrap/ThreadFactoryImpl.java | 56 - .../apache/http/impl/bootstrap/Worker.java | 81 - .../http/impl/bootstrap/package-info.java | 31 - .../http/impl/client/AIMDBackoffManager.java | 167 -- .../impl/client/AbstractResponseHandler.java | 82 - .../client/AuthenticationStrategyImpl.java | 260 --- .../http/impl/client/BasicAuthCache.java | 165 -- .../http/impl/client/BasicCookieStore.java | 149 -- .../impl/client/BasicCredentialsProvider.java | 113 -- .../impl/client/BasicResponseHandler.java | 69 - .../ext/apache/http/impl/client/Clock.java | 43 - .../http/impl/client/CloseableHttpClient.java | 242 --- .../impl/client/DefaultBackoffStrategy.java | 57 - .../DefaultConnectionKeepAliveStrategy.java | 73 - .../DefaultHttpRequestRetryHandler.java | 205 -- .../impl/client/DefaultRedirectStrategy.java | 236 --- ...efaultServiceUnavailableRetryStrategy.java | 83 - .../impl/client/DefaultUserTokenHandler.java | 103 - .../client/EntityEnclosingRequestWrapper.java | 117 -- .../client/FutureRequestExecutionMetrics.java | 156 -- .../client/FutureRequestExecutionService.java | 142 -- .../http/impl/client/HttpClientBuilder.java | 1203 ------------ .../apache/http/impl/client/HttpClients.java | 86 - .../impl/client/HttpRequestFutureTask.java | 118 -- .../impl/client/HttpRequestTaskCallable.java | 121 -- .../impl/client/IdleConnectionEvictor.java | 124 -- .../http/impl/client/InternalHttpClient.java | 255 --- .../http/impl/client/LaxRedirectStrategy.java | 66 - .../http/impl/client/MinimalHttpClient.java | 166 -- .../impl/client/NoopUserTokenHandler.java | 49 - .../http/impl/client/NullBackoffStrategy.java | 50 - .../client/ProxyAuthenticationStrategy.java | 58 - .../apache/http/impl/client/ProxyClient.java | 255 --- .../http/impl/client/RedirectLocations.java | 227 --- .../http/impl/client/RequestWrapper.java | 171 -- .../StandardHttpRequestRetryHandler.java | 81 - .../apache/http/impl/client/SystemClock.java | 41 - .../SystemDefaultCredentialsProvider.java | 152 -- .../client/TargetAuthenticationStrategy.java | 58 - .../apache/http/impl/client/package-info.java | 52 - .../BasicHttpClientConnectionManager.java | 395 ---- .../ext/apache/http/impl/conn/CPool.java | 71 - .../ext/apache/http/impl/conn/CPoolEntry.java | 102 - .../ext/apache/http/impl/conn/CPoolProxy.java | 270 --- .../conn/ConnectionShutdownException.java | 50 - .../DefaultHttpClientConnectionOperator.java | 189 -- .../impl/conn/DefaultHttpResponseParser.java | 168 -- .../DefaultHttpResponseParserFactory.java | 78 - .../DefaultManagedHttpClientConnection.java | 141 -- .../impl/conn/DefaultProxyRoutePlanner.java | 67 - .../http/impl/conn/DefaultRoutePlanner.java | 114 -- .../impl/conn/DefaultSchemePortResolver.java | 63 - .../http/impl/conn/InMemoryDnsResolver.java | 95 - .../http/impl/conn/LoggingInputStream.java | 145 -- .../LoggingManagedHttpClientConnection.java | 133 -- .../http/impl/conn/LoggingOutputStream.java | 104 -- .../ManagedHttpClientConnectionFactory.java | 141 -- .../PoolingHttpClientConnectionManager.java | 596 ------ .../impl/conn/SystemDefaultDnsResolver.java | 48 - .../impl/conn/SystemDefaultRoutePlanner.java | 133 -- .../ext/apache/http/impl/conn/Wire.java | 153 -- .../apache/http/impl/conn/package-info.java | 32 - .../AbstractCookieAttributeHandler.java | 55 - .../http/impl/cookie/AbstractCookieSpec.java | 131 -- .../http/impl/cookie/BasicClientCookie.java | 406 ---- .../http/impl/cookie/BasicClientCookie2.java | 105 -- .../http/impl/cookie/BasicCommentHandler.java | 60 - .../http/impl/cookie/BasicDomainHandler.java | 142 -- .../http/impl/cookie/BasicExpiresHandler.java | 75 - .../http/impl/cookie/BasicMaxAgeHandler.java | 76 - .../http/impl/cookie/BasicPathHandler.java | 103 - .../http/impl/cookie/BasicSecureHandler.java | 69 - .../http/impl/cookie/CookieSpecBase.java | 143 -- .../http/impl/cookie/DefaultCookieSpec.java | 222 --- .../cookie/DefaultCookieSpecProvider.java | 135 -- .../apache/http/impl/cookie/IgnoreSpec.java | 68 - .../http/impl/cookie/IgnoreSpecProvider.java | 62 - .../http/impl/cookie/LaxExpiresHandler.java | 221 --- .../http/impl/cookie/LaxMaxAgeHandler.java | 80 - .../impl/cookie/NetscapeDomainHandler.java | 126 -- .../cookie/NetscapeDraftHeaderParser.java | 102 - .../http/impl/cookie/NetscapeDraftSpec.java | 175 -- .../cookie/NetscapeDraftSpecProvider.java | 76 - .../impl/cookie/PublicSuffixDomainFilter.java | 105 -- .../impl/cookie/RFC2109DomainHandler.java | 130 -- .../apache/http/impl/cookie/RFC2109Spec.java | 244 --- .../http/impl/cookie/RFC2109SpecProvider.java | 90 - .../impl/cookie/RFC2109VersionHandler.java | 83 - .../RFC2965CommentUrlAttributeHandler.java | 76 - .../RFC2965DiscardAttributeHandler.java | 76 - .../cookie/RFC2965DomainAttributeHandler.java | 195 -- .../cookie/RFC2965PortAttributeHandler.java | 169 -- .../apache/http/impl/cookie/RFC2965Spec.java | 257 --- .../http/impl/cookie/RFC2965SpecProvider.java | 93 - .../RFC2965VersionAttributeHandler.java | 103 - .../impl/cookie/RFC6265CookieSpecBase.java | 277 --- .../cookie/RFC6265CookieSpecProvider.java | 123 -- .../http/impl/cookie/RFC6265LaxSpec.java | 62 - .../http/impl/cookie/RFC6265StrictSpec.java | 68 - .../apache/http/impl/cookie/package-info.java | 32 - ...DisallowIdentityContentLengthStrategy.java | 64 - .../http/impl/entity/EntityDeserializer.java | 143 -- .../http/impl/entity/EntitySerializer.java | 121 -- .../impl/entity/LaxContentLengthStrategy.java | 127 -- .../entity/StrictContentLengthStrategy.java | 117 -- .../apache/http/impl/entity/package-info.java | 31 - .../impl/execchain/BackoffStrategyExec.java | 106 -- .../http/impl/execchain/ClientExecChain.java | 76 - .../http/impl/execchain/ConnectionHolder.java | 158 -- .../impl/execchain/HttpResponseProxy.java | 214 --- .../http/impl/execchain/MainClientExec.java | 585 ------ .../impl/execchain/MinimalClientExec.java | 251 --- .../http/impl/execchain/ProtocolExec.java | 203 -- .../http/impl/execchain/RedirectExec.java | 187 -- .../execchain/RequestAbortedException.java | 55 - .../impl/execchain/RequestEntityProxy.java | 146 -- .../impl/execchain/ResponseEntityProxy.java | 156 -- .../apache/http/impl/execchain/RetryExec.java | 128 -- .../ServiceUnavailableRetryExec.java | 110 -- .../execchain/TunnelRefusedException.java | 55 - .../http/impl/execchain/package-info.java | 31 - .../http/impl/io/AbstractMessageParser.java | 285 --- .../http/impl/io/AbstractMessageWriter.java | 120 -- .../impl/io/AbstractSessionInputBuffer.java | 401 ---- .../impl/io/AbstractSessionOutputBuffer.java | 307 --- .../http/impl/io/ChunkedInputStream.java | 330 ---- .../http/impl/io/ChunkedOutputStream.java | 208 --- .../impl/io/ContentLengthInputStream.java | 232 --- .../impl/io/ContentLengthOutputStream.java | 136 -- .../impl/io/DefaultHttpRequestParser.java | 140 -- .../io/DefaultHttpRequestParserFactory.java | 72 - .../impl/io/DefaultHttpRequestWriter.java | 69 - .../io/DefaultHttpRequestWriterFactory.java | 64 - .../impl/io/DefaultHttpResponseParser.java | 141 -- .../io/DefaultHttpResponseParserFactory.java | 72 - .../impl/io/DefaultHttpResponseWriter.java | 69 - .../io/DefaultHttpResponseWriterFactory.java | 64 - .../apache/http/impl/io/EmptyInputStream.java | 84 - .../http/impl/io/HttpRequestParser.java | 102 - .../http/impl/io/HttpRequestWriter.java | 62 - .../http/impl/io/HttpResponseParser.java | 103 - .../http/impl/io/HttpResponseWriter.java | 62 - .../impl/io/HttpTransportMetricsImpl.java | 65 - .../http/impl/io/IdentityInputStream.java | 99 - .../http/impl/io/IdentityOutputStream.java | 104 -- .../http/impl/io/SessionInputBufferImpl.java | 412 ---- .../http/impl/io/SessionOutputBufferImpl.java | 293 --- .../http/impl/io/SocketInputBuffer.java | 108 -- .../http/impl/io/SocketOutputBuffer.java | 75 - .../ext/apache/http/impl/io/package-info.java | 32 - .../ext/apache/http/impl/package-info.java | 32 - .../http/impl/pool/BasicConnFactory.java | 184 -- .../apache/http/impl/pool/BasicConnPool.java | 94 - .../apache/http/impl/pool/BasicPoolEntry.java | 64 - .../apache/http/impl/pool/package-info.java | 32 - .../ext/apache/http/io/BufferInfo.java | 58 - .../ext/apache/http/io/EofSensor.java | 42 - .../ext/apache/http/io/HttpMessageParser.java | 56 - .../http/io/HttpMessageParserFactory.java | 42 - .../ext/apache/http/io/HttpMessageWriter.java | 54 - .../http/io/HttpMessageWriterFactory.java | 41 - .../apache/http/io/HttpTransportMetrics.java | 48 - .../apache/http/io/SessionInputBuffer.java | 152 -- .../apache/http/io/SessionOutputBuffer.java | 120 -- .../ext/apache/http/io/package-info.java | 32 - .../http/message/AbstractHttpMessage.java | 180 -- .../ext/apache/http/message/BasicHeader.java | 94 - .../http/message/BasicHeaderElement.java | 168 -- .../message/BasicHeaderElementIterator.java | 155 -- .../http/message/BasicHeaderIterator.java | 179 -- .../message/BasicHeaderValueFormatter.java | 426 ----- .../http/message/BasicHeaderValueParser.java | 304 --- .../BasicHttpEntityEnclosingRequest.java | 78 - .../apache/http/message/BasicHttpRequest.java | 116 -- .../http/message/BasicHttpResponse.java | 237 --- .../http/message/BasicLineFormatter.java | 323 ---- .../apache/http/message/BasicLineParser.java | 461 ----- .../http/message/BasicListHeaderIterator.java | 194 -- .../http/message/BasicNameValuePair.java | 113 -- .../apache/http/message/BasicRequestLine.java | 86 - .../apache/http/message/BasicStatusLine.java | 103 - .../http/message/BasicTokenIterator.java | 419 ----- .../apache/http/message/BufferedHeader.java | 135 -- .../ext/apache/http/message/HeaderGroup.java | 311 ---- .../http/message/HeaderValueFormatter.java | 122 -- .../http/message/HeaderValueParser.java | 134 -- .../apache/http/message/LineFormatter.java | 132 -- .../ext/apache/http/message/LineParser.java | 137 -- .../ext/apache/http/message/ParserCursor.java | 100 - .../ext/apache/http/message/TokenParser.java | 267 --- .../ext/apache/http/message/package-info.java | 32 - .../ext/apache/http/package-info.java | 43 - .../http/params/AbstractHttpParams.java | 135 -- .../apache/http/params/BasicHttpParams.java | 194 -- .../http/params/CoreConnectionPNames.java | 170 -- .../http/params/CoreProtocolPNames.java | 152 -- .../http/params/DefaultedHttpParams.java | 163 -- .../http/params/HttpAbstractParamBean.java | 48 - .../http/params/HttpConnectionParamBean.java | 71 - .../http/params/HttpConnectionParams.java | 243 --- .../apache/http/params/HttpParamConfig.java | 78 - .../ext/apache/http/params/HttpParams.java | 195 -- .../apache/http/params/HttpParamsNames.java | 57 - .../http/params/HttpProtocolParamBean.java | 69 - .../http/params/HttpProtocolParams.java | 240 --- .../http/params/SyncBasicHttpParams.java | 89 - .../ext/apache/http/params/package-info.java | 32 - .../apache/http/pool/AbstractConnPool.java | 599 ------ .../ext/apache/http/pool/ConnFactory.java | 44 - .../ext/apache/http/pool/ConnPool.java | 68 - .../ext/apache/http/pool/ConnPoolControl.java | 56 - .../ext/apache/http/pool/PoolEntry.java | 194 -- .../apache/http/pool/PoolEntryCallback.java | 41 - .../ext/apache/http/pool/PoolEntryFuture.java | 160 -- .../ext/apache/http/pool/PoolStats.java | 114 -- .../apache/http/pool/RouteSpecificPool.java | 184 -- .../ext/apache/http/pool/package-info.java | 32 - .../http/protocol/BasicHttpContext.java | 98 - .../http/protocol/BasicHttpProcessor.java | 246 --- .../apache/http/protocol/ChainBuilder.java | 126 -- .../http/protocol/DefaultedHttpContext.java | 84 - .../http/protocol/ExecutionContext.java | 80 - .../ext/apache/http/protocol/HTTP.java | 135 -- .../ext/apache/http/protocol/HttpContext.java | 75 - .../apache/http/protocol/HttpCoreContext.java | 155 -- .../http/protocol/HttpDateGenerator.java | 77 - .../protocol/HttpExpectationVerifier.java | 81 - .../apache/http/protocol/HttpProcessor.java | 55 - .../http/protocol/HttpProcessorBuilder.java | 151 -- .../http/protocol/HttpRequestExecutor.java | 312 ---- .../http/protocol/HttpRequestHandler.java | 62 - .../protocol/HttpRequestHandlerMapper.java | 50 - .../protocol/HttpRequestHandlerRegistry.java | 107 -- .../protocol/HttpRequestHandlerResolver.java | 51 - .../protocol/HttpRequestInterceptorList.java | 103 - .../protocol/HttpResponseInterceptorList.java | 103 - .../ext/apache/http/protocol/HttpService.java | 461 ----- .../http/protocol/ImmutableHttpProcessor.java | 145 -- .../http/protocol/RequestConnControl.java | 70 - .../apache/http/protocol/RequestContent.java | 128 -- .../ext/apache/http/protocol/RequestDate.java | 66 - .../http/protocol/RequestExpectContinue.java | 94 - .../http/protocol/RequestTargetHost.java | 96 - .../http/protocol/RequestUserAgent.java | 80 - .../http/protocol/ResponseConnControl.java | 106 -- .../apache/http/protocol/ResponseContent.java | 134 -- .../apache/http/protocol/ResponseDate.java | 67 - .../apache/http/protocol/ResponseServer.java | 72 - .../http/protocol/SyncBasicHttpContext.java | 74 - .../protocol/UriHttpRequestHandlerMapper.java | 116 -- .../http/protocol/UriPatternMatcher.java | 165 -- .../apache/http/protocol/package-info.java | 32 - .../apache/http/ssl/PrivateKeyDetails.java | 63 - .../apache/http/ssl/PrivateKeyStrategy.java | 48 - .../apache/http/ssl/SSLContextBuilder.java | 400 ---- .../ext/apache/http/ssl/SSLContexts.java | 90 - .../http/ssl/SSLInitializationException.java | 37 - .../ext/apache/http/ssl/TrustStrategy.java | 57 - .../ext/apache/http/ssl/package-info.java | 32 - .../ext/apache/http/util/Args.java | 127 -- .../ext/apache/http/util/Asserts.java | 68 - .../ext/apache/http/util/ByteArrayBuffer.java | 347 ---- .../ext/apache/http/util/CharArrayBuffer.java | 492 ----- .../ext/apache/http/util/CharsetUtils.java | 58 - .../ext/apache/http/util/EncodingUtils.java | 144 -- .../ext/apache/http/util/EntityUtils.java | 294 --- .../ext/apache/http/util/ExceptionUtils.java | 82 - .../ext/apache/http/util/LangUtils.java | 100 - .../ext/apache/http/util/NetUtils.java | 54 - .../ext/apache/http/util/TextUtils.java | 75 - .../ext/apache/http/util/VersionInfo.java | 326 ---- .../ext/apache/http/util/package-info.java | 31 - 634 files changed, 78753 deletions(-) delete mode 100644 agent/src/main/java/com/tracelytics/agent/FrameworkRecorder.java delete mode 100644 agent/src/main/java/com/tracelytics/joboe/AgentHostInfoReader.java delete mode 100644 agent/src/main/java/com/tracelytics/monitor/SystemCollector.java delete mode 100644 agent/src/main/java/com/tracelytics/monitor/SystemMonitor.java delete mode 100644 agent/src/main/java/com/tracelytics/monitor/SystemMonitorController.java delete mode 100644 agent/src/main/java/com/tracelytics/monitor/SystemMonitorFactory.java delete mode 100644 agent/src/main/java/com/tracelytics/monitor/SystemMonitorFactoryImpl.java delete mode 100644 agent/src/main/java/com/tracelytics/monitor/SystemMonitorWithFrequency.java delete mode 100644 agent/src/main/java/com/tracelytics/monitor/SystemMonitorWithInterval.java delete mode 100644 agent/src/main/java/com/tracelytics/monitor/SystemReporter.java delete mode 100644 agent/src/main/java/com/tracelytics/monitor/SystemReporterException.java delete mode 100644 agent/src/main/java/com/tracelytics/monitor/framework/FrameworkInfoCollector.java delete mode 100644 agent/src/main/java/com/tracelytics/monitor/framework/FrameworkInfoMonitor.java delete mode 100644 agent/src/main/java/com/tracelytics/monitor/framework/FrameworkInfoReporter.java delete mode 100644 agent/src/main/java/com/tracelytics/monitor/jmx/processor/AttributeProcessor.java delete mode 100644 agent/src/main/java/com/tracelytics/monitor/jmx/processor/AttributeProcessorLocator.java delete mode 100644 agent/src/main/java/com/tracelytics/monitor/jmx/processor/CpuLoadAttributeProcessor.java delete mode 100644 agent/src/main/java/com/tracelytics/monitor/jmx/processor/GenericAttributeProcessor.java delete mode 100644 agent/src/main/java/com/tracelytics/monitor/jmx/processor/OptionalAttributeProcessor.java delete mode 100644 agent/src/main/java/com/tracelytics/monitor/metrics/AbstractMetricsEntryCollector.java delete mode 100644 agent/src/main/java/com/tracelytics/monitor/metrics/CustomMetricsCollector.java delete mode 100644 agent/src/main/java/com/tracelytics/monitor/metrics/JMXCollector.java delete mode 100644 agent/src/main/java/com/tracelytics/monitor/metrics/JMXScope.java delete mode 100644 agent/src/main/java/com/tracelytics/monitor/metrics/MetricsCategory.java delete mode 100644 agent/src/main/java/com/tracelytics/monitor/metrics/MetricsCollector.java delete mode 100644 agent/src/main/java/com/tracelytics/monitor/metrics/MetricsMonitor.java delete mode 100644 agent/src/main/java/com/tracelytics/monitor/metrics/MetricsReporter.java delete mode 100644 agent/src/main/java/com/tracelytics/monitor/metrics/SpanMetricsCollector.java delete mode 100644 agent/src/main/java/com/tracelytics/monitor/metrics/SystemMetricsCollector.java delete mode 100644 agent/src/main/java/com/tracelytics/monitor/metrics/TraceDecisionMetricsCollector.java delete mode 100644 agent/src/main/java/com/tracelytics/monitor/metrics/TracingReporterMetricsCollector.java delete mode 100644 agent/src/test/java/com/tracelytics/agent/FrameworkRecorderTest.java delete mode 100644 agent/src/test/java/com/tracelytics/joboe/AgentHostInfoReaderTest.java delete mode 100644 agent/src/test/java/com/tracelytics/joboe/DockerInfoReaderTest.java delete mode 100644 agent/src/test/java/com/tracelytics/joboe/SuSE-release delete mode 100644 agent/src/test/java/com/tracelytics/joboe/TestSubmitRejectionRpcClient.java delete mode 100644 agent/src/test/java/com/tracelytics/joboe/debian_version delete mode 100644 agent/src/test/java/com/tracelytics/joboe/docker-cgroup-ce delete mode 100644 agent/src/test/java/com/tracelytics/joboe/docker-cgroup-ecs delete mode 100644 agent/src/test/java/com/tracelytics/joboe/docker-cgroup-empty delete mode 100644 agent/src/test/java/com/tracelytics/joboe/docker-cgroup-invalid delete mode 100644 agent/src/test/java/com/tracelytics/joboe/docker-cgroup-non-docker delete mode 100644 agent/src/test/java/com/tracelytics/joboe/docker-cgroup-standard delete mode 100644 agent/src/test/java/com/tracelytics/joboe/docker-cgroup-standard-2 delete mode 100644 agent/src/test/java/com/tracelytics/joboe/gentoo-release delete mode 100644 agent/src/test/java/com/tracelytics/joboe/lsb-release delete mode 100644 agent/src/test/java/com/tracelytics/joboe/redhat-release delete mode 100644 agent/src/test/java/com/tracelytics/joboe/slackware-version delete mode 100644 agent/src/test/java/com/tracelytics/joboe/system-release-cpe delete mode 100644 agent/src/test/java/com/tracelytics/metrics/histogram/HdrHistrogramAdapterTest.java delete mode 100644 agent/src/test/java/com/tracelytics/metrics/histogram/MockHistogramAdapter.java delete mode 100644 agent/src/test/java/com/tracelytics/monitor/SystemMonitorControllerTest.java delete mode 100644 agent/src/test/java/com/tracelytics/monitor/SystemMonitorFactoryTest.java delete mode 100644 agent/src/test/java/com/tracelytics/monitor/SystemMonitorWithFrequencyTest.java delete mode 100644 agent/src/test/java/com/tracelytics/monitor/framework/FrameworkInfoReporterTest.java delete mode 100644 agent/src/test/java/com/tracelytics/monitor/metrics/CustomMetricsCollectorTest.java delete mode 100644 agent/src/test/java/com/tracelytics/monitor/metrics/JMXCollectorTest.java delete mode 100644 agent/src/test/java/com/tracelytics/monitor/metrics/MetricsCollectorTest.java delete mode 100644 agent/src/test/java/com/tracelytics/monitor/metrics/MetricsMonitorTest.java delete mode 100644 agent/src/test/java/com/tracelytics/monitor/metrics/MetricsReportTest.java delete mode 100644 agent/src/test/java/com/tracelytics/monitor/metrics/SpanMetricsCollectorTest.java delete mode 100644 agent/src/test/java/com/tracelytics/monitor/metrics/SystemMetricsCollectorTest.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/ConnectionClosedException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/ConnectionReuseStrategy.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/Consts.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/ContentTooLongException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/ExceptionLogger.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/FormattedHeader.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/Header.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/HeaderElement.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/HeaderElementIterator.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/HeaderIterator.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpClientConnection.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpConnection.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpConnectionFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpConnectionMetrics.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpEntity.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpEntityEnclosingRequest.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpHeaders.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpHost.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpInetConnection.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpMessage.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpRequest.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpRequestFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpRequestInterceptor.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpResponse.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpResponseFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpResponseInterceptor.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpServerConnection.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpStatus.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpVersion.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/MalformedChunkCodingException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/MessageConstraintException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/MethodNotSupportedException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/NameValuePair.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/NoHttpResponseException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/ParseException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/ProtocolException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/ProtocolVersion.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/ReasonPhraseCatalog.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/RequestLine.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/StatusLine.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/TokenIterator.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/TruncatedChunkException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/UnsupportedHttpVersionException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/annotation/Experimental.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/annotation/GuardedBy.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/annotation/Immutable.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/annotation/NotThreadSafe.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/annotation/Obsolete.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/annotation/ThreadSafe.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/annotation/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AUTH.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthOption.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthProtocolState.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthScheme.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthSchemeFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthSchemeProvider.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthSchemeRegistry.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthScope.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthState.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthenticationException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/BasicUserPrincipal.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/ChallengeState.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/ContextAwareAuthScheme.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/Credentials.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/InvalidCredentialsException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/KerberosCredentials.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/MalformedChallengeException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/NTCredentials.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/NTUserPrincipal.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/UsernamePasswordCredentials.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/params/AuthPNames.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/params/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/AuthCache.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/AuthenticationStrategy.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/BackoffManager.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/CircularRedirectException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/ClientProtocolException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/ConnectionBackoffStrategy.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/CookieStore.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/CredentialsProvider.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/HttpClient.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/HttpRequestRetryHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/HttpResponseException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/NonRepeatableRequestException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/RedirectException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/RedirectStrategy.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/ResponseHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/ServiceUnavailableRetryStrategy.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/UserTokenHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/config/AuthSchemes.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/config/CookieSpecs.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/config/RequestConfig.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/config/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/DecompressingEntity.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/DeflateDecompressingEntity.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/DeflateInputStream.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/EntityBuilder.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/GzipCompressingEntity.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/GzipDecompressingEntity.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/InputStreamFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/LazyDecompressingInputStream.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/UrlEncodedFormEntity.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/AbortableHttpRequest.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/AbstractExecutionAwareRequest.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/CloseableHttpResponse.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/Configurable.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpDelete.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpEntityEnclosingRequestBase.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpExecutionAware.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpGet.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpHead.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpOptions.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpPatch.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpPost.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpPut.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpRequestBase.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpRequestWrapper.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpTrace.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpUriRequest.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/RequestBuilder.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/params/AllClientPNames.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/params/ClientPNames.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/params/HttpClientParamConfig.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/params/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/HttpClientContext.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/RequestAcceptEncoding.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/RequestAddCookies.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/RequestAuthCache.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/RequestClientConnControl.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/RequestDefaultHeaders.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/RequestExpectContinue.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/ResponseContentEncoding.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/ResponseProcessCookies.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/utils/CloneUtils.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/utils/DateUtils.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/utils/HttpClientUtils.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/utils/URIBuilder.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/utils/URIUtils.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/utils/URLEncodedUtils.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/client/utils/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/concurrent/BasicFuture.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/concurrent/Cancellable.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/concurrent/FutureCallback.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/concurrent/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/config/ConnectionConfig.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/config/Lookup.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/config/MessageConstraints.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/config/Registry.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/config/RegistryBuilder.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/config/SocketConfig.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/config/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ClientConnectionManager.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ClientConnectionRequest.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ConnectTimeoutException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ConnectionKeepAliveStrategy.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ConnectionPoolTimeoutException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ConnectionReleaseTrigger.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ConnectionRequest.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/DnsResolver.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/EofSensorInputStream.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/EofSensorWatcher.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/HttpClientConnectionManager.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/HttpClientConnectionOperator.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/HttpConnectionFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/HttpHostConnectException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/HttpInetSocketAddress.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/HttpRoutedConnection.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ManagedClientConnection.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ManagedHttpClientConnection.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/SchemePortResolver.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/UnsupportedSchemeException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/params/ConnConnectionPNames.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/params/ConnManagerPNames.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/params/ConnRoutePNames.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/params/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/routing/BasicRouteDirector.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/routing/HttpRoute.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/routing/HttpRouteDirector.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/routing/HttpRoutePlanner.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/routing/RouteInfo.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/routing/RouteTracker.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/routing/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/LayeredSchemeSocketFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/LayeredSocketFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/LayeredSocketFactoryAdaptor.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/Scheme.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SchemeLayeredSocketFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SchemeLayeredSocketFactoryAdaptor.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SchemeLayeredSocketFactoryAdaptor2.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SchemeRegistry.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SchemeSocketFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SchemeSocketFactoryAdaptor.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SocketFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SocketFactoryAdaptor.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/socket/ConnectionSocketFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/socket/LayeredConnectionSocketFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/socket/PlainConnectionSocketFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/socket/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/AbstractVerifier.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/AllowAllHostnameVerifier.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/BrowserCompatHostnameVerifier.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/DefaultHostnameVerifier.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/NoopHostnameVerifier.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/SSLConnectionSocketFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/SSLInitializationException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/StrictHostnameVerifier.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/TrustSelfSignedStrategy.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/TrustStrategy.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/X509HostnameVerifier.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/util/InetAddressUtils.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/util/PublicSuffixList.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/util/PublicSuffixListParser.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/util/PublicSuffixMatcher.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/util/PublicSuffixMatcherLoader.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/util/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/ClientCookie.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CommonCookieAttributeHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/Cookie.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieAttributeHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieIdentityComparator.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieOrigin.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookiePathComparator.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookiePriorityComparator.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieRestrictionViolationException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieSpec.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieSpecFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieSpecProvider.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieSpecRegistry.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/MalformedCookieException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/SM.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/SetCookie.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/SetCookie2.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/params/CookieSpecPNames.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/params/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/AbstractHttpEntity.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/BasicHttpEntity.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/BufferedHttpEntity.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/ByteArrayEntity.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/ContentLengthStrategy.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/ContentProducer.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/ContentType.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/EntityTemplate.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/FileEntity.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/HttpEntityWrapper.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/InputStreamEntity.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/SerializableEntity.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/StringEntity.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/AbstractHttpClientConnection.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/AbstractHttpServerConnection.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/BHttpConnectionBase.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/ConnSupport.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultBHttpClientConnection.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultBHttpClientConnectionFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultBHttpServerConnection.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultBHttpServerConnectionFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultConnectionReuseStrategy.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultHttpClientConnection.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultHttpRequestFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultHttpResponseFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultHttpServerConnection.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/EnglishReasonPhraseCatalog.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/HttpConnectionMetricsImpl.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/NoConnectionReuseStrategy.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/SocketHttpClientConnection.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/SocketHttpServerConnection.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/AuthSchemeBase.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/BasicScheme.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/BasicSchemeFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/DigestScheme.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/DigestSchemeFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/GGSSchemeBase.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/HttpAuthenticator.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/HttpEntityDigester.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/KerberosScheme.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/KerberosSchemeFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/NTLMEngine.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/NTLMEngineException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/NTLMEngineImpl.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/NTLMScheme.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/NTLMSchemeFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/RFC2617Scheme.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/SPNegoScheme.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/SPNegoSchemeFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/UnsupportedDigestAlgorithmException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/bootstrap/HttpServer.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/bootstrap/RequestListener.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/bootstrap/SSLServerSetupHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/bootstrap/ServerBootstrap.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/bootstrap/ThreadFactoryImpl.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/bootstrap/Worker.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/bootstrap/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/AIMDBackoffManager.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/AbstractResponseHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/AuthenticationStrategyImpl.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/BasicAuthCache.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/BasicCookieStore.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/BasicCredentialsProvider.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/BasicResponseHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/Clock.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/CloseableHttpClient.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/DefaultBackoffStrategy.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/DefaultConnectionKeepAliveStrategy.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/DefaultHttpRequestRetryHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/DefaultRedirectStrategy.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/DefaultServiceUnavailableRetryStrategy.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/DefaultUserTokenHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/EntityEnclosingRequestWrapper.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/FutureRequestExecutionMetrics.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/FutureRequestExecutionService.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/HttpClientBuilder.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/HttpClients.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/HttpRequestFutureTask.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/HttpRequestTaskCallable.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/IdleConnectionEvictor.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/InternalHttpClient.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/LaxRedirectStrategy.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/MinimalHttpClient.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/NoopUserTokenHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/NullBackoffStrategy.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/ProxyAuthenticationStrategy.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/ProxyClient.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/RedirectLocations.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/RequestWrapper.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/StandardHttpRequestRetryHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/SystemClock.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/SystemDefaultCredentialsProvider.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/TargetAuthenticationStrategy.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/BasicHttpClientConnectionManager.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/CPool.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/CPoolEntry.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/CPoolProxy.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/ConnectionShutdownException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/DefaultHttpClientConnectionOperator.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/DefaultHttpResponseParser.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/DefaultHttpResponseParserFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/DefaultManagedHttpClientConnection.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/DefaultProxyRoutePlanner.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/DefaultRoutePlanner.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/DefaultSchemePortResolver.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/InMemoryDnsResolver.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/LoggingInputStream.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/LoggingManagedHttpClientConnection.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/LoggingOutputStream.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/ManagedHttpClientConnectionFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/PoolingHttpClientConnectionManager.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/SystemDefaultDnsResolver.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/SystemDefaultRoutePlanner.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/Wire.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/AbstractCookieAttributeHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/AbstractCookieSpec.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicClientCookie.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicClientCookie2.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicCommentHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicDomainHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicExpiresHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicMaxAgeHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicPathHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicSecureHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/CookieSpecBase.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/DefaultCookieSpec.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/DefaultCookieSpecProvider.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/IgnoreSpec.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/IgnoreSpecProvider.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/LaxExpiresHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/LaxMaxAgeHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/NetscapeDomainHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/NetscapeDraftHeaderParser.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/NetscapeDraftSpec.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/NetscapeDraftSpecProvider.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/PublicSuffixDomainFilter.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2109DomainHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2109Spec.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2109SpecProvider.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2109VersionHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2965CommentUrlAttributeHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2965DiscardAttributeHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2965DomainAttributeHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2965PortAttributeHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2965Spec.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2965SpecProvider.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2965VersionAttributeHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC6265CookieSpecBase.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC6265CookieSpecProvider.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC6265LaxSpec.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC6265StrictSpec.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/entity/DisallowIdentityContentLengthStrategy.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/entity/EntityDeserializer.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/entity/EntitySerializer.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/entity/LaxContentLengthStrategy.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/entity/StrictContentLengthStrategy.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/entity/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/BackoffStrategyExec.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/ClientExecChain.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/ConnectionHolder.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/HttpResponseProxy.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/MainClientExec.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/MinimalClientExec.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/ProtocolExec.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/RedirectExec.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/RequestAbortedException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/RequestEntityProxy.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/ResponseEntityProxy.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/RetryExec.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/ServiceUnavailableRetryExec.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/TunnelRefusedException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/AbstractMessageParser.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/AbstractMessageWriter.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/AbstractSessionInputBuffer.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/AbstractSessionOutputBuffer.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/ChunkedInputStream.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/ChunkedOutputStream.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/ContentLengthInputStream.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/ContentLengthOutputStream.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpRequestParser.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpRequestParserFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpRequestWriter.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpRequestWriterFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpResponseParser.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpResponseParserFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpResponseWriter.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpResponseWriterFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/EmptyInputStream.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/HttpRequestParser.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/HttpRequestWriter.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/HttpResponseParser.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/HttpResponseWriter.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/HttpTransportMetricsImpl.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/IdentityInputStream.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/IdentityOutputStream.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/SessionInputBufferImpl.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/SessionOutputBufferImpl.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/SocketInputBuffer.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/SocketOutputBuffer.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/pool/BasicConnFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/pool/BasicConnPool.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/pool/BasicPoolEntry.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/pool/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/io/BufferInfo.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/io/EofSensor.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/io/HttpMessageParser.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/io/HttpMessageParserFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/io/HttpMessageWriter.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/io/HttpMessageWriterFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/io/HttpTransportMetrics.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/io/SessionInputBuffer.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/io/SessionOutputBuffer.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/io/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/message/AbstractHttpMessage.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHeader.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHeaderElement.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHeaderElementIterator.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHeaderIterator.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHeaderValueFormatter.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHeaderValueParser.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHttpEntityEnclosingRequest.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHttpRequest.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHttpResponse.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicLineFormatter.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicLineParser.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicListHeaderIterator.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicNameValuePair.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicRequestLine.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicStatusLine.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicTokenIterator.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BufferedHeader.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/message/HeaderGroup.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/message/HeaderValueFormatter.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/message/HeaderValueParser.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/message/LineFormatter.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/message/LineParser.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/message/ParserCursor.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/message/TokenParser.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/message/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/params/AbstractHttpParams.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/params/BasicHttpParams.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/params/CoreConnectionPNames.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/params/CoreProtocolPNames.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/params/DefaultedHttpParams.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpAbstractParamBean.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpConnectionParamBean.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpConnectionParams.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpParamConfig.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpParams.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpParamsNames.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpProtocolParamBean.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpProtocolParams.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/params/SyncBasicHttpParams.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/params/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/AbstractConnPool.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/ConnFactory.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/ConnPool.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/ConnPoolControl.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/PoolEntry.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/PoolEntryCallback.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/PoolEntryFuture.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/PoolStats.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/RouteSpecificPool.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/BasicHttpContext.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/BasicHttpProcessor.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/ChainBuilder.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/DefaultedHttpContext.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/ExecutionContext.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HTTP.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpContext.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpCoreContext.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpDateGenerator.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpExpectationVerifier.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpProcessor.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpProcessorBuilder.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpRequestExecutor.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpRequestHandler.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpRequestHandlerMapper.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpRequestHandlerRegistry.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpRequestHandlerResolver.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpRequestInterceptorList.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpResponseInterceptorList.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpService.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/ImmutableHttpProcessor.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/RequestConnControl.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/RequestContent.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/RequestDate.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/RequestExpectContinue.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/RequestTargetHost.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/RequestUserAgent.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/ResponseConnControl.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/ResponseContent.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/ResponseDate.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/ResponseServer.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/SyncBasicHttpContext.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/UriHttpRequestHandlerMapper.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/UriPatternMatcher.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/ssl/PrivateKeyDetails.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/ssl/PrivateKeyStrategy.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/ssl/SSLContextBuilder.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/ssl/SSLContexts.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/ssl/SSLInitializationException.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/ssl/TrustStrategy.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/ssl/package-info.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/util/Args.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/util/Asserts.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/util/ByteArrayBuffer.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/util/CharArrayBuffer.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/util/CharsetUtils.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/util/EncodingUtils.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/util/EntityUtils.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/util/ExceptionUtils.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/util/LangUtils.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/util/NetUtils.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/util/TextUtils.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/util/VersionInfo.java delete mode 100644 dependencies/src/main/java/com/tracelytics/ext/apache/http/util/package-info.java diff --git a/agent/src/main/java/com/tracelytics/agent/FrameworkRecorder.java b/agent/src/main/java/com/tracelytics/agent/FrameworkRecorder.java deleted file mode 100644 index 03d6c60d..00000000 --- a/agent/src/main/java/com/tracelytics/agent/FrameworkRecorder.java +++ /dev/null @@ -1,238 +0,0 @@ -package com.tracelytics.agent; - -import java.io.*; -import java.net.URL; -import java.net.URLClassLoader; -import java.security.ProtectionDomain; -import java.util.*; -import java.util.jar.*; - -import com.tracelytics.logging.Logger; -import com.tracelytics.logging.LoggerFactory; - -/** - * Extracts and reports framework information by locating the jar used by a package. - * - * We are using the MANIFEST.MF within the jar for framework information. Take note that if the information in the MANIFEST does not comply to the spec in - * http://docs.oracle.com/javase/7/docs/technotes/guides/jar/jar.html - * , then we will not report the framework - * - * @author Patson Luk - * - */ -public class FrameworkRecorder { - private static Logger logger = LoggerFactory.getLogger(); - private static final VersionExtractor[] EXTRACTORS = new VersionExtractor[] { new BundleVersionExtractor(), new ImplementationVersionExtractor(), new SpecificationVersionExtractor() }; - private static Set pendingFrameworks = new HashSet(); - private static Map processedSources = Collections.synchronizedMap(new WeakHashMap()); //synchronize it as it might hang indefinitely sometimes on docker instance, could be related to https://bugs.openjdk.java.net/browse/JDK-8075006 - - /** - * Extract and report the framework by reading the source jar of this ctClass - * @param protectionDomain - */ - public static void reportFramework(ProtectionDomain protectionDomain, ClassLoader classLoader, String packageName) { - //skip core java classes as it might introduce deadlock, also the java version should have already been reported in init message - if (packageName != null && (packageName.startsWith("java.") || packageName.startsWith("javax.") || packageName.startsWith("sun."))) { - return; - } - - if (protectionDomain != null) { - if (protectionDomain.getCodeSource() != null) { - URL location = protectionDomain.getCodeSource().getLocation(); - if (location != null && !processedSources.containsKey(location)) { - processedSources.put(location, true); - FrameworkInfo frameworkInfo = extractFrameworkInfoFromSource(location); - - if (frameworkInfo == null && packageName != null) { - logger.debug("Failed to extract framework info from source " + location + " try to load framework info using Package instead " + packageName); - frameworkInfo = extractFrameworkInfoFromPackage(classLoader, packageName); - } - - if (frameworkInfo != null) { - logger.debug("Found framework info " + frameworkInfo + " for " + location); - pendingFrameworks.add(frameworkInfo); - } else { - logger.debug("Cannot find valid manifest info from the source file [" + location + "]"); - } - } - } - } - } - - private static FrameworkInfo extractFrameworkInfoFromSource(URL sourceLocation) { - InputStream sourceStream = null; - try { - sourceStream = sourceLocation.openStream(); - if (sourceStream != null) { //source stream could be null, for example file:/C:/apache-tomcat-9.0.30/webapps/test_jdbc_war/WEB-INF/classes/ - JarInputStream jarInputStream = new JarInputStream(sourceStream); - logger.debug("Extracting framework info from cp entry " + sourceLocation); - Manifest manifest = jarInputStream.getManifest(); - - if (manifest != null) { - Attributes attributes = manifest.getMainAttributes(); - FrameworkInfo frameworkInfo = extractInfoFromAttributes(attributes); - if (frameworkInfo != null) { - logger.debug("Framework info extracted from [" + sourceLocation + "] : " + frameworkInfo); - } else { - logger.debug("No framework info extracted from [" + sourceLocation + "]"); - } - return frameworkInfo; - } - } - } catch (IOException e) { - logger.debug("Source file entry [" + sourceLocation + "] is not a valid jar, skipping..."); - } catch (Throwable e) { - logger.warn("Unexpected exception while parsing source file [" + sourceLocation + "] for framework versions, the entry would be skipped : " + e.getMessage(), e); - } finally { - if (sourceStream != null) { - try { - sourceStream.close(); - } catch (IOException e) { - logger.warn("Failed to close source stream after framework extraction: " + e.getMessage(), e); - } - } - } - return null; - } - - /** - * Extracts framework info by reading java.lang.Package from the ClassLoader - * @param loader - * @param packageName - * @return a FrameworkInfo object if found valid info, otherwise returns null - */ - static FrameworkInfo extractFrameworkInfoFromPackage(ClassLoader loader, String packageName) { - Package packageInfo = new PackageClassLoader(loader).getPackage(packageName); - if (packageInfo != null) { - if (packageInfo.getImplementationTitle() != null) { //have to at least have title - return new FrameworkInfo(packageInfo.getImplementationTitle(), packageInfo.getImplementationVersion()); - } else if (packageInfo.getImplementationVendor() != null) { //if implementation title is not found, use vendor name as title (this works for Jetty) - return new FrameworkInfo(packageInfo.getImplementationVendor(), packageInfo.getImplementationVersion()); - } else if (packageInfo.getSpecificationTitle() != null) { - return new FrameworkInfo(packageInfo.getSpecificationTitle(), packageInfo.getSpecificationVersion()); - } else if (packageInfo.getSpecificationVendor() != null) { - return new FrameworkInfo(packageInfo.getSpecificationVendor(), packageInfo.getSpecificationVersion()); - } - } - return null; - } - - /** - * A classloader that exposes the getPackage method of its parent loader. - * @author Patson Luk - * - */ - private static class PackageClassLoader extends URLClassLoader { - public PackageClassLoader(ClassLoader parent) { - super(new URL[0], parent); - } - - protected Package getPackage(String packageName) { - return super.getPackage(packageName); - } - } - - static FrameworkInfo extractInfoFromAttributes(Attributes attributes) { - for (VersionExtractor extractor : EXTRACTORS) { - FrameworkInfo frameworkInfo = extractor.extract(attributes); - if (frameworkInfo != null) { - return frameworkInfo; - } - } - return null; - } - - - /** - * Get clone of the list of pending frameworks, this would also clear the existing pending frameworks - * @return - */ - public static Set consumePendingFrameworks() { - HashSet clonedSet = new HashSet(pendingFrameworks); - pendingFrameworks.clear(); - - return clonedSet; - } - - private static abstract class VersionExtractor { - private final String[] KEYS = getIdentityKeys(); - - FrameworkInfo extract(Attributes attributes) { - String version = attributes.getValue(getVersionKey()); - - if (version != null) { - for (String key : KEYS) { - String value = attributes.getValue(key); - if (value != null) { - logger.debug("Found [" + key + "] with value [" + value + "] while extracting framework version [" + version + "] from " + getClass().getSimpleName()); - return new FrameworkInfo(value, version); - } - } - } - return null; - } - - protected abstract String[] getIdentityKeys(); - - protected abstract String getVersionKey(); - } - - private static class BundleVersionExtractor extends VersionExtractor { - @Override - protected String[] getIdentityKeys() { - return new String[]{"Bundle-SymbolicName", "Bundle-Name", "Bundle-Vendor"}; - } - - @Override - protected String getVersionKey() { - return "Bundle-Version"; - } - } - - private static class ImplementationVersionExtractor extends VersionExtractor { - @Override - protected String[] getIdentityKeys() { - return new String[]{"Implementation-Vendor-Id", "Implementation-Title", "Implementation-Vendor"}; - } - - @Override - protected String getVersionKey() { - return "Implementation-Version"; - } - } - - private static class SpecificationVersionExtractor extends VersionExtractor { - @Override - protected String[] getIdentityKeys() { - return new String[]{"Specification-Title", "Specification-Vendor"}; - } - - @Override - protected String getVersionKey() { - return "Specification-Version"; - } - } - - public static class FrameworkInfo { - private String id; - public FrameworkInfo(String id, String version) { - this.id = id; - this.version = version; - } - private String version; - - - public String getId() { - return id; - } - - public String getVersion() { - return version; - } - - @Override - public String toString() { - return (id != null ? id : "unknown") + (version != null ? (" | version : [" + version + "]") : ""); - } - } -} diff --git a/agent/src/main/java/com/tracelytics/joboe/AgentHostInfoReader.java b/agent/src/main/java/com/tracelytics/joboe/AgentHostInfoReader.java deleted file mode 100644 index f6cfad78..00000000 --- a/agent/src/main/java/com/tracelytics/joboe/AgentHostInfoReader.java +++ /dev/null @@ -1,829 +0,0 @@ -package com.tracelytics.joboe; - -import com.tracelytics.joboe.config.ConfigManager; -import com.tracelytics.joboe.config.ConfigProperty; -import com.tracelytics.joboe.rpc.HostType; -import com.tracelytics.joboe.span.impl.ScopeContextSnapshot; -import com.tracelytics.joboe.span.impl.ScopeManager; -import com.tracelytics.logging.Logger; -import com.tracelytics.logging.LoggerFactory; -import com.tracelytics.util.*; -import com.tracelytics.util.HostInfoUtils.NetworkAddressInfo; - -import java.io.*; -import java.lang.management.ManagementFactory; -import java.net.*; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import com.google.auto.service.AutoService; - -/** - * Helper to extract information on the host this JVM runs on - * @author pluk - * - */ -public class AgentHostInfoReader implements HostInfoReader { - public static final AgentHostInfoReader INSTANCE = new AgentHostInfoReader(); - private static Logger logger = LoggerFactory.getLogger(); - - private static final int HOST_ID_CHECK_INTERVAL = 60; - - private static String distro; - private static HostId hostId; //lazily initialized to avoid cyclic init - private static String hostname; - private static boolean checkedDistro = false; - private static HostInfoUtils.OsType osType = HostInfoUtils.getOsType(); - - static final String HOSTNAME_SEPARATOR = ";"; - - static enum DistroType { AMAZON, UBUNTU, DEBIAN, REDHAT_BASED, SUSE, SLACKWARE, GENTOO } - static final Map DISTRO_FILE_NAMES = new HashMap(); - - public static final String HOSTNAME_ALIAS_KEY = "ConfiguredHostname"; - - static { - - DISTRO_FILE_NAMES.put(DistroType.AMAZON, "/etc/system-release-cpe"); - DISTRO_FILE_NAMES.put(DistroType.REDHAT_BASED, "/etc/redhat-release"); - DISTRO_FILE_NAMES.put(DistroType.UBUNTU, "/etc/lsb-release"); - DISTRO_FILE_NAMES.put(DistroType.DEBIAN, "/etc/debian_version"); - DISTRO_FILE_NAMES.put(DistroType.SUSE, "/etc/SuSE-release"); - DISTRO_FILE_NAMES.put(DistroType.SLACKWARE, "/etc/slackware-version"); - DISTRO_FILE_NAMES.put(DistroType.GENTOO, "/etc/gentoo-release"); - } - - private AgentHostInfoReader() { - //prevent instantiations - } - - public String getAwsInstanceId() { - return Ec2InstanceReader.getInstanceId(); - } - - public String getAwsAvailabilityZone() { - return Ec2InstanceReader.getAvailabilityZone(); - } - - public String getDockerContainerId() { - return DockerInfoReader.getDockerId(); - } - - public String getHerokuDynoId() { - return HerokuDynoReader.getDynoId(); - } - - @Override - public String getAzureInstanceId() { - return AzureReader.getInstanceId(); - } - - // The network adapter status. It's used for Windows only. - enum NicStatus { - NOT_PRESENT("Not Present"), - UP("Up"), - DISCONNECTED("Disconnected"); - - private final String desc; - private static final Map ENUM_MAP; - - static { - Map map = new ConcurrentHashMap(); - for (NicStatus instance : NicStatus.values()) { - map.put(instance.getDesc(),instance); - } - ENUM_MAP = Collections.unmodifiableMap(map); - } - - NicStatus(String desc) { - this.desc = desc; - } - - public String getDesc() { - return this.desc; - } - - public static NicStatus fromDesc(String desc) { - return ENUM_MAP.get(desc); - } - } - - /** - * Get the network adapters status by executing a command on Windows. - * @param nicStatusMap - */ - private static void buildNicStatusMap(Map nicStatusMap) { - String output; - try { - output = ExecUtils.exec("powershell.exe Get-NetAdapter -IncludeHidden | Select-Object InterfaceDescription,Status | Format-Table -AutoSize", - System.getProperty("line.separator")); - } catch (Exception e) { - logger.info("Failed to obtain nic status from exec `Get-NetAdapter` : " + e.getMessage()); - return; - } - - String[] lines = output.split(System.getProperty("line.separator")); - if (lines.length < 3) { - logger.info("No enough data received from exec `Get-NetAdapter`(" + lines.length + "): " + Arrays.toString(lines)); - return; - } - - String header = lines[0]; - int statusStartPoint = header.indexOf("Status"); - if (statusStartPoint == -1) { - logger.info("Failed to obtain nic status as the header `Status` is not found. " + Arrays.toString(lines)); - return; - } - - lines = Arrays.copyOfRange(lines, 2, lines.length); - - for (String line : lines) { - if (statusStartPoint > line.length()) { - continue; - } - String name = line.substring(0, statusStartPoint).trim(); - NicStatus status = NicStatus.fromDesc(line.substring(statusStartPoint).trim()); - logger.debug("Get device display name=" + name + ", status=" + status); - nicStatusMap.put(name, status); - } - - } - /** - * Extracts network interface info from the system. Take note that loop back, point-to-point and non-physical addresses are excluded - * @return - */ - @Override - public NetworkAddressInfo getNetworkAddressInfo() { - try { - List ips = new ArrayList(); - List macAddresses = new ArrayList(); - - // map of device id -> status - Map nicStatusMap = new HashMap(); - boolean isWindowsIPv4 = false; - if (osType.equals(HostInfoUtils.OsType.WINDOWS) && Boolean.getBoolean("java.net.preferIPv4Stack")) { - buildNicStatusMap(nicStatusMap); - isWindowsIPv4 = true; - } - - for (NetworkInterface networkInterface : Collections.list(NetworkInterface.getNetworkInterfaces())) { - try { - logger.debug("Found network interface " + networkInterface.getName() + " " + networkInterface.getDisplayName()); - if (!networkInterface.isLoopback() && !networkInterface.isPointToPoint() && isPhysicalInterface(networkInterface) && !isGhostHyperV(networkInterface)) { - logger.debug("Processing physical network interface " + networkInterface.getName() + " " + networkInterface.getDisplayName()); - boolean hasIp = false; - for (InetAddress address : Collections.list(networkInterface.getInetAddresses())) { - String ipAddress = address.getHostAddress(); - logger.debug("Found ip address " + ipAddress); - if (!ips.contains(ipAddress)) { - ips.add(ipAddress); - } - hasIp = true; - } - - if (isWindowsIPv4) { //extra check for windows IPv4 preferred environment, see https://github.com/librato/joboe/pull/1090 for details - NicStatus status = nicStatusMap.get(networkInterface.getDisplayName()); - logger.debug("Checking " + networkInterface.getName() + ", " + networkInterface.getDisplayName() + ", status=" + status); - if (!(NicStatus.UP.equals(status) || NicStatus.DISCONNECTED.equals(status))) { - // ignore disabled/null NIC on Windows when "-Djava.net.preferIPv4Stack=true" is set - logger.debug("Ignore disabled/null network adapter " + networkInterface.getDisplayName() + ", status=" + status); - continue; - } - // We cannot simply filter out NICs without an IP for all the scenarios. This is because if an NIC is DISCONNECTED, it will have - // some kind of `link local` IP address (169.254. 0.0/16). The link local IP can be fetched by the Go API (used by the - // host agent) but not by the Java Windows API when `java.net.preferIPv4Stack`=true. - // Therefore, if the isWindowsIPv4 is true (check that when it's true), we'll accept the DISCONNECTED NIC without - // considering if it has an IP. For all other cases, that NIC will be filtered out if it doesn't have an IP address. - if (NicStatus.UP.equals(status) && !hasIp) { - logger.debug("Ignore network adapter which is up but no IP assigned: " + networkInterface.getDisplayName()); - continue; - } - } else if (!hasIp){ - logger.debug("Ignore network adapter without an IP: " + networkInterface.getName()); - continue; - } - //add mac addresses too - byte[] hwAddr = networkInterface.getHardwareAddress(); - if ((hwAddr != null) && (hwAddr.length != 0)) { - String macAddress = getMacAddressFromBytes(hwAddr); - logger.debug("Found MAC address " + macAddress); - if (!macAddresses.contains(macAddress)) { - macAddresses.add(macAddress); - } - } - } - } catch (NoSuchMethodError e) { - logger.debug("Failed to get network info for " + networkInterface.getName() + ", probably running JDK 1.5 or earlier"); - } catch (SocketException e) { - logger.debug("Failed to get network info for " + networkInterface.getName() + ":" + e.getMessage()); - } - } - logger.debug("All MAC addresses accepted: " + Arrays.toString(macAddresses.toArray())); - return new NetworkAddressInfo(ips, macAddresses); - } catch (SocketException e) { - logger.warn("Failed to get network info : " + e.getMessage()); - } - return null; - } - - /** - * Determines whether a network interface is physical (for Linux only). - * - * By our definition, a network interface is considered physical if its link in /sys/class/net does NOT contain "/virtual/" - * https://github.com/librato/joboe/issues/728 - * - * Take note that this definition is different from NetworkInterface.isVirtual() - * - * @param networkInterface - * @return - */ - private static boolean isPhysicalInterface(NetworkInterface networkInterface) { - if (osType != HostInfoUtils.OsType.LINUX) { //not applicable to non-linux systems, consider all interfaces physical - return true; - } - - //cannot use java.nio.file.Files.readSymbolicLink as it's not available in jdk 1.6 - String interfaceFilePath = "/sys/class/net/" + networkInterface.getName(); - File interfaceFile = new File(interfaceFilePath); - try { - return !interfaceFile.getCanonicalPath().contains("/virtual/"); - } catch (IOException e) { - logger.warn("Error identifying network interface in " + interfaceFilePath + " message : " + e.getMessage(), e); - return true; //having problem identifying the interface, treat it as physical - } - } - - /** - * To detect whether it is a ghost Microsoft Hyper-V Network Adapter. - * - * Since in IPv4 preferred environment, `NetworkInterface.getAll` might return ghost Microsoft Hyper-V Network Adapter - * - * https://swicloud.atlassian.net/browse/AO-14670 for details - * @param networkInterface - * @return false if it's NOT a Microsoft Hyper-V Network Adapter or it's UP - */ - private static boolean isGhostHyperV(NetworkInterface networkInterface) { - final String hyperVPrefix = "Microsoft Hyper-V Network Adapter"; - try { - String displayName = networkInterface.getDisplayName(); - return displayName != null && displayName.startsWith(hyperVPrefix) && !networkInterface.isUp(); - } catch (SocketException e) { - logger.debug("Cannot call isUp on " + networkInterface.getDisplayName(), e); - return false; - } - } - - private static String getMacAddressFromBytes(byte[] bytes) { - StringBuilder sb = new StringBuilder(18); - for (byte b : bytes) { - if (sb.length() > 0) - sb.append(':'); - sb.append(String.format("%02x", b)); - } - return sb.toString().toUpperCase(); - } - - @Override - public synchronized String getHostName() { - if (hostname == null) { //only load host name on the first time as we wish to minimize spawning processes - hostname = loadHostName(); - } - return hostname; - } - - @Override - public synchronized HostId getHostId() { - if (hostId == null) { - Metadata existingMetdataContext = null; - ScopeContextSnapshot scopeContextSnapshot = null; - try { - existingMetdataContext = Context.getMetadata(); - scopeContextSnapshot = ScopeManager.INSTANCE.getSnapshot(); - - Context.clearMetadata(); //make sure our init route does not accidentally trigger tracing instrumentations - ScopeManager.INSTANCE.removeAllScopes(); //make sure no scope is active for this thread - - //synchronously get it once first to ensure it's available at the return statement - hostId = buildHostId(); - //also start the background checker here - startHostIdChecker(); - } finally { - Context.setMetadata(existingMetdataContext); //set the existing context back - scopeContextSnapshot.restore(); - } - } - return hostId; - } - - public static String loadHostName() { - String hostName = loadHostNameFromExec(); - - if (hostName != null) { - return hostName; - } - - hostName = loadHostNameFromInetAddress(); - - if (hostName != null) { - return hostName; - } - - // We've failed to get an IP address, so as a last resort... - hostName = "unknown_hostname"; - return hostName; - } - - /** - * This was copied from JAgentInfo.java - * - * Returns system host name using external 'hostname' command. - * - * This feels lame, but there is no other way to get a hostname that definitively matches - * the gethostname() C library function we use elsewhere (liboboe, tracelyzer, etc.) without - * resorting to JNI. We only do this at startup so I think we can live with it. - * - * 'InetAddress.getHostName()' and 'getCanonicalHostName()' may vary or fail based on - * DNS settings, /etc/hosts settings, etc. and just aren't guaranteed to be the same - * as gethostname(), even though on many systems they are. - * - * Also see http://stackoverflow.com/questions/7348711/recommended-way-to-get-hostname-in-java - */ - private static String loadHostNameFromExec() { - try { - return ExecUtils.exec("hostname"); - } catch (Exception e) { - //in some "slim" os, it might not have `hostname`. For example Orcale linux slim - logger.info("Failed to obtain host name from exec `hostname` : " + e.getMessage()); - return null; - } - } - - /** - * This was copied from JAgentInfo.java - * @return - */ - private static String loadHostNameFromInetAddress() { - try { - InetAddress addr = InetAddress.getLocalHost(); - return addr.getCanonicalHostName(); - } catch(UnknownHostException hostEx) { - // Our hostname doesn't resolve, likely a mis-configured host, so fallback to using the first non-loopback IP address - try { - Enumeration netInts = NetworkInterface.getNetworkInterfaces(); - NetworkInterface netInt; - Enumeration addrs; - InetAddress addr; - - while (netInts.hasMoreElements()) { - netInt = netInts.nextElement(); - addrs = netInt.getInetAddresses(); - - while (addrs.hasMoreElements()) { - addr = addrs.nextElement(); - - if (!addr.isLoopbackAddress() && !addr.isLinkLocalAddress()) { - return addr.getHostAddress(); - } - } - } - - } catch(SocketException socketEx) { - logger.warn("Unable to retrieve network interfaces", socketEx); - } - - return null; - } - } - - public static String getDistro() { - if (!checkedDistro) { - if (osType == HostInfoUtils.OsType.LINUX) { - distro = getLinuxDistro(); - } else if (osType == HostInfoUtils.OsType.WINDOWS) { - distro = getWindowsDistro(); - } - checkedDistro = true; - } - return distro; //could be null for unsupported system - } - - - @Override - /** - * Get a map of host information - * @return - */ - public Map getHostMetadata() { - HashMap infoMap = new HashMap(); - - String hostnameAlias = (String) ConfigManager.getConfig(ConfigProperty.AGENT_HOSTNAME_ALIAS); - if (hostnameAlias != null) { - infoMap.put(HOSTNAME_ALIAS_KEY, hostnameAlias); - } - - addOsInfo(infoMap); - addNetworkAddresses(infoMap); - - return infoMap; - } - - private static void addOsInfo(Map infoMap) { - infoMap.put("UnameSysName", osType.getLabel()); - infoMap.put("UnameVersion", ManagementFactory.getOperatingSystemMXBean().getVersion()); - - String distro = getDistro(); - if (distro != null) { - infoMap.put("Distro", distro); - } - } - - private void addNetworkAddresses(Map infoMap) { - NetworkAddressInfo networkInfo = getNetworkAddressInfo(); - if (networkInfo != null) { - infoMap.put("IPAddresses", networkInfo.getIpAddresses()); - } - } - - /** - * - * Identifies the distro value on a Linux system - * - * Code logic copied from https://github.com/librato/oboe/blob/a3dd998e7ea239e3d5e5c7ece8c635c3ff61c903/liboboe/reporter/ssl.cc#L559 - * @return - */ - private static String getLinuxDistro() { - // Note: Order of checking is important because some distros share same file names but with different function. - // Keep this order: redhat based -> ubuntu -> debian - - BufferedReader fileReader = null; - - try { - if ((fileReader = getFileReader(DistroType.REDHAT_BASED)) != null) { - // Redhat, CentOS, Fedora - return getRedHatBasedDistro(fileReader); - } else if ((fileReader = getFileReader(DistroType.AMAZON)) != null) { - // Amazon Linux - return getAmazonLinuxDistro(fileReader); - } else if ((fileReader = getFileReader(DistroType.UBUNTU)) != null) { - // Ubuntu - return getUbuntuDistro(fileReader); - } else if ((fileReader = getFileReader(DistroType.DEBIAN)) != null) { - // Debian - return getDebianDistro(fileReader); - } else if ((fileReader = getFileReader(DistroType.SUSE)) != null) { - // Novell SuSE - return getNovellSuseDistro(fileReader); - } else if ((fileReader = getFileReader(DistroType.SLACKWARE)) != null) { - // Slackware - return getSlackwareDistro(fileReader); - } else if ((fileReader = getFileReader(DistroType.SLACKWARE)) != null) { - return getGentooDistro(fileReader); - } else { - return "Unknown"; - } - } catch (IOException e) { - logger.warn("Problem reading distro file : " + e.getMessage(), e); - return "Unknown"; - } finally { - if (fileReader != null) { - try { - fileReader.close(); - } catch (IOException e) { - logger.warn(e.getMessage(), e); - } - } - } - } - - private static String getWindowsDistro() { - return ManagementFactory.getOperatingSystemMXBean().getName(); - } - - static String getGentooDistro(BufferedReader fileReader) throws IOException { - String line; - return (line = fileReader.readLine()) != null ? line : "Gentoo unknown"; - } - - static String getSlackwareDistro(BufferedReader fileReader) throws IOException { - String line; - return (line = fileReader.readLine()) != null ? line : "Slackware unknown"; - } - - static String getNovellSuseDistro(BufferedReader fileReader) throws IOException { - String line; - return (line = fileReader.readLine()) != null ? line : "Novell SuSE unknown"; - } - - static String getDebianDistro(BufferedReader fileReader) throws IOException { - String line; - return (line = fileReader.readLine()) != null ? ("Debian " + line) : "Debian unknown"; - } - - static String getRedHatBasedDistro(BufferedReader fileReader) throws IOException { - String line; - return (line = fileReader.readLine()) != null ? line : "Red Hat based unknown"; - } - - static String getAmazonLinuxDistro(BufferedReader fileReader) throws IOException { - String line; - if ((line = fileReader.readLine()) != null) { - String[] tokens = line.split(":"); - if (tokens.length >= 5) { - String patch = tokens[4]; - return "Amzn Linux " + patch; - } - } - return "Amzn Linux unknown"; - } - - static String getUbuntuDistro(BufferedReader fileReader) throws IOException { - String line; - while ((line = fileReader.readLine()) != null) { - String[] tokens = line.split("="); - if (tokens.length >= 2 && "DISTRIB_DESCRIPTION".equals(tokens[0])) { - // trim trailing/leading quotes - String patch = tokens[1]; - if (patch.startsWith("\"")) { - patch = patch.substring(1); - } - if (patch.endsWith("\"")) { - patch = patch.substring(0, patch.length() - 1); - } - - return patch; - } - } - return "Ubuntu unknown"; - } - - - - private static BufferedReader getFileReader(DistroType distroType) { - String path = DISTRO_FILE_NAMES.get(distroType); - if (path == null) { - logger.warn("Unexpected distroType lookup: " + distroType); - return null; - } - File file = new File(path); - try { - return file.exists() ? new BufferedReader(new FileReader(file)) : null; - } catch (FileNotFoundException e) { - logger.warn(e.getMessage(), e); - return null; - } - } - - private void startHostIdChecker() { - ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1, DaemonThreadFactory.newInstance("host-id-checker")); - //align to minute, figure out the delay in ms - long delay = 60 * 1000 - System.currentTimeMillis() % (60 * 1000); - executorService.scheduleAtFixedRate(new Runnable() { - public void run() { - hostId = buildHostId(); - } - }, delay, HOST_ID_CHECK_INTERVAL * 1000, TimeUnit.MILLISECONDS); - } - - private HostId buildHostId() { - NetworkAddressInfo networkAddressInfo = getNetworkAddressInfo(); - List macAddresses = networkAddressInfo != null ? networkAddressInfo.getMacAddresses() : Collections.emptyList(); - //assume all that uses HostInfoUtils are persistent server, can be improved to recognize different types later - return new HostId(getHostName(), JavaProcessUtils.getPid(), macAddresses, Ec2InstanceReader.getInstanceId(), Ec2InstanceReader.getAvailabilityZone(), DockerInfoReader.getDockerId(), HerokuDynoReader.getDynoId(), AzureReader.getInstanceId(), HostType.PERSISTENT); - } - - public static class Ec2InstanceReader { - private static final int TIMEOUT_DEFAULT = 1000; - private static final int TIMEOUT_MIN = 0; //do not wait at all, disable retrieval - private static final int TIMEOUT_MAX = 3000; - - private static final int TIMEOUT = getTimeout(); - - private static int getTimeout() { - Integer configValue = (Integer) ConfigManager.getConfig(ConfigProperty.AGENT_EC2_METADATA_TIMEOUT); - if (configValue == null) { - return TIMEOUT_DEFAULT; - } else if (configValue > TIMEOUT_MAX) { - logger.warn("EC2 metadata read timeout cannot be greater than " + TIMEOUT_MAX + " millisec but found [" + configValue + "]. Using " + TIMEOUT_MAX + " instead."); - return TIMEOUT_MAX; - } else if (configValue < TIMEOUT_MIN) { - logger.warn("EC2 metadata read timeout cannot be smaller than " + TIMEOUT_MIN + " millisec but found [" + configValue + "]. Using " + TIMEOUT_MIN + " instead, which essentially disable reading EC2 metadata"); - return TIMEOUT_MIN; - } else { - return configValue; - } - } - - /** - * System property for overriding the Amazon EC2 Instance Metadata Service - * endpoint. - */ - public static final String EC2_METADATA_SERVICE_OVERRIDE_SYSTEM_PROPERTY = "com.amazonaws.sdk.ec2MetadataServiceEndpointOverride"; - - private static final String EC2_METADATA_SERVICE_URL = "http://169.254.169.254"; - private static final String INSTANCE_ID_PATH = "latest/meta-data/instance-id"; - private static final String AVAILABILITY_ZONE_PATH = "latest/meta-data/placement/availability-zone"; - - private String instanceId; - private String availabilityZone; - - private static final Ec2InstanceReader SINGLETON = new Ec2InstanceReader(); - - public static String getInstanceId() { - return SINGLETON.instanceId; - } - - public static String getAvailabilityZone() { - return SINGLETON.availabilityZone; - } - - private Ec2InstanceReader() { - initialize(); - } - - private void initialize() { - if (TIMEOUT == TIMEOUT_MIN) { //disable reader - return; - } - instanceId = getResourceOnEndpoint(INSTANCE_ID_PATH); - if (instanceId != null) { //only proceed if instance id can be found - availabilityZone = getResourceOnEndpoint(AVAILABILITY_ZONE_PATH); - logger.debug("Found EC2 instance id " + instanceId + " availability zone: " + availabilityZone); - } - } - - private static String getResourceOnEndpoint(String relativePath) { - HttpURLConnection connection = null; - BufferedReader reader = null; - try { - URI uri = new URI(getMetadataHost() + "/" + relativePath); - connection = (HttpURLConnection) uri.toURL().openConnection(Proxy.NO_PROXY); - connection.setConnectTimeout(TIMEOUT); - connection.setReadTimeout(TIMEOUT); - - int statusCode = connection.getResponseCode(); - - if (statusCode == HttpURLConnection.HTTP_OK) { - reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); - return reader.readLine(); - } else { - return null; - } - } catch (IOException e) { - logger.debug("Timeout on reading EC2 metadata after waiting for [" + TIMEOUT + "] milliseconds. Probably not an EC2 instance"); - return null; - } catch (URISyntaxException e) { - logger.warn(e.getMessage(), e); - return null; - } finally { - if (reader != null) { - try { - reader.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - if (connection != null) { - connection.disconnect(); - } - } - } - - private static String getMetadataHost() { - String host = System.getProperty(EC2_METADATA_SERVICE_OVERRIDE_SYSTEM_PROPERTY); - return host != null ? host : EC2_METADATA_SERVICE_URL; - } - } - - public static class DockerInfoReader { - public static final String DEFAULT_LINUX_DOCKER_FILE_LOCATION = "/proc/self/cgroup"; - private static final int DOCKER_ID_LENGTH = 64; - private static final Set DOCKER_CGROUP_PATH_TOKEN = new HashSet(); - - static { - DOCKER_CGROUP_PATH_TOKEN.add("docker"); - DOCKER_CGROUP_PATH_TOKEN.add("ecs"); - DOCKER_CGROUP_PATH_TOKEN.add("kubepods"); - DOCKER_CGROUP_PATH_TOKEN.add("docker.service"); - } - - private String dockerId; - - static final DockerInfoReader SINGLETON = new DockerInfoReader(); - - public static String getDockerId() { - return SINGLETON.dockerId; - } - - private DockerInfoReader() { - if (osType == HostInfoUtils.OsType.LINUX) { - initializeLinux(DEFAULT_LINUX_DOCKER_FILE_LOCATION); - } else if (osType == HostInfoUtils.OsType.WINDOWS) { - initializeWindows(); - } - - if (dockerId != null) { - logger.debug("Found Docker instance ID :" + this.dockerId); - } else { - logger.debug("Cannot locate Docker id, not a Docker container"); - } - } - - void initializeLinux(String dockerFileLocation) { - BufferedReader reader = null; - - try { - reader = new BufferedReader(new FileReader(dockerFileLocation)); - String line; - - // refers to logic from c-lib https://github.com/librato/oboe/blob/af14cd2daaba7b6c21fa4aa780b222f02fe95f07/liboboe/reporter/ssl.cc#L1134 - // iterate over each line and look for the keyword "docker" or "ecs" - while ((line = reader.readLine()) != null) { - List tokens = Arrays.asList(line.split("/")); - if (!Collections.disjoint(tokens, DOCKER_CGROUP_PATH_TOKEN)) { //if the tokens contains any of the valid "docker" label segments in it - for (String token : tokens) { - if (token.length() == DOCKER_ID_LENGTH) { - dockerId = token; - return; - } - } - } - } - - dockerId = null; - } catch (FileNotFoundException e) { - dockerId = null; - logger.debug("Cannot locate docker id as file " + dockerFileLocation + " cannot be found : " + e.getMessage()); - } catch (IOException e) { - dockerId = null; - logger.debug("Cannot locate docker id as file " + dockerFileLocation + " throws IOException : " + e.getMessage()); - } finally { - if (reader != null) { - try { - reader.close(); - } catch (IOException e) { - logger.warn(e.getMessage(), e); - } - } - } - } - - /** - * Initializes Windows docker ID if the java process is running within a Windows docker container - * - * Determines if it is a Windows container by checking if `cexecsvc` exists in `powershell get-process` - * - * If so, set the host name as Docker ID - * - */ - private void initializeWindows() { - try { - String getContainerTypeResult = ExecUtils.exec("powershell Get-ItemProperty -Path HKLM:\\SYSTEM\\CurrentControlSet\\Control\\ -Name \"ContainerType\""); - if (getContainerTypeResult != null && !"".equals(getContainerTypeResult)) { - dockerId = AgentHostInfoReader.INSTANCE.getHostName(); - - } - } catch (Exception e) { - logger.info("Failed to identify whether this windows system is a docker container: " + e.getMessage()); - } - } - } - - - public static class HerokuDynoReader { - private static final String DYNO_ENV_VARIABLE = "DYNO"; - private static final HerokuDynoReader SINGLETON = new HerokuDynoReader(); - - private final String dynoId; - - public static String getDynoId() { - return SINGLETON.dynoId; - } - - private HerokuDynoReader() { - this.dynoId = System.getenv(DYNO_ENV_VARIABLE); - if (this.dynoId != null) { - logger.debug("Found Heroku Dyno ID: " + this.dynoId); - } - } - } - - public static class AzureReader { - private static final String INSTANCE_ID_ENV_VARIABLE = "WEBSITE_INSTANCE_ID"; - private static final AzureReader SINGLETON = new AzureReader(); - - private final String instanceId; - - public static String getInstanceId() { - return SINGLETON.instanceId; - } - - private AzureReader() { - this.instanceId = System.getenv(INSTANCE_ID_ENV_VARIABLE); - if (this.instanceId != null) { - logger.debug("Found Azure instance ID: " + this.instanceId); - } - } - } -} diff --git a/agent/src/main/java/com/tracelytics/monitor/SystemCollector.java b/agent/src/main/java/com/tracelytics/monitor/SystemCollector.java deleted file mode 100644 index 194a5ae9..00000000 --- a/agent/src/main/java/com/tracelytics/monitor/SystemCollector.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.tracelytics.monitor; - -import java.util.Map; - -import com.tracelytics.logging.Logger; -import com.tracelytics.logging.LoggerFactory; - -/** - * Collects information and returns as maps. Take note that this collector only collects data. - * How the collected data are to be reported is defined by the {@link SystemReporter} - * - * @param Type of the collected data map Key - * @param Type of the collected data map Value - * @author Patson Luk - * - */ -public abstract class SystemCollector { - protected static Logger logger = LoggerFactory.getLogger(); - - /** - * Collects information and return via a Map. Take note that based on the concrete implementation, this method might only return part of the data within a collection cycle - * - * @return a Map with data collected. - * @throws Exception - * @see {@link SystemMonitor#hasMoreData()} - */ - protected abstract Map collect() throws Exception; -} diff --git a/agent/src/main/java/com/tracelytics/monitor/SystemMonitor.java b/agent/src/main/java/com/tracelytics/monitor/SystemMonitor.java deleted file mode 100644 index 379e1fb5..00000000 --- a/agent/src/main/java/com/tracelytics/monitor/SystemMonitor.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.tracelytics.monitor; - -import java.util.Map; - -import com.tracelytics.logging.Logger; -import com.tracelytics.logging.LoggerFactory; - -/** - * An abstract monitor that collects and reports system information periodically based on the interval provided in the ctor. - *

- * Each concrete child monitor provides exactly 1 {@link SystemCollector} and 1 {@link SystemReporter} - *

- * A Monitor runs cycles as as below: - *

    - *
  1. {@link SystemCollector#startCollection()} is invoked to notify the {@code SystemCollector} that the collection cycle has started
  2. - *
  3. {@link SystemReporter#preReportData()} is invoked such that {@code SystemReporter} can perform tasks before data reporting
  4. - *
  5. {@link SystemCollector#hasMoreData()} is invoked, if true, keep looping step 4. Otherwise goto step 5
  6. - *
  7. {@link SystemCollector#collect()} is invoked, the returned value is then passed to {@link SystemReporter#reportData(Map)}
  8. - *
  9. {@link SystemReporter#postReportData()} is invoked such that {@code SystemReporter} can perform tasks after data reporting
  10. - *
  11. Sleep for the amount of time defined in {@code interval}
  12. - *
  13. Go back to step 1 once the sleep is over
  14. - *
- *

- * Take note that we want to have the {@link SystemCollector#hasMoreData()} and {@link SystemCollector#collect()} interweave with - * {@link SystemReporter#reportData(Map)} as this allows: - *

    - *
  • Stop data collection if the {@code SystemReporter} fails to further reports events in this cycle
  • - *
  • Operation unit on each collection, for example separate event generated for each {@link SystemCollector#collect()} - *
- *

- * This is created and managed by SystemMonitorFactory and SystemMonitorController - *

- * @param Type of the collected data map Key - * @param Type of the collected data map Value - * @see SystemCollector - * @see SystemReporter - * - * @author Patson Luk - */ - -public abstract class SystemMonitor implements Runnable { - protected static final Logger logger = LoggerFactory.getLogger(); - - private boolean stopSignalled = false; - - protected final SystemCollector collector; - protected final SystemReporter reporter; - - public SystemMonitor(SystemCollector collector, SystemReporter reporter) { - super(); - this.collector = collector; - this.reporter = reporter; - } - - /** - * Starts the data collection/report cycle - */ - public final void run() { - try { - if (collector == null || reporter == null) { - logger.warn("Cannot find valid collector or reporter for [ " + getClass().getName() + "]. This monitor is skipped "); - return; - } - - while (!stopSignalled) { - waitForNextCycle(); - executeCycle(); - } - } catch (InterruptedException e) { - logger.debug(getMonitorName() + " interrupted. Message: " + e.getMessage()); - } - } - - /** - * Monitoring interval in millisec - * @return - */ - protected abstract long getInterval(); - - protected abstract String getMonitorName() ; - - protected void executeCycle() { - if (reporter == null || collector == null) { - return ; - } - - logger.trace("Starting reporting cycle of monitor [" + getMonitorName() + "]"); - reporter.preReportData(); - - try { - Map collectedData = collector.collect(); - - if (collectedData != null && !collectedData.isEmpty()) { - reporter.reportData(collectedData, getInterval()); - } - } catch (SystemReporterException e) { - logger.warn(e.getMessage()); - } catch (Exception e) { - logger.warn(e.getMessage(), e); - } - - reporter.postReportData(); - } - - /** - * Blocks until it's time for next collection/report cycle - * @throws Exception - */ - protected abstract void waitForNextCycle() throws InterruptedException; - - public void close() { - stopSignalled = true; - } -} - diff --git a/agent/src/main/java/com/tracelytics/monitor/SystemMonitorController.java b/agent/src/main/java/com/tracelytics/monitor/SystemMonitorController.java deleted file mode 100644 index 86b30448..00000000 --- a/agent/src/main/java/com/tracelytics/monitor/SystemMonitorController.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.tracelytics.monitor; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import com.tracelytics.agent.Agent; -import com.tracelytics.agent.AppEnvironment; -import com.tracelytics.ext.javassist.bytecode.ClassFile; -import com.tracelytics.joboe.config.ConfigContainer; -import com.tracelytics.joboe.config.ConfigGroup; -import com.tracelytics.joboe.config.ConfigManager; -import com.tracelytics.joboe.config.ConfigProperty; -import com.tracelytics.logging.Logger; -import com.tracelytics.logging.LoggerFactory; -import com.tracelytics.util.DaemonThreadFactory; - -/** - * The controller of the System Monitor module. - *

- * Manages a list of {@code SystemMonitor} for system monitoring. Take note that this controller can only be started once per JVM - *

- * Each {@code SystemMonitor} is a self contained Runnable with it's own interval, the behavior is implemented in {@link SystemMonitor#run()}. - * The {@code SystemMonitor} defines {@link SystemCollector} and {@link SystemReporter} in order to collect and report data. For detailed information, - * please refer to documentation in {@link SystemMonitor}. - * - * - * The construction of the monitors is implemented in {@link SystemMonitorFactoryImpl}. Therefore to attach extra {@code SystemMonitor}, add the code logic in - * that factory. - * - * @see SystemMonitor - * - * @author Patson Luk - * - */ -public class SystemMonitorController { - protected static final Logger logger = LoggerFactory.getLogger(); - - private static volatile ExecutorService executor; - private static List> monitors = new ArrayList>(); - private static ConfigContainer configs; - - static { - configs = ConfigManager.getConfigs(ConfigGroup.MONITOR); - } - - /** - * Starts up the system monitoring if some particular prerequisites are met. - */ - public static synchronized void conditionalStart() { - // We'll try to start up the system monitor daemon earlier in the premain if AGENT_SYSMON_EARLY_START is set - // to true. However, due to possible classloading deadlock issues, the environment with JBoss or old JDK - // versions (<1.7) are excluded. - Boolean sysMonEarlyStart = (Boolean) ConfigManager.getConfig(ConfigProperty.AGENT_SYSMON_EARLY_START); - sysMonEarlyStart = sysMonEarlyStart == null?false:sysMonEarlyStart; - - if(sysMonEarlyStart - && !"jboss".equals(AppEnvironment.getAppServerName()) - && ClassFile.MAJOR_VERSION >= ClassFile.JAVA_7) { - SystemMonitorController.start(); - } - } - - /** - * Starts the System monitoring. Should only be called once. If more than once has been called, the other calls would be ignored - */ - public static synchronized void start() { - if (executor == null) { - if (configs == null) { - logger.error("Cannot start the System Monitors! The property/config is not found!"); - return; - } - - logger.debug("Start creating metrics collectors"); - - List> monitors = new SystemMonitorFactoryImpl(configs).buildMonitors(); - - executor = Executors.newCachedThreadPool(DaemonThreadFactory.newInstance("system-monitor")); - - for (SystemMonitor monitor : monitors) { - executor.execute(monitor); - } - - SystemMonitorController.monitors.addAll(monitors); - - logger.debug("Finished creating System monitors"); - } else { - logger.debug("System Monitor has already been started!"); - } - } - - public static synchronized void stop() { - for (SystemMonitor monitor : monitors) { - monitor.close(); - } - - if (executor != null) { - executor.shutdownNow(); - } - executor = null; - } -} diff --git a/agent/src/main/java/com/tracelytics/monitor/SystemMonitorFactory.java b/agent/src/main/java/com/tracelytics/monitor/SystemMonitorFactory.java deleted file mode 100644 index cf8d1782..00000000 --- a/agent/src/main/java/com/tracelytics/monitor/SystemMonitorFactory.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.tracelytics.monitor; - -import java.util.List; - -public interface SystemMonitorFactory { - public List> buildMonitors(); -} \ No newline at end of file diff --git a/agent/src/main/java/com/tracelytics/monitor/SystemMonitorFactoryImpl.java b/agent/src/main/java/com/tracelytics/monitor/SystemMonitorFactoryImpl.java deleted file mode 100644 index 386e0ca4..00000000 --- a/agent/src/main/java/com/tracelytics/monitor/SystemMonitorFactoryImpl.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.tracelytics.monitor; - -import com.tracelytics.joboe.config.ConfigContainer; -import com.tracelytics.logging.Logger; -import com.tracelytics.logging.LoggerFactory; -import com.tracelytics.monitor.framework.FrameworkInfoMonitor; -import com.tracelytics.monitor.metrics.MetricsMonitor; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * Factory that creates the {@link SystemMonitor}. Currently it only supports building a full list of {@code SystemMonitor}s based on the configurations in - * {@code ConfigContainer} - * - * @author Patson Luk - * - */ - -public class SystemMonitorFactoryImpl implements SystemMonitorFactory { - protected static final Logger logger = LoggerFactory.getLogger(); - - private ConfigContainer configs; - - public SystemMonitorFactoryImpl(ConfigContainer configs) { - this.configs = configs; - } - - /** - * Build a list of {@code SystemMonitor}s. To attach more {@code SystemMonitor} to the monitoring system, add the construction in this method - * - * @return list of {@code SystemMonitor}s based on the configurations provided by the factory constructor - */ - public List> buildMonitors() { - List> monitors = new ArrayList>(); - - //Build Framework info collector - FrameworkInfoMonitor frameworkInfoMonitor = buildFrameworkInfoMonitor(); - if (frameworkInfoMonitor != null) { - monitors.add(frameworkInfoMonitor); - } - - //Build Metrics monitor - MetricsMonitor metricsMonitor = buildMetricsMonitor(); - if (metricsMonitor != null) { - monitors.add(metricsMonitor); - } - - - return Collections.unmodifiableList(monitors); - } - - private FrameworkInfoMonitor buildFrameworkInfoMonitor() { - try { - return new FrameworkInfoMonitor(configs); - } catch (Exception e) { - logger.warn("Failed to build Framework Monitor! " + e.getMessage()); - return null; - } - } - - private MetricsMonitor buildMetricsMonitor() { - try { - return MetricsMonitor.buildInstance(configs); - } catch (Exception e) { - logger.warn("Failed to build Metrics Monitor! " + e.getMessage()); - return null; - } - } -} diff --git a/agent/src/main/java/com/tracelytics/monitor/SystemMonitorWithFrequency.java b/agent/src/main/java/com/tracelytics/monitor/SystemMonitorWithFrequency.java deleted file mode 100644 index 74e6e154..00000000 --- a/agent/src/main/java/com/tracelytics/monitor/SystemMonitorWithFrequency.java +++ /dev/null @@ -1,126 +0,0 @@ -package com.tracelytics.monitor; - -import com.tracelytics.agent.Agent; -import com.tracelytics.joboe.config.InvalidConfigException; - -/** - * Controls reporting in better time precision. - * - * Instead of sleeping for an arbitrary amount of time in between cycles as in {@link SystemMonitorWithInterval}, - * it calculates the exact amount of time required to reach the next "valid mark" in time. - * - * A valid mark is defined by the timeUnit and frequency provided via the constructor. - * It is either at the beginning of the timeUnit or whole increments to it calculated by the frequency - * - * For example, - * for timeUnit PER_HOUR with frequency 6, it will report at - * hh:00:00, hh:10:00, hh:20:00, hh:30:00, hh:40:00, hh:50:00 of each hour - * for timeUnit PER_MINUTE with frequency 2, it will report at - * hh:mm:00, hh:mm:30 of each minute - * - * Take note that the timeUnit should be divisible by the frequency - * - * @author pluk - * - * @param - * @param - */ -public abstract class SystemMonitorWithFrequency extends SystemMonitor { - protected long interval; //in millisec - private final long timeUnit; - private long wakeUpTime = 0; //next wakeUpTime to prevent duplicated reporting - - /** - * Constructs a System Monitor with precise timing. Take note that the timeUnit should be divisible by the frequency - * @param timeUnit the unit of time for the frequency - * @param frequency the frequency per timeUnit - * @throws InvalidConfigException timeUnit provided is not divisible by the frequency, for example PER_DAY (every 24 hours), is divisible by 6 but not 7 - */ - public SystemMonitorWithFrequency(TimeUnit timeUnit, int frequency, SystemCollector collector, SystemReporter reporter) throws InvalidConfigException { - super(collector, reporter); - setFrequency(timeUnit, frequency); - this.timeUnit = timeUnit.duration; - } - - - @Override - protected void waitForNextCycle() throws InterruptedException { - long sleepTime = getSleepTime(); - logger.trace("Waiting for next reporting cycle of [" + getMonitorName() + "]. Sleeping for [" + sleepTime + "] ms"); - Thread.sleep(sleepTime); //wait for next cycle - } - - protected final void setFrequency(TimeUnit timeUnit, int frequency) throws InvalidConfigException { - try { - interval = timeUnit.getInterval(frequency); - } catch (IllegalArgumentException e) { - throw new InvalidConfigException(e); - } - } - - /** - * Sets interval in milliseconds. Interval should be positive and either a divisor of timeUnit value or divisible by timeUnit value, - * which the timeUnit is provided at the constructor - * - * For example, if the timeUnit provided is PER_MINUTE then the timeUnit value is 60 * 1000 (in millisec). Therefore values such as - * 5000 (5 secs), 15000 (15 secs), 30000 (30 secs) are valid as they are divisor of 60000, also values such as - * 60000 (1 min), 120000 (2 mins), 600000 (10 mins) are also valid as they are divisible by 60000. - * - * If the interval provided is not valid, an {@link InvalidConfigException} would be thrown - * - * @param interval intervals in milliseconds - * @throws InvalidConfigException - */ - protected void setInterval(long interval) throws InvalidConfigException { - if (interval > 0 && (interval % timeUnit == 0 || timeUnit % interval == 0)) { //then it's a valid interval - this.interval = interval; - } else { - throw new InvalidConfigException("interval [" + interval + "] should be positive and be either a divisor of " + timeUnit + " or divisible by " + timeUnit); - } - } - - protected long getSleepTime() { - return getSleepTime(Agent.currentTimeStamp() / 1000); - } - - private long getSleepTime(long currentTimeInMillisec) { - //TODO to support PER_DAY ad PER_WEEK, an adjustment is required a Agent.currentTimeStamp reports epoch time that might not start at the 0th hour of the local date - long sleepTime = interval - currentTimeInMillisec % interval; //the remainder of current time modulus by interval gives how much time has passed since last mark, subtract this value from interval gives the time required to reach next mark - - if (currentTimeInMillisec + sleepTime == wakeUpTime) { //prevent problem with time drifting or very short operation (less than a millisec) - sleepTime += interval; //add 1 interval to avoid repeating on same wake up time - } - - wakeUpTime = currentTimeInMillisec + sleepTime; //update wakeUpTime for check on next call - - return sleepTime; - } - - @Override - public long getInterval() { - return interval; - } - - public enum TimeUnit { - PER_HOUR(60 * 60 * 1000), PER_MINUTE(60 * 1000), PER_SECOND(1 * 1000); - - private final int duration; //in millisec - - private TimeUnit(int duration) { - this.duration = duration; - } - - /** - * Gets interval in millisecond. For example on PER_HOUR with frequency 12, interval would be 5 minutes which is 300,000 ms - * @param frequency - * @return - */ - public int getInterval(int frequency) throws IllegalArgumentException { - if (duration % frequency != 0) { - throw new IllegalArgumentException("Invalid frequency " + frequency + ". Time unit [" + this + "] is not divisible by the frequency"); - } - return duration / frequency; - } - } -} - diff --git a/agent/src/main/java/com/tracelytics/monitor/SystemMonitorWithInterval.java b/agent/src/main/java/com/tracelytics/monitor/SystemMonitorWithInterval.java deleted file mode 100644 index ff652c01..00000000 --- a/agent/src/main/java/com/tracelytics/monitor/SystemMonitorWithInterval.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.tracelytics.monitor; - - -/** - * Simply sleeps for the interval defined in the constructor - * - * @author pluk - * - * @param - * @param - */ -public abstract class SystemMonitorWithInterval extends SystemMonitor { - protected static final long DEFAULT_INTERVAL = 30 * 1000; //By default, collect every 30 secs - private static final long MIN_INTERVAL = 30 * 1000; //30 secs as minimum, avoid excessive polling. At the moment we don't even store metrics in our backend at any more fine-grained intervals than 30 seconds. - - private long interval; - - /** - * - * @param interval the polling interval of the data collection. Take note that this is just a rough estimate, as it does not factor in the actual data collection time - */ - public SystemMonitorWithInterval(Long interval, SystemCollector collector, SystemReporter reporter) { - super(collector, reporter); - if (interval == null) { - this.interval = DEFAULT_INTERVAL; - } else if (interval.compareTo(MIN_INTERVAL) < 0) { - this.interval = MIN_INTERVAL; - logger.warn("Interval [" + interval + "] is invalid. Using default [" + MIN_INTERVAL + "] instead"); - } else { - this.interval = interval; - } - } - - @Override - protected void waitForNextCycle() throws InterruptedException { - long sleepTime = interval; - logger.trace("Waiting for next reporting cycle of [" + getMonitorName() + "]. Sleeping for [" + sleepTime + "] ms"); - Thread.sleep(interval); //wait for next cycle - } - - @Override - public long getInterval() { - return interval; - } - -} - diff --git a/agent/src/main/java/com/tracelytics/monitor/SystemReporter.java b/agent/src/main/java/com/tracelytics/monitor/SystemReporter.java deleted file mode 100644 index b14437c8..00000000 --- a/agent/src/main/java/com/tracelytics/monitor/SystemReporter.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.tracelytics.monitor; - -import java.util.Map; - -import com.tracelytics.logging.Logger; -import com.tracelytics.logging.LoggerFactory; - -/** - * Reports data collected by {@link SystemCollector}. Take note that this is not bound to any reporting method. Though the existing implementations all - * report {@link Event}, it does not have to be always the case. - * - * @param Type of the collected data map Key - * @param Type of the collected data map Value - * @author Patson Luk - * - */ -public abstract class SystemReporter { - protected Logger logger = LoggerFactory.getLogger(); - - public void preReportData() {} - public void postReportData() {} - - /** - * Reports data based on the input collectedData - * @param collectedData - * @param the interval for the collected data in millisec - * - * @throws SystemReporterException - */ - public abstract void reportData(Map collectedData, long interval) throws SystemReporterException; - - -} diff --git a/agent/src/main/java/com/tracelytics/monitor/SystemReporterException.java b/agent/src/main/java/com/tracelytics/monitor/SystemReporterException.java deleted file mode 100644 index 512dd1b2..00000000 --- a/agent/src/main/java/com/tracelytics/monitor/SystemReporterException.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.tracelytics.monitor; - -/** - * Used to raise exception for System monitor module - * @author Patson Luk - * - */ -public class SystemReporterException extends Exception { - public SystemReporterException(String message) { - super(message); - } -} diff --git a/agent/src/main/java/com/tracelytics/monitor/framework/FrameworkInfoCollector.java b/agent/src/main/java/com/tracelytics/monitor/framework/FrameworkInfoCollector.java deleted file mode 100644 index e6d943e1..00000000 --- a/agent/src/main/java/com/tracelytics/monitor/framework/FrameworkInfoCollector.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.tracelytics.monitor.framework; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import com.tracelytics.agent.FrameworkRecorder; -import com.tracelytics.agent.FrameworkRecorder.FrameworkInfo; -import com.tracelytics.joboe.config.ConfigManager; -import com.tracelytics.joboe.config.ConfigProperty; -import com.tracelytics.joboe.rpc.ClientException; -import com.tracelytics.monitor.SystemCollector; - -/** - * Collects Framework information extracted and recorded by {@link FrameworkRecorder} - * @author Patson Luk - * - */ -class FrameworkInfoCollector extends SystemCollector { - @Override - /** - * Goes through the pending frameworks, build the KVs for reporting - */ - protected Map collect() { - Set pendingFrameworks = FrameworkRecorder.consumePendingFrameworks(); - Map map = new HashMap(); - - for (FrameworkInfo info : pendingFrameworks) { - String frameworkPhrase = info.getId(); - frameworkPhrase = frameworkPhrase.trim().toLowerCase().replaceAll("[\\W]", "_"); - String key = "Java." + frameworkPhrase + ".Version"; - String version = info.getVersion(); - - map.put(key, version != null ? version : ""); - } - - return map; - } - -} diff --git a/agent/src/main/java/com/tracelytics/monitor/framework/FrameworkInfoMonitor.java b/agent/src/main/java/com/tracelytics/monitor/framework/FrameworkInfoMonitor.java deleted file mode 100644 index 9c817e4a..00000000 --- a/agent/src/main/java/com/tracelytics/monitor/framework/FrameworkInfoMonitor.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.tracelytics.monitor.framework; - -import com.tracelytics.joboe.config.ConfigContainer; -import com.tracelytics.joboe.config.InvalidConfigException; -import com.tracelytics.joboe.rpc.ClientException; -import com.tracelytics.monitor.SystemMonitorWithInterval; - -/** - * {@code SystemMonitor} for Framework info - * @author Patson Luk - * - */ -public class FrameworkInfoMonitor extends SystemMonitorWithInterval { - private static final long DEFAULT_INTERVAL = 60 * 1000; //every 1 min - - public FrameworkInfoMonitor(ConfigContainer configs) throws ClientException { - super(DEFAULT_INTERVAL, new FrameworkInfoCollector(), new FrameworkInfoReporter()); - } - - @Override - protected String getMonitorName() { - return "Framework Info Monitor"; - } - - -} diff --git a/agent/src/main/java/com/tracelytics/monitor/framework/FrameworkInfoReporter.java b/agent/src/main/java/com/tracelytics/monitor/framework/FrameworkInfoReporter.java deleted file mode 100644 index c54d0603..00000000 --- a/agent/src/main/java/com/tracelytics/monitor/framework/FrameworkInfoReporter.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.tracelytics.monitor.framework; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import com.tracelytics.joboe.config.ConfigManager; -import com.tracelytics.joboe.config.ConfigProperty; -import com.tracelytics.joboe.rpc.Client; -import com.tracelytics.joboe.rpc.Result; -import com.tracelytics.joboe.rpc.RpcClientManager; -import com.tracelytics.joboe.rpc.RpcClientManager.OperationType; -import com.tracelytics.joboe.rpc.ClientException; -import com.tracelytics.joboe.rpc.ClientLoggingCallback; -import com.tracelytics.monitor.SystemReporter; -import com.tracelytics.monitor.SystemReporterException; - -/** - * {@code SystemReporter} for Framework info - * @author Patson Luk - * - */ -class FrameworkInfoReporter extends SystemReporter { - private Map frameworkKvs; - private final Client rpcClient; - - private ClientLoggingCallback loggingCallback = new ClientLoggingCallback("framework init"); - - public FrameworkInfoReporter() throws ClientException { - this(RpcClientManager.getClient(OperationType.METRICS)); - } - - FrameworkInfoReporter(Client rpcClient) { - this.rpcClient = rpcClient; - } - - @Override - public void preReportData() { - frameworkKvs = new HashMap(); //reset - } - - @Override - public void postReportData() { - if (!frameworkKvs.isEmpty()) { - String layerName = (String) ConfigManager.getConfig(ConfigProperty.AGENT_LAYER); - - Map frameworkInfo = new HashMap(); - frameworkInfo.put("__Init", true); - frameworkInfo.put("Layer", layerName); - - frameworkInfo.putAll(frameworkKvs); - - try { - rpcClient.postStatus(Collections.singletonList(frameworkInfo), loggingCallback); - } catch (ClientException e) { - logger.debug("Failed reporting Framework Info : " + e.getMessage()); - } - - logger.debug(getClass().getSimpleName() + " reported jar with manifest info of size [" + frameworkKvs.size() + "]"); - } - } - - - @Override - public void reportData(Map collectedData, long interval) { - frameworkKvs.putAll(collectedData); //buffer up the framework to send them in one call for better performance - } - -} diff --git a/agent/src/main/java/com/tracelytics/monitor/jmx/processor/AttributeProcessor.java b/agent/src/main/java/com/tracelytics/monitor/jmx/processor/AttributeProcessor.java deleted file mode 100644 index 751f757f..00000000 --- a/agent/src/main/java/com/tracelytics/monitor/jmx/processor/AttributeProcessor.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.tracelytics.monitor.jmx.processor; - -import java.lang.reflect.Array; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.management.MBeanServer; -import javax.management.ObjectName; -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.TabularData; - -import com.tracelytics.ext.google.common.primitives.Primitives; -import com.tracelytics.logging.Logger; -import com.tracelytics.logging.LoggerFactory; - -/** - * Base class of processing an attribute. Processors are responsible to process the JMX attribute and convert it into a map filled with keys and values. - * - * The concrete child class implements the actual logic and behavior of the processing - * - * @author Patson Luk - * - */ -public abstract class AttributeProcessor { - protected static final Logger logger = LoggerFactory.getLogger(); - - protected MBeanServer mBeanServer; - - public AttributeProcessor(MBeanServer mBeanServer) { - super(); - this.mBeanServer = mBeanServer; - } - - /** - * Appends an attribute object to the input container map, take note that the object will be flattened if it is of type CompositeData, TabularData - * or arrays. - *

- * Otherwise the data would be converted to its String value and stored into the input container map - * - * @param attributeObj the value to be inserted into this container - * @param prefix prefix of the attribute - * @param values the container map that stores the result - */ - protected void appendAttribute(Object attributeObj, String prefix, Map values) { - - if (attributeObj == null) { - values.put(prefix, attributeObj); - } else if (attributeObj instanceof CompositeData) { - handleCompositeData((CompositeData) attributeObj, prefix, values); - } else if (attributeObj instanceof TabularData) { - //for tabular data, we will insert the indices/keys as [index1,index2,index3] - //for example, if the index is "PS Survivor Space", then the full entry would be something like - //JMX.java.lang:type=GarbageCollector,name=PS_Scavenge.LastGcInfo.memoryUsageAfterGc[PS_Survivor_Space].value.committed = 2555904 - - TabularData tabularData = (TabularData) attributeObj; - Set keys = tabularData.keySet(); - - for (Object key : keys) { - Object[] indices = ((List) key).toArray(); - - StringBuffer indexString = new StringBuffer(); - - for (Object index : indices) { - if (indexString.length() == 0) { - indexString.append(index.toString().replace(' ', '_')); - } else { - indexString.append("," + index.toString().replace(' ', '_')); - } - } - - CompositeData compositeData = tabularData.get(indices); - handleCompositeData(compositeData, prefix + "[" + indexString.toString() + "]", values); - } - } else if (attributeObj.getClass().isArray()) { - //for array data, we will insert the key as [arrayIndex] for example Threading.thread[2].id = 2 - for (int i = 0; i < Array.getLength(attributeObj); i++) { //We cannot cast directly to Object[] as it would fail on primitive arrays - Object element = Array.get(attributeObj, i); -// System.out.println("Index : " + i); - appendAttribute(element, prefix + "[" + i + "]", values); - } - } else if (Primitives.isWrapperType(attributeObj.getClass())){ //simple data type - values.put(prefix, attributeObj); - } else { - values.put(prefix, attributeObj.toString()); - } - } - - private void handleCompositeData(CompositeData compositeData, String prefix, Map values) { - @SuppressWarnings("unchecked") - Set keys = compositeData.getCompositeType().keySet(); - - for (String key : keys) { - appendAttribute(compositeData.get(key), prefix + "." + key.replace(' ', '_'), values); - } - - } - - /** - * Processes the JMX attribute and convert it into a map filled with keys and values. - * @param mBeanName the mBeanName as ObjectName - * @param attributeName the name of the attribute - * @return a map filled with information by processing the input attribute - */ - public abstract Map process(ObjectName mBeanName, String attributeName) throws Exception; - -} \ No newline at end of file diff --git a/agent/src/main/java/com/tracelytics/monitor/jmx/processor/AttributeProcessorLocator.java b/agent/src/main/java/com/tracelytics/monitor/jmx/processor/AttributeProcessorLocator.java deleted file mode 100644 index 838bdc09..00000000 --- a/agent/src/main/java/com/tracelytics/monitor/jmx/processor/AttributeProcessorLocator.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.tracelytics.monitor.jmx.processor; - -import javax.management.MBeanServer; -import javax.management.MalformedObjectNameException; -import javax.management.ObjectName; - -import com.tracelytics.logging.Logger; -import com.tracelytics.logging.LoggerFactory; - -/** - * This locator holds the information of AttributeProcessor assignments. - *

- * Based on different mBean and attribute, this locator will return the corresponding AttributeProcessor - * @author Patson Luk - * - */ -public class AttributeProcessorLocator { - protected static final Logger logger = LoggerFactory.getLogger(); - - private static ObjectName OS_OBJECT_NAME; - - static { - try { - OS_OBJECT_NAME= new ObjectName("java.lang:type=OperatingSystem"); - } catch (MalformedObjectNameException e) { - logger.warn(e.getMessage()); - } catch (NullPointerException e) { - logger.warn(e.getMessage()); - } - } - - private AttributeProcessorLocator() { - } - - /** - * - * @param mBeanName mBean name as ObjectName - * @param attributeName attribute to be processed - * @param mbs - * @return AttributeProcessor located based on the inputs - */ - public static AttributeProcessor getProcessor(ObjectName mBeanName, String attributeName, MBeanServer mbs) { - if (OS_OBJECT_NAME.equals(mBeanName) && attributeName.equals("ProcessCpuLoad")) { //special processor for java.lang:type=OperatingSystem[ProcessCpuLoad] - return CpuLoadAttributeProcessor.getInstance(mbs); - } else if (OS_OBJECT_NAME.equals(mBeanName) && attributeName.equals("ProcessCpuTime")) { //IBM 1.5 does not have this attribute, so this attribute is optional (should not trigger error message if missing) - return OptionalAttributeProcessor.getInstance(mbs); - } else { - return new GenericAttributeProcessor(mbs); - } - } - - - - -} diff --git a/agent/src/main/java/com/tracelytics/monitor/jmx/processor/CpuLoadAttributeProcessor.java b/agent/src/main/java/com/tracelytics/monitor/jmx/processor/CpuLoadAttributeProcessor.java deleted file mode 100644 index 423d955a..00000000 --- a/agent/src/main/java/com/tracelytics/monitor/jmx/processor/CpuLoadAttributeProcessor.java +++ /dev/null @@ -1,122 +0,0 @@ -package com.tracelytics.monitor.jmx.processor; - -import java.lang.management.ManagementFactory; -import java.lang.management.OperatingSystemMXBean; -import java.lang.management.RuntimeMXBean; -import java.math.BigDecimal; -import java.util.LinkedHashMap; -import java.util.Map; - -import javax.management.AttributeNotFoundException; -import javax.management.InstanceNotFoundException; -import javax.management.MBeanException; -import javax.management.MBeanServer; -import javax.management.ObjectName; -import javax.management.ReflectionException; - -/** - * A CPU load attribute processor that computes the CPU load if such an attribute is not supported by the system. CPU load is only support in Java 1.7+ - * - * Take note that this should be a singleton as it is stateful to a specific JVM instance (process). - * - * @author Patson Luk - * - */ -class CpuLoadAttributeProcessor extends AttributeProcessor { - private static CpuLoadAttributeProcessor reference; - - - private long previousProcessCpuTime = 0; - private long previousUpTime = 0; - - private CpuLoadAttributeProcessor(MBeanServer mBeanServer) { - super(mBeanServer); - } - - static synchronized CpuLoadAttributeProcessor getInstance(MBeanServer mBeanServer) { - if (reference == null) { - reference = new CpuLoadAttributeProcessor(mBeanServer); - } - - return reference; - } - - - @Override - /** - * Attempt to retrieve the CPU load information from MBeanServer. If not available, try to compute the value. - */ - public Map process(ObjectName mBeanName, String attributeName) throws InstanceNotFoundException, ReflectionException, MBeanException { - Map values = new LinkedHashMap(); - - Object attributeObj; - try { - attributeObj = mBeanServer.getAttribute(mBeanName, attributeName); - appendAttribute(attributeObj, "", values); - - //System.out.println("Compared with computation result: " + computeCpuLoad()); //just for comparison! - - } catch (AttributeNotFoundException e) { - //try to compute the CPU load if the attribute is not available in the mBean as it is only supported in java 1.7+ - Double cpuLoad = computeCpuLoad(); - if (cpuLoad != null) { - appendAttribute(cpuLoad, "", values); - } - } - - return values; - } - - /** - * Compute the Cpu load using logic in JConsole source. Referenced from {@link http://knight76.blogspot.ca/2009/05/how-to-get-java-cpu-usage-jvm-instance.html} - * - * @return Cpu load from 0 to 1. Null if the computation is not successful - */ - private synchronized Double computeCpuLoad() { - OperatingSystemMXBean osBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); - RuntimeMXBean runtimeBean = (RuntimeMXBean) ManagementFactory.getRuntimeMXBean(); - - int availableProcessorCount = osBean.getAvailableProcessors(); - - try { - ObjectName objectName = new ObjectName("java.lang:type=OperatingSystem"); - Object processCpuTimeObj; - - try { - processCpuTimeObj= mBeanServer.getAttribute(objectName, "ProcessCpuTime"); - } catch (AttributeNotFoundException e) { - //Ok as some JVM (IBM 5.0) does not provide this value - logger.debug("Cannot compute CPU load as ProcessCpuTime is not available"); - return null; - } - - if (processCpuTimeObj != null) { - long elapsedCpu = (Long)processCpuTimeObj - previousProcessCpuTime; - - previousProcessCpuTime = (Long)processCpuTimeObj; - - long elapsedUpTime = runtimeBean.getUptime() - previousUpTime; - - previousUpTime = runtimeBean.getUptime(); - -// System.out.println("Process: " + elapsedCpu + " Uptime: " + elapsedUpTime + " Processor count: " + availableProcessorCount); - - - if (elapsedUpTime > 0L) { - BigDecimal cpuUsage = new BigDecimal(elapsedCpu / (elapsedUpTime * 1000000.0 * availableProcessorCount)); - - cpuUsage = cpuUsage.setScale(4, BigDecimal.ROUND_HALF_UP); - - return cpuUsage.doubleValue(); - } - } - - } catch (Exception e) { - logger.warn("Unexpected error while computing CPU load: " + e.getMessage(), e); - } - - return null; - } - - -} diff --git a/agent/src/main/java/com/tracelytics/monitor/jmx/processor/GenericAttributeProcessor.java b/agent/src/main/java/com/tracelytics/monitor/jmx/processor/GenericAttributeProcessor.java deleted file mode 100644 index 40e833f0..00000000 --- a/agent/src/main/java/com/tracelytics/monitor/jmx/processor/GenericAttributeProcessor.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.tracelytics.monitor.jmx.processor; - -import java.util.LinkedHashMap; -import java.util.Map; - -import javax.management.AttributeNotFoundException; -import javax.management.InstanceNotFoundException; -import javax.management.MBeanException; -import javax.management.MBeanServer; -import javax.management.ObjectName; -import javax.management.ReflectionException; -import javax.management.RuntimeMBeanException; - -/** - * Generic attribute processor for attribute values that do not need any special processing. Simply retrieve the value from MBeanServer and append it to the map - * @author Patson Luk - * - */ -class GenericAttributeProcessor extends AttributeProcessor { - - public GenericAttributeProcessor(MBeanServer mBeanServer) { - super(mBeanServer); - } - - public Map process(ObjectName mBeanName, String attributeName) throws InstanceNotFoundException, AttributeNotFoundException, ReflectionException, MBeanException { - Map values = new LinkedHashMap(); - - Object attributeObj; - try { - attributeObj = mBeanServer.getAttribute(mBeanName, attributeName); - appendAttribute(attributeObj, "", values); - } catch (RuntimeMBeanException e) { - if (e.getCause() != null && e.getCause() instanceof UnsupportedOperationException) { - //then it is OK, since some environment might not support certain properties even though they are defined in the MBean info - } else { - throw e; - } - } - - - return values; - } - - -} diff --git a/agent/src/main/java/com/tracelytics/monitor/jmx/processor/OptionalAttributeProcessor.java b/agent/src/main/java/com/tracelytics/monitor/jmx/processor/OptionalAttributeProcessor.java deleted file mode 100644 index fc751e2d..00000000 --- a/agent/src/main/java/com/tracelytics/monitor/jmx/processor/OptionalAttributeProcessor.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.tracelytics.monitor.jmx.processor; - -import java.util.LinkedHashMap; -import java.util.Map; - -import javax.management.AttributeNotFoundException; -import javax.management.InstanceNotFoundException; -import javax.management.MBeanException; -import javax.management.MBeanServer; -import javax.management.ObjectName; -import javax.management.ReflectionException; - -/** - * A CPU time attribute processor that is more forgiving when the attribute is missing. Such an attribute is not found in IBM 1.5 jre - * - * - * @author Patson Luk - * - */ -class OptionalAttributeProcessor extends AttributeProcessor { - private static OptionalAttributeProcessor reference; - - - - private OptionalAttributeProcessor(MBeanServer mBeanServer) { - super(mBeanServer); - } - - static synchronized OptionalAttributeProcessor getInstance(MBeanServer mBeanServer) { - if (reference == null) { - reference = new OptionalAttributeProcessor(mBeanServer); - } - - return reference; - } - - - @Override - /** - * Attempt to retrieve the CPU time information from MBeanServer. If not available, simply display debug message and return - */ - public Map process(ObjectName mBeanName, String attributeName) throws InstanceNotFoundException, ReflectionException, MBeanException { - Map values = new LinkedHashMap(); - - Object attributeObj; - try { - attributeObj = mBeanServer.getAttribute(mBeanName, attributeName); - appendAttribute(attributeObj, "", values); - - } catch (AttributeNotFoundException e) { - //Ok as some JVM (IBM 5.0) does not provide this value - logger.debug("Cannot load attribute [" + mBeanName.getCanonicalName() + "]. This is expected as some JVMs might not publish this attribute. Skipping..."); - } - - - return values; - } -} diff --git a/agent/src/main/java/com/tracelytics/monitor/metrics/AbstractMetricsEntryCollector.java b/agent/src/main/java/com/tracelytics/monitor/metrics/AbstractMetricsEntryCollector.java deleted file mode 100644 index 7e66e92b..00000000 --- a/agent/src/main/java/com/tracelytics/monitor/metrics/AbstractMetricsEntryCollector.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.tracelytics.monitor.metrics; - -import java.util.List; - -import com.tracelytics.logging.Logger; -import com.tracelytics.logging.LoggerFactory; -import com.tracelytics.metrics.MetricsEntry; - -/** - * Sub metrics collector used by {@link MetricsCollector} - * @author pluk - * - */ -abstract class AbstractMetricsEntryCollector { - protected static Logger logger = LoggerFactory.getLogger(); - abstract List> collectMetricsEntries() throws Exception; -} diff --git a/agent/src/main/java/com/tracelytics/monitor/metrics/CustomMetricsCollector.java b/agent/src/main/java/com/tracelytics/monitor/metrics/CustomMetricsCollector.java deleted file mode 100644 index 78c46896..00000000 --- a/agent/src/main/java/com/tracelytics/monitor/metrics/CustomMetricsCollector.java +++ /dev/null @@ -1,200 +0,0 @@ -package com.tracelytics.monitor.metrics; - -import com.tracelytics.ext.google.common.cache.CacheBuilder; -import com.tracelytics.ext.google.common.cache.CacheLoader; -import com.tracelytics.ext.google.common.cache.LoadingCache; -import com.tracelytics.joboe.settings.SettingsArg; -import com.tracelytics.joboe.settings.SettingsArgChangeListener; -import com.tracelytics.joboe.settings.SettingsManager; -import com.tracelytics.metrics.MetricKey; -import com.tracelytics.metrics.MetricsEntry; -import com.tracelytics.metrics.measurement.*; - - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.ConcurrentMap; - -/** - * Sub metrics collector that collects custom metrics, it serves 2 purposes: - * 1. Allow api trigger to report custom metrics and it gets batched up here - * 2. Allow metrics collector to periodically call this to collect metrics recorded in point 1 - * - * @author Patson Luk - * - */ -public class CustomMetricsCollector extends AbstractMetricsEntryCollector { - public static final CustomMetricsCollector INSTANCE = new CustomMetricsCollector(); - private LoadingCache summaryMeasurements; - private LoadingCache incrementMeasurements; - - private static final int DEFAULT_LIMIT = 500; - static int limit = DEFAULT_LIMIT; - private boolean reportedLimitExceeded = false; - static final int TAGS_LIMIT = 50; - - static { - addLimitChangeListener(); - } - - private CustomMetricsCollector() { - reset(); - limit = DEFAULT_LIMIT; - reportedLimitExceeded = false; - } - - private static void addLimitChangeListener() { - SettingsManager.registerListener(new SettingsArgChangeListener(SettingsArg.MAX_CUSTOM_METRICS) { - @Override - public void onChange(Integer newValue) { - if (newValue != null) { - limit = newValue; - } else { - limit = DEFAULT_LIMIT; - } - } - }); - - } - - - @Override - List> collectMetricsEntries() { - List> entries = new ArrayList>(); - - ConcurrentMap reportingSummaryMeasurements = summaryMeasurements.asMap(); - ConcurrentMap reportingIncrementMeasurements = incrementMeasurements.asMap(); - - reset(); - - for (Entry entry : reportingSummaryMeasurements.entrySet()) { - entries.add(new SummaryMeasurementMetricsEntry(entry.getKey(), entry.getValue())); - } - - for (Entry entry : reportingIncrementMeasurements.entrySet()) { - entries.add(new SimpleMeasurementMetricsEntry(entry.getKey(), entry.getValue()) { - @Override - /** - * Overrides to give a different label "count" instead of "value" - */ - public Map getSerializedKvs() { - return Collections.singletonMap("count", value); - } - }); - } - return entries; - } - - /** - * For internal testing only - * @param name - * @param tags - * @return - */ - public Double getSum(String name, Map tags) { - MetricKey key = new MetricKey(name, tags); - SummaryDoubleMeasurement summaryMeasurement = summaryMeasurements.getIfPresent(key); - if (summaryMeasurement != null) { - return summaryMeasurement.getSum(); - } else { - return null; - } - } - - /** - * For internal testing only - * @param name - * @param tags - * @return - */ - public Long getCount(String name, Map tags) { - MetricKey key = new MetricKey(name, tags); - SummaryDoubleMeasurement summaryMeasurement = summaryMeasurements.getIfPresent(key); - if (summaryMeasurement != null) { - return summaryMeasurement.getCount(); - } - return incrementMeasurements.getIfPresent(key); - } - - public final void reset() { - summaryMeasurements = createSummaryMeasurementCache(); - incrementMeasurements = createIncrementMeasurementCache(); - } - - private static LoadingCache createSummaryMeasurementCache() { - return CacheBuilder.newBuilder().build(new CacheLoader () { - @Override - public SummaryDoubleMeasurement load(MetricKey key) throws Exception { - return new SummaryDoubleMeasurement(); - } - }); - } - - private static LoadingCache createIncrementMeasurementCache() { - return CacheBuilder.newBuilder().build(new CacheLoader () { - @Override - public Long load(MetricKey key) throws Exception { - return 0l; - } - }); - } - - - public void recordSummaryMetric(String name, double value, int count, Map tags) { - if (tags != null && tags.size() > TAGS_LIMIT) { - logger.warn("Only " + TAGS_LIMIT + " tags are allowed but found " + tags.size() + " tags in metric [" + name + "], entry ignored"); - return; - } - - if (count <= 0) { - logger.warn("Only positive count is allowed but found " + count + " in metric [" + name + "], entry ignored"); - return; - } - - MetricKey metricKey = new MetricKey(name, tags); - - if (summaryMeasurements.getIfPresent(metricKey) == null && summaryMeasurements.size() + incrementMeasurements.size() >= limit) { - if (!reportedLimitExceeded) { - logger.warn("Dropping metric entry with name [" + name + "] as limit " + limit + " has been reached. No more metric entry with new name/tags will be accepted until next report cycle..."); - reportedLimitExceeded = true; - } - return; - } - - SummaryMeasurement measurement = summaryMeasurements.getUnchecked(metricKey); - measurement.recordValue(value); - if (count != 1) { - measurement.incrementCount(count - 1); - } - - } - - public void recordIncrementMetrics(String name, int count, Map tags) { - if (tags != null && tags.size() > TAGS_LIMIT) { - logger.warn("Only " + TAGS_LIMIT + " tags are allowed but found " + tags.size() + " tags in metric [" + name + "], entry ignored"); - return; - } - - if (count <= 0) { - logger.warn("Only positive count is allowed but found " + count + " in metric [" + name + "], entry ignored"); - return; - } - - MetricKey metricKey = new MetricKey(name, tags); - - if (incrementMeasurements.getIfPresent(metricKey) == null && summaryMeasurements.size() + incrementMeasurements.size() >= limit) { - if (!reportedLimitExceeded) { - logger.warn("Dropping metric entry with name [" + name + "] as limit " + limit + " has been reached. No more metric entry with new name/tags will be accepted until next report cycle..."); - reportedLimitExceeded = true; - } - return; - } - - Long measurement = incrementMeasurements.getUnchecked(metricKey); - incrementMeasurements.put(metricKey, measurement + count); - } - -} diff --git a/agent/src/main/java/com/tracelytics/monitor/metrics/JMXCollector.java b/agent/src/main/java/com/tracelytics/monitor/metrics/JMXCollector.java deleted file mode 100644 index 1287e995..00000000 --- a/agent/src/main/java/com/tracelytics/monitor/metrics/JMXCollector.java +++ /dev/null @@ -1,315 +0,0 @@ -package com.tracelytics.monitor.metrics; - -import java.lang.management.ManagementFactory; -import java.util.*; -import java.util.Map.Entry; - -import javax.management.AttributeNotFoundException; -import javax.management.InstanceNotFoundException; -import javax.management.IntrospectionException; -import javax.management.JMRuntimeException; -import javax.management.MBeanAttributeInfo; -import javax.management.MBeanException; -import javax.management.MBeanInfo; -import javax.management.MBeanServer; -import javax.management.MalformedObjectNameException; -import javax.management.ObjectName; -import javax.management.ReflectionException; - -import com.tracelytics.ext.json.JSONArray; -import com.tracelytics.ext.json.JSONException; -import com.tracelytics.ext.json.JSONObject; -import com.tracelytics.joboe.config.ConfigContainer; -import com.tracelytics.joboe.config.ConfigProperty; -import com.tracelytics.joboe.config.InvalidConfigException; -import com.tracelytics.metrics.MetricKey; -import com.tracelytics.metrics.MetricsEntry; -import com.tracelytics.metrics.measurement.SimpleMeasurementMetricsEntry; -import com.tracelytics.monitor.jmx.processor.AttributeProcessor; -import com.tracelytics.monitor.jmx.processor.AttributeProcessorLocator; - -/** - * Sub metrics collector that collects metrics from JMX's mBeans. Take note that each {@link #collect()} call would return information collected from each of the {@link JMXScope} passed in via the constructor - * as {@code ConfigProperty.MONITOR_JMX_SCOPES} in {@link ConfigContainer} - * - * @author Patson Luk - * - */ -class JMXCollector extends AbstractMetricsEntryCollector { - - private List scopes; //scopes that this collector should collect information from - - static final int DEFAULT_MAX_ENTRY_COUNT = 100; //entries allowed per collection cycle - private int maxEntryCount = DEFAULT_MAX_ENTRY_COUNT; - - - static final String JMX_LABEL = "trace.jvm"; - private static final String DEFAULT_MBEAN_DOMAIN = "java.lang"; - - public JMXCollector(ConfigContainer configs) throws InvalidConfigException { - //determine information groups to collect - String scopesString = (String) configs.get(ConfigProperty.MONITOR_JMX_SCOPES); - if (scopesString == null) { - throw new InvalidConfigException("No JMX scope was defined! No JMX metrics would be collected"); - } else { - scopes = parseScopesString(scopesString); - } - - //Set the max entry count if provided - if (configs.containsProperty(ConfigProperty.MONITOR_JMX_MAX_ENTRY)) { - int maxEntryCount = (Integer)configs.get(ConfigProperty.MONITOR_JMX_MAX_ENTRY); - if (maxEntryCount < 0) { - throw new InvalidConfigException(ConfigProperty.MONITOR_JMX_MAX_ENTRY + " should not be negative but found: " + maxEntryCount); - } - this.maxEntryCount = maxEntryCount; - } - - } - - /** - * Parse the scopes string from external input - * @param scopesString - * @return a List of JMXScope based on the input argument - * @throws InvalidConfigException - */ - private static List parseScopesString(String scopesString) throws InvalidConfigException { - List scopes = new ArrayList(); - try { - JSONObject object = new JSONObject(scopesString); - for (Object keyAsObject : object.keySet()) { - String objectName = (String) keyAsObject; - - Object attributeObj = object.get(objectName); - - String[] attributes; - - if (attributeObj instanceof String) { - String attributeString = (String) attributeObj; - attributeString = attributeString.trim(); - - if ("".equals(attributeString) || "*".equals(attributeString)) { - attributes = new String[0]; - } else { - attributes = new String[] { attributeString }; - } - } else if (attributeObj instanceof JSONArray){ - JSONArray attributeArray = (JSONArray) attributeObj; - - attributes = new String[attributeArray.length()]; - for (int i = 0 ; i < attributeArray.length(); i++) { - attributes[i] = attributeArray.getString(i); - } - } else { - logger.warn("Unexpected jmx scope value of type [" + attributeObj.getClass().getName() + "]"); - return Collections.emptyList(); - } - - scopes.add(new JMXScope(objectName, attributes)); - } - } catch (JSONException e) { - logger.warn("JSON Exception encountered! " + e.getMessage()); - throw new InvalidConfigException("Error parsing scope for JMX : " + e.getMessage(), e); - } - - Collections.sort(scopes, new Comparator() { - public int compare(JMXScope o1, JMXScope o2) { - if (o1.getObjectName() == null) { - return o2.getObjectName() == null ? 0 : -1; - } - return o1.getObjectName().compareTo(o2.getObjectName()); - } - }); - - return scopes; - } - - - /** - * Collects information from the JMX mBeans - * @return a Map with key as the attribute name/key and value as the attribute values from the JMX mBeans - */ - public Map collect() throws IntrospectionException, InstanceNotFoundException, ReflectionException, AttributeNotFoundException, MBeanException { - ClassLoader existingContextLoader = Thread.currentThread().getContextClassLoader(); - ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); - try { - if (systemClassLoader != null && existingContextLoader == null) { - Thread.currentThread().setContextClassLoader(systemClassLoader); //set system class loader to context, it should have better access to classes than the null (bootstrap) loader - } - return collect(ManagementFactory.getPlatformMBeanServer()); - } catch (JMRuntimeException e) { - //known issue for some app server, which the JMX class might not be available yet during startup see https://github.com/librato/joboe/issues/675 - if (e.getCause() instanceof ClassNotFoundException) { - logger.debug("Cannot load JMX impl class: " + e.getMessage() + " the class might be available later on", e); - return Collections.emptyMap(); - } - throw e; - } finally { - Thread.currentThread().setContextClassLoader(existingContextLoader); //reset back to whatever it was - } - } - - /** - * Collects information from the JMX mBeans - * @return a Map with key as the attribute name/key and value as the numeric attribute values from the JMX mBeans - */ - Map collect(MBeanServer mbs) throws IntrospectionException, InstanceNotFoundException, ReflectionException, AttributeNotFoundException, MBeanException { - Map information = new LinkedHashMap(); - - for (JMXScope scope : scopes) { - logger.trace("Collecting JMX scope [" + scope + "]"); - - try { - @SuppressWarnings("unchecked") - Set names = mbs.queryNames(new ObjectName(scope.getObjectName()), null); //query a list of mBean names based on the input ObjectName - - Map entriesFromScope = new LinkedHashMap(); - for (ObjectName name : names) { //iterate through each mBean - - logger.trace("Procesing MBean with ObjectName [" + name.toString() + "]"); - - List targetAttributes; - - if (scope.getAttributes() == null) { //if no specific attributes have been defined, then find all attributes - targetAttributes = new ArrayList(); - - MBeanInfo info = mbs.getMBeanInfo(name); - for (MBeanAttributeInfo attributeInfo : info.getAttributes()) { //iterate through each attribute under the mBean - targetAttributes.add(attributeInfo.getName()); - } - } else { - targetAttributes = scope.getAttributes(); - } - - for (String targetAttribute : targetAttributes) { //iterate the target attribute by names - logger.trace("Processing MBean attribute with name [" + targetAttribute + "]"); - try { - entriesFromScope.putAll(processMBeanAttribute(name, targetAttribute, mbs)); - } catch (Exception e) { - logger.warn("JMX Attribute error [" + e.getClass().getName() + "]" + e.getMessage() + " from " + name.getCanonicalName()); - } - - } - } - - if (names.isEmpty()) { - logger.debug("Cannot find any mBeans under scope [" + scope.getObjectName() + "]"); - } - - if (information.size() + entriesFromScope.size() <= maxEntryCount) { - information.putAll(entriesFromScope); - } else if (information.size() < maxEntryCount) { - List mapKeys = new ArrayList(entriesFromScope.keySet()); - int remainingCapacity = maxEntryCount - information.size(); - entriesFromScope.keySet().retainAll(mapKeys.subList(0, remainingCapacity)); - information.putAll(entriesFromScope); - logger.warn("Stop collecting JXM entries as the max entries [" + maxEntryCount + "] has reached"); - } else { - logger.warn("Stop collecting JXM entries as the max entries [" + maxEntryCount + "] has reached"); - break; - } - } catch (MalformedObjectNameException e) { - logger.warn("[" + getClass().getName() + "]" + e.getMessage()); - } catch (NullPointerException e) { - logger.warn("[" + getClass().getName() + "]" + e.getMessage()); - } - } - return information; - } - - - /** - * Processes the mBean Attribute and returns a Map filled with keys and values. Take note that although the input is one parameter, the - * result could be variable in size. - * - * For example, if the processing could not find the attribute, it might be an empty map. And if the attribute is a CompositeData, the result map might - * contain multiple keys and values of the flattened composite data - * - * Only value that is of `java.lang.Number` will be collected - * - * @param mBeanName - * @param attributeName - * @param mbs - * @return keys and values after processing the mBean attribute. Take note that although the input is one parameter, the result could be variable in size. - */ - private static Map processMBeanAttribute(ObjectName mBeanName, String attributeName, MBeanServer mbs) throws Exception { - String prefix = (JMX_LABEL + "." + getMetricNameSegmentFromObjectName(mBeanName) + "." + attributeName.toString()).replace(' ', '_'); - - AttributeProcessor processor = AttributeProcessorLocator.getProcessor(mBeanName, attributeName, mbs); - - Map processedData = processor.process(mBeanName, attributeName); - - Map result = new LinkedHashMap(); - - for (Entry entry : processedData.entrySet()) { - String metricName; - if (entry.getKey().length() == 0) { - metricName = prefix; - } else { - metricName = prefix + entry.getKey(); - } - - Object value = entry.getValue(); - if (value instanceof Number) { - MetricKey metricKey = new MetricKey(metricName, getMetricTagsFromObjectName(mBeanName)); - logger.trace("Collected JMX metric entry [" + metricKey + "]"); - result.put(metricKey, (Number) value); - } else { - logger.debug("Skipping JMX entry [" + metricName + "] in metrics reporting, as its value [" + value + "] is not a number!"); - } - } - - - return result; - } - - private static Map getMetricTagsFromObjectName(ObjectName mBeanName) { - Map tags = new HashMap(mBeanName.getKeyPropertyList()); - tags.remove("type"); - tags.remove("j2eeType"); - tags.remove("name"); - return tags; - } - - private static String getMetricNameSegmentFromObjectName(ObjectName mBeanName) { - String domain = mBeanName.getDomain(); - StringBuilder result = new StringBuilder(); - - if (!DEFAULT_MBEAN_DOMAIN.equals(domain)) { - result.append(domain); - } - - String typeProperty = mBeanName.getKeyProperty("type"); - if (typeProperty == null) { - typeProperty = mBeanName.getKeyProperty("j2eeType"); - } - if (typeProperty != null) { - appendSegment(result, typeProperty); - } - String nameProperty = mBeanName.getKeyProperty("name"); - if (nameProperty != null) { - appendSegment(result, nameProperty); - } - - return result.toString(); - } - - private static void appendSegment(StringBuilder existingBuilder, String newSegment) { - if (existingBuilder.length() > 0) { - existingBuilder.append('.'); - } - existingBuilder.append(newSegment); - } - - @Override - List> collectMetricsEntries() throws IntrospectionException, InstanceNotFoundException, AttributeNotFoundException, ReflectionException, MBeanException { - Map data = collect(); - List metricsEntries = new ArrayList(); - for (Entry entry : data.entrySet()) { - metricsEntries.add(new SimpleMeasurementMetricsEntry(entry.getKey(), entry.getValue())); - } - return metricsEntries; - } - - - -} diff --git a/agent/src/main/java/com/tracelytics/monitor/metrics/JMXScope.java b/agent/src/main/java/com/tracelytics/monitor/metrics/JMXScope.java deleted file mode 100644 index ef0571ab..00000000 --- a/agent/src/main/java/com/tracelytics/monitor/metrics/JMXScope.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.tracelytics.monitor.metrics; - -import java.util.Arrays; -import java.util.List; - -/** - * Defines the Scope of the JMX collection. It consists of the MBean name or pattern in the form of ObjectName and a list of attribute names. - *

- * Take note that if attribute names are not provided, it will look for all the attributes under the input MBean name or pattern - * @author Patson Luk - * - */ -public class JMXScope { - private String objectName; - private String[] attributes; - - /** - * - * @param objectName mBean name or pattern - * @param attributes list of attributes to be targeted for JMX. If not provided, it will be interpreted as getting all attributes - */ - JMXScope(String objectName, String...attributes) { - this.objectName = objectName; - this.attributes = attributes; - } - - String getObjectName() { - return objectName; - } - - List getAttributes() { - if (attributes == null || attributes.length == 0) { - return null; - } else { - return Arrays.asList(attributes); - } - } - - @Override - public String toString() { - StringBuffer result = new StringBuffer(objectName); - if (attributes != null && attributes.length > 0) { - result.append("["); - for (String attribute : attributes) { - result.append(attribute + ","); - } - - result.delete(result.length() - 1, result.length()); //trim the trailing comma - result.append("]"); - } - return result.toString(); - } - - -} \ No newline at end of file diff --git a/agent/src/main/java/com/tracelytics/monitor/metrics/MetricsCategory.java b/agent/src/main/java/com/tracelytics/monitor/metrics/MetricsCategory.java deleted file mode 100644 index c52246d5..00000000 --- a/agent/src/main/java/com/tracelytics/monitor/metrics/MetricsCategory.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.tracelytics.monitor.metrics; - -public enum MetricsCategory { - SYSTEM, - TRACING_REPORTER, - SPAN_METRICS, - LAYER_COUNT, //aka throughput - JMX, - CUSTOM -} diff --git a/agent/src/main/java/com/tracelytics/monitor/metrics/MetricsCollector.java b/agent/src/main/java/com/tracelytics/monitor/metrics/MetricsCollector.java deleted file mode 100644 index d3a2374b..00000000 --- a/agent/src/main/java/com/tracelytics/monitor/metrics/MetricsCollector.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.tracelytics.monitor.metrics; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.*; - -import com.tracelytics.joboe.config.ConfigContainer; -import com.tracelytics.joboe.config.ConfigProperty; -import com.tracelytics.joboe.config.InvalidConfigException; -import com.tracelytics.metrics.MetricsEntry; -import com.tracelytics.monitor.SystemCollector; -import com.tracelytics.util.DaemonThreadFactory; - -/** - * Collects metrics by maintain a list of sub metric entry collector of type {@link AbstractMetricsEntryCollector}. - * - * {@link MetricsCategory} outlines a list of possible metrics available, though the actual metric types collected depends on configurations - * - * - * @author pluk - * - */ -class MetricsCollector extends SystemCollector>> { - private Map collectors = new HashMap(); - private ExecutorService executorService; - private static final int MAX_WAIT_TIME = 10; //max wait time for a collection task, in terms of second - - - public MetricsCollector(ConfigContainer configs) throws InvalidConfigException { - collectors.put(MetricsCategory.SYSTEM, new SystemMetricsCollector()); - collectors.put(MetricsCategory.TRACING_REPORTER, new TracingReporterMetricsCollector()); - - if (configs.get(ConfigProperty.MONITOR_SPAN_METRICS_ENABLE) == null || (Boolean)configs.get(ConfigProperty.MONITOR_SPAN_METRICS_ENABLE)) { //default as true - collectors.put(MetricsCategory.SPAN_METRICS, new SpanMetricsCollector()); - } - collectors.put(MetricsCategory.LAYER_COUNT, new TraceDecisionMetricsCollector()); - - if (configs.get(ConfigProperty.MONITOR_JMX_ENABLE) == null || (Boolean)configs.get(ConfigProperty.MONITOR_JMX_ENABLE)) { - collectors.put(MetricsCategory.JMX, new JMXCollector(configs)); - } - - collectors.put(MetricsCategory.CUSTOM, CustomMetricsCollector.INSTANCE); - - executorService = Executors.newCachedThreadPool(DaemonThreadFactory.newInstance("metrics-collector")); - } - - @Override - protected Map>> collect() throws Exception { - Map>>> collectedFutures = new HashMap>>>(); - Map>> entriesFromAllCollectors = new HashMap>>(); - - for (final Entry collectorEntry : collectors.entrySet()) { - final AbstractMetricsEntryCollector collector = collectorEntry.getValue(); - - //asynchronously call all sub metric entry collectors to collect metrics - Future>> collectedFuture = executorService.submit(new Callable>>() { - public List> call() throws Exception { - List> collectedEntries = collector.collectMetricsEntries(); - return collectedEntries; - } - }); - - collectedFutures.put(collectorEntry.getKey(), collectedFuture); - } - - - //rather simple but naive implementation to iterate each task and wait. Can be improved if jdk 8 is used... - for (Entry>>> futureEntry : collectedFutures.entrySet()) { - try { - entriesFromAllCollectors.put(futureEntry.getKey(), futureEntry.getValue().get(MAX_WAIT_TIME, TimeUnit.SECONDS)); - } catch (Exception e) { - logger.warn("Failed to collect info for " + futureEntry.getKey() + ", skipping... Error message: " + e.getMessage(), e); - } - } - - return entriesFromAllCollectors; - } -} diff --git a/agent/src/main/java/com/tracelytics/monitor/metrics/MetricsMonitor.java b/agent/src/main/java/com/tracelytics/monitor/metrics/MetricsMonitor.java deleted file mode 100644 index 31896ad0..00000000 --- a/agent/src/main/java/com/tracelytics/monitor/metrics/MetricsMonitor.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.tracelytics.monitor.metrics; - -import java.util.List; - -import com.tracelytics.joboe.config.ConfigContainer; -import com.tracelytics.joboe.config.ConfigProperty; -import com.tracelytics.joboe.config.InvalidConfigException; -import com.tracelytics.joboe.rpc.ClientException; -import com.tracelytics.joboe.rpc.RpcClientManager; -import com.tracelytics.joboe.rpc.RpcClientManager.OperationType; -import com.tracelytics.joboe.settings.SettingsArg; -import com.tracelytics.joboe.settings.SettingsArgChangeListener; -import com.tracelytics.joboe.settings.SettingsManager; -import com.tracelytics.metrics.MetricsEntry; -import com.tracelytics.monitor.SystemMonitorWithFrequency; - -/** - * {@code SystemMonitor} for various metrics. The the list of supported metrics, please refer to {@link MetricsCollector} - * @author Patson Luk - * - */ -public class MetricsMonitor extends SystemMonitorWithFrequency>> { - private static MetricsMonitor singleton; - - static final int DEFAULT_FREQUENCY = 1; - static final TimeUnit DEFAULT_TIME_UNIT = TimeUnit.PER_MINUTE; - - public MetricsMonitor(ConfigContainer configs) throws InvalidConfigException, ClientException { - super(DEFAULT_TIME_UNIT, DEFAULT_FREQUENCY, new MetricsCollector(configs), new MetricsReporter(RpcClientManager.getClient(OperationType.METRICS))); - - if (configs.containsProperty(ConfigProperty.MONITOR_METRICS_FLUSH_INTERVAL)) { - setInterval((Integer) configs.get(ConfigProperty.MONITOR_METRICS_FLUSH_INTERVAL) * 1000); - } - - SettingsManager.registerListener(new SettingsArgChangeListener(SettingsArg.METRIC_FLUSH_INTERVAL) { - @Override - public void onChange(Integer newValue) { - try { - if (newValue != null) { - setInterval((long) newValue * 1000); - } else { //reset back to default - setFrequency(DEFAULT_TIME_UNIT, DEFAULT_FREQUENCY); - } - logger.debug("Changed metrics report interval to " + newValue); - } catch (InvalidConfigException e) { - logger.warn("Cannot set interval to [" + newValue + "] : " + e.getMessage()); - } - } - }); - } - - public static synchronized MetricsMonitor buildInstance(ConfigContainer configs) throws InvalidConfigException, ClientException { - if (singleton == null) { - singleton = new MetricsMonitor(configs); - } - return singleton; - } - - @Override - protected String getMonitorName() { - return "Metrics Monitor"; - } - - @Override - public void close() { - logger.debug("Flushing metrics before closing " + getMonitorName()); - executeCycle(); - - super.close(); - } - -} diff --git a/agent/src/main/java/com/tracelytics/monitor/metrics/MetricsReporter.java b/agent/src/main/java/com/tracelytics/monitor/metrics/MetricsReporter.java deleted file mode 100644 index 588c391d..00000000 --- a/agent/src/main/java/com/tracelytics/monitor/metrics/MetricsReporter.java +++ /dev/null @@ -1,172 +0,0 @@ -package com.tracelytics.monitor.metrics; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.SortedMap; -import java.util.TreeMap; - -import com.tracelytics.agent.Agent; -import com.tracelytics.joboe.rpc.Client; -import com.tracelytics.joboe.rpc.ClientException; -import com.tracelytics.joboe.rpc.ClientLoggingCallback; -import com.tracelytics.joboe.rpc.Result; -import com.tracelytics.metrics.MetricsEntry; -import com.tracelytics.metrics.MetricsEntry.MetricsEntryType; -import com.tracelytics.monitor.SystemReporter; -import com.tracelytics.monitor.SystemReporterException; -import com.tracelytics.util.HostInfoUtils; - - -/** - * {@code SystemReporter} for all metrics by converting metrics collected from {@link MetricsCollector} into metrics messages, and send them using the provided rpc client - * - * Take note that though MetricsCollector extracts metrics from several different sources, - * this reporter handles those metrics generically without making any special cases based on the source type. - * - * - * @author Patson Luk - * - */ -class MetricsReporter extends SystemReporter>> { - static final int MAX_MEASUREMENT_ENTRY_COUNT = 2000; - //static final int MAX_HISTOGRAM_ENTRY_COUNT = 100; //Do not limit histogram counts for now - static final int MAX_METRIC_NAME_LENGTH = 255; - static final int MAX_TAG_NAME_LENGTH = 64; - static final int MAX_TAG_VALUE_LENGTH = 255; - private Client rpcClient; - private ClientLoggingCallback loggingCallback = new ClientLoggingCallback("post metrics"); - - MetricsReporter(Client rpcClient) { - this.rpcClient = rpcClient; - } - - @Override - public void reportData(Map>> collectedData, long interval) throws SystemReporterException { - List> measurementKeyValues = new ArrayList>(); - List> histogramKeyValues = new ArrayList>(); - List> customMetricsKeyValues = new ArrayList>(); - Map topLevelKeyValues = new HashMap(); - - SortedMap>> sortedData = new TreeMap>>(collectedData); - - int measurementCount = 0; - int histogramCount = 0; - for (Entry>> collectedByMetricsType : sortedData.entrySet()) { - for (MetricsEntry metricsEntry : collectedByMetricsType.getValue()) { - if (metricsEntry.getType() == MetricsEntryType.MEASUREMENT || metricsEntry.getType() == MetricsEntryType.HISTOGRAM) { - if (metricsEntry.getType() == MetricsEntryType.MEASUREMENT) { - if (++ measurementCount > MAX_MEASUREMENT_ENTRY_COUNT) { - continue; //do not proceed further if limit exceeded - } - } else { - histogramCount ++; //no limit for now - } - - if (metricsEntry.getType() == MetricsEntryType.MEASUREMENT) { - if (collectedByMetricsType.getKey() == MetricsCategory.CUSTOM) { - customMetricsKeyValues.add(extractKeyValues(metricsEntry)); - } else { - measurementKeyValues.add(extractKeyValues(metricsEntry)); - } - } else { - histogramKeyValues.add(extractKeyValues(metricsEntry)); - } - } else if (metricsEntry.getType() == MetricsEntryType.TOP_LEVEL) { - topLevelKeyValues.putAll(metricsEntry.getSerializedKvs()); - } else { - logger.warn("Unexpected metrics type : " + metricsEntry.getType()); - } - } - } - - if (measurementCount > MAX_MEASUREMENT_ENTRY_COUNT) { - logger.warn("Dropped " + (measurementCount - MAX_MEASUREMENT_ENTRY_COUNT) + " measurement entries as the limit " + MAX_MEASUREMENT_ENTRY_COUNT + " was exceeded"); - } else { - logger.debug("Going to report " + measurementCount + " Measurement metrics entries"); - } - logger.debug("Going to report " + histogramCount + " Histogram metrics entries"); - - List> metricsMessages = new ArrayList>(); - //build the non-custom metric message - Map metricsMessage = new HashMap(); - - if (!measurementKeyValues.isEmpty()) { - metricsMessage.put("measurements", measurementKeyValues); - } - - if (!histogramKeyValues.isEmpty()) { - metricsMessage.put("histograms", histogramKeyValues); - } - - metricsMessage.putAll(topLevelKeyValues); - - int flushInterval = (int)interval / 1000; //from millisec to second - putInfoKeyValues(metricsMessage, flushInterval); - - metricsMessages.add(metricsMessage); - - //build the custom metric message - if (!customMetricsKeyValues.isEmpty()) { - Map customMetricsMessage = new HashMap(); - putInfoKeyValues(customMetricsMessage, flushInterval); - - customMetricsMessage.put("IsCustom", true); - customMetricsMessage.put("measurements", customMetricsKeyValues); - - metricsMessages.add(customMetricsMessage); - } - - try { - rpcClient.postMetrics(metricsMessages, loggingCallback); - } catch (ClientException e) { - logger.debug("Failed to post metrics message : " + e.getMessage()); - } - } - - private Map extractKeyValues(MetricsEntry metricsEntry) { - Map extractedKeyValues = new HashMap(); - String trimmedMetricName = metricsEntry.getName().length() <= MAX_METRIC_NAME_LENGTH ? metricsEntry.getName() : metricsEntry.getName().substring(0, MAX_METRIC_NAME_LENGTH); - - extractedKeyValues.put("name", trimmedMetricName); - if (metricsEntry.getTags() != null && !metricsEntry.getTags().isEmpty()) { //only add tags KV if tags is non-empty - Map trimmedTags = new HashMap(); //AO metrics only support String value for now - for (Entry tagEntry : metricsEntry.getTags().entrySet()) { - String trimmedKey = tagEntry.getKey().length() <= MAX_TAG_NAME_LENGTH ? tagEntry.getKey() : tagEntry.getKey().substring(0, MAX_TAG_NAME_LENGTH); - Object trimmedValue; - Object value = tagEntry.getValue(); - if (value != null) { - if (value instanceof String) { - String valueString = (String) value; - trimmedValue = valueString.length() <= MAX_TAG_VALUE_LENGTH ? valueString : valueString.substring(0, MAX_TAG_VALUE_LENGTH); - } else { - trimmedValue = value; - } - } else { - logger.warn("Unexpected null tag value for metrics [" + metricsEntry.getName() + "] with tag [" + tagEntry.getKey() + "]" ); - trimmedValue = null; - } - trimmedTags.put(trimmedKey, trimmedValue.toString()); - } - extractedKeyValues.put("tags", trimmedTags); - } - extractedKeyValues.putAll(metricsEntry.getSerializedKvs()); - - return extractedKeyValues; - } - - /** - * - * @param metricsMessage - * @param flushInterval flush interval in second - */ - private void putInfoKeyValues(Map metricsMessage, int flushInterval) { - metricsMessage.putAll(HostInfoUtils.getHostMetadata()); - - metricsMessage.put("Timestamp_u", Agent.currentTimeStamp()); - - metricsMessage.put("MetricsFlushInterval", flushInterval); - } -} diff --git a/agent/src/main/java/com/tracelytics/monitor/metrics/SpanMetricsCollector.java b/agent/src/main/java/com/tracelytics/monitor/metrics/SpanMetricsCollector.java deleted file mode 100644 index 2d954b6d..00000000 --- a/agent/src/main/java/com/tracelytics/monitor/metrics/SpanMetricsCollector.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.tracelytics.monitor.metrics; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import com.tracelytics.joboe.span.impl.InboundMetricMeasurementSpanReporter; -import com.tracelytics.joboe.span.impl.MetricHistogramSpanReporter; -import com.tracelytics.joboe.span.impl.MetricSpanReporter; -import com.tracelytics.joboe.span.impl.TransactionNameManager; -import com.tracelytics.metrics.MetricsEntry; -import com.tracelytics.metrics.TopLevelMetricsEntry; - -/** - * Sub metrics collector that collects span metrics (span histograms and measurements) - * @author pluk - * - */ -public class SpanMetricsCollector extends AbstractMetricsEntryCollector { - public static final String TRANSACTION_NAME_OVERFLOW_LABEL = "TransactionNameOverflow"; - private static Set registeredReporters = new HashSet(); - - static { - registeredReporters.add(InboundMetricMeasurementSpanReporter.REPORTER); - registeredReporters.add(MetricHistogramSpanReporter.REPORTER); - } - - SpanMetricsCollector() { - - } - - @Override - List> collectMetricsEntries() { - return collectMetricsEntries(registeredReporters); - } - - List> collectMetricsEntries(Set reporters) { - List> entries = new ArrayList>(); - for (MetricSpanReporter spanReporter : reporters) { - entries.addAll(spanReporter.consumeMetricEntries()); - } - - //add an extra entry if TransactionName limit was reached - if (TransactionNameManager.isLimitExceeded()) { - entries.add(new TopLevelMetricsEntry(TRANSACTION_NAME_OVERFLOW_LABEL, true)); - } - - TransactionNameManager.clearTransactionNames(); - - return entries; - } -} diff --git a/agent/src/main/java/com/tracelytics/monitor/metrics/SystemMetricsCollector.java b/agent/src/main/java/com/tracelytics/monitor/metrics/SystemMetricsCollector.java deleted file mode 100644 index b2668567..00000000 --- a/agent/src/main/java/com/tracelytics/monitor/metrics/SystemMetricsCollector.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.tracelytics.monitor.metrics; - -import com.tracelytics.metrics.measurement.SimpleMeasurementMetricsEntry; - -import java.lang.management.ManagementFactory; -import java.lang.management.OperatingSystemMXBean; -import java.util.ArrayList; -import java.util.List; - -/** - * Sub metrics collector that collectors metrics on system level, such as CPU load and memory usage - * @author pluk - * - */ -class SystemMetricsCollector extends AbstractMetricsEntryCollector { - @Override - List collectMetricsEntries() throws Exception { - List info = new ArrayList(); - - OperatingSystemMXBean operatingMXBean = ManagementFactory.getOperatingSystemMXBean(); - - try { - if (operatingMXBean instanceof com.sun.management.OperatingSystemMXBean) { - com.sun.management.OperatingSystemMXBean sunMXBean = (com.sun.management.OperatingSystemMXBean) operatingMXBean; - - info.add(new SimpleMeasurementMetricsEntry("TotalRAM", sunMXBean.getTotalPhysicalMemorySize())); - info.add(new SimpleMeasurementMetricsEntry("FreeRAM", sunMXBean.getFreePhysicalMemorySize())); - - try { - double loadAverage = operatingMXBean.getSystemLoadAverage(); - if (loadAverage >= 0) { - info.add(new SimpleMeasurementMetricsEntry("Load1", loadAverage)); - } else { - loadAverage = sunMXBean.getSystemCpuLoad(); - if (loadAverage >= 0) { - info.add(new SimpleMeasurementMetricsEntry("Load1", loadAverage)); - } - } - } catch (NoSuchMethodError e) { //jdk 1.6 - logger.debug("Heartbeat not tracking system load average, probably running JDK 1.6 or earlier"); - } - - - try { - double processLoad = sunMXBean.getProcessCpuLoad(); - if (processLoad >= 0) { - info.add(new SimpleMeasurementMetricsEntry("ProcessLoad", processLoad)); - } - } catch (NoSuchMethodError e) { //jdk 1.6 - logger.debug("Not tracking process load average, probably running JDK 1.6 or earlier"); - } - - } - } catch (NoClassDefFoundError e) { - logger.debug("com.sun.management.OperatingSystemMXBean is not found. A non Oracle/Sun JVM"); - } - - Runtime runtime = Runtime.getRuntime(); - info.add(new SimpleMeasurementMetricsEntry("ProcessRAM", runtime.totalMemory())); - - logger.debug("Collected Heartbeat: " + info); - - return info; - } -} diff --git a/agent/src/main/java/com/tracelytics/monitor/metrics/TraceDecisionMetricsCollector.java b/agent/src/main/java/com/tracelytics/monitor/metrics/TraceDecisionMetricsCollector.java deleted file mode 100644 index 43732419..00000000 --- a/agent/src/main/java/com/tracelytics/monitor/metrics/TraceDecisionMetricsCollector.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.tracelytics.monitor.metrics; - -import java.util.*; -import java.util.Map.Entry; - -import com.tracelytics.joboe.TraceDecisionUtil; -import com.tracelytics.joboe.TraceDecisionUtil.MetricType; -import com.tracelytics.joboe.TraceConfig; -import com.tracelytics.metrics.MetricsEntry; -import com.tracelytics.metrics.measurement.SimpleMeasurementMetricsEntry; - -/** - * Sub metrics collector that collects metrics recorded by {@link TraceDecisionUtil} such as "RequestCount", "TraceCount" - * @author Patson Luk - * - */ -class TraceDecisionMetricsCollector extends AbstractMetricsEntryCollector { - - @Override - List> collectMetricsEntries() { - List layerMetricsEntries = new ArrayList(); - - - layerMetricsEntries.add(getMetricEntry(MetricType.THROUGHPUT, "RequestCount")); - layerMetricsEntries.add(getMetricEntry(MetricType.TOKEN_BUCKET_EXHAUSTION, "TokenBucketExhaustionCount")); - layerMetricsEntries.add(getMetricEntry(MetricType.TRACE_COUNT, "TraceCount")); - layerMetricsEntries.add(getMetricEntry(MetricType.SAMPLE_COUNT, "SampleCount")); - layerMetricsEntries.add(getMetricEntry(MetricType.THROUGH_TRACE_COUNT, "ThroughTraceCount")); - layerMetricsEntries.add(getMetricEntry(MetricType.THROUGH_IGNORED_COUNT, "ThroughIgnoredCount")); - layerMetricsEntries.add(getMetricEntry(MetricType.TRIGGERED_TRACE_COUNT, "TriggeredTraceCount")); - - Map layerConfigs = TraceDecisionUtil.consumeLastTraceConfigs(); - - Map, Integer> layerSampleRate = new HashMap, Integer>(); - Map, Integer> layerSampleSource = new HashMap, Integer>(); - for (Entry layerConfig : layerConfigs.entrySet()) { - layerSampleRate.put(new AbstractMap.SimpleEntry("layer", layerConfig.getKey()), layerConfig.getValue().getSampleRate()); - layerSampleSource.put(new AbstractMap.SimpleEntry("layer", layerConfig.getKey()), layerConfig.getValue().getSampleRateSourceValue()); - } - - layerMetricsEntries.addAll(convertToMetricsEntries(layerSampleRate, "SampleRate")); - layerMetricsEntries.addAll(convertToMetricsEntries(layerSampleSource, "SampleSource")); - - return layerMetricsEntries; - } - - private SimpleMeasurementMetricsEntry getMetricEntry(MetricType metricType, String keyName) { - return new SimpleMeasurementMetricsEntry(keyName, Collections.emptyMap(), TraceDecisionUtil.consumeMetricsData(metricType)); - } - private List convertToMetricsEntries(Map, Integer> data, String keyName) { - List entries = new ArrayList(); - for (Entry, Integer> metricsEntry : data.entrySet()) { - Entry singleTag = metricsEntry.getKey(); - Map tags = Collections.singletonMap(singleTag.getKey(), singleTag.getValue()); - entries.add(new SimpleMeasurementMetricsEntry(keyName, tags, metricsEntry.getValue())); - } - return entries; - } -} diff --git a/agent/src/main/java/com/tracelytics/monitor/metrics/TracingReporterMetricsCollector.java b/agent/src/main/java/com/tracelytics/monitor/metrics/TracingReporterMetricsCollector.java deleted file mode 100644 index bf15b89e..00000000 --- a/agent/src/main/java/com/tracelytics/monitor/metrics/TracingReporterMetricsCollector.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.tracelytics.monitor.metrics; - -import java.util.ArrayList; -import java.util.List; - -import com.tracelytics.joboe.EventImpl; -import com.tracelytics.joboe.EventReporterStats; -import com.tracelytics.metrics.measurement.SimpleMeasurementMetricsEntry; - -/** - * Sub metrics collector that collects metrics specific to the Tracing event reporter such as number of tracing events sent, the largest queue size since last collection etc - * @author pluk - * - */ -class TracingReporterMetricsCollector extends AbstractMetricsEntryCollector { - @Override - List collectMetricsEntries() throws Exception { - EventReporterStats stats = EventImpl.getEventReporter().consumeStats(); - - List metricsEntries = new ArrayList(); - metricsEntries.add(new SimpleMeasurementMetricsEntry("NumSent", stats.getSentCount())); - metricsEntries.add(new SimpleMeasurementMetricsEntry("NumOverflowed", stats.getOverflowedCount())); - metricsEntries.add(new SimpleMeasurementMetricsEntry("NumFailed", stats.getFailedCount())); - metricsEntries.add(new SimpleMeasurementMetricsEntry("TotalEvents", stats.getProcessedCount())); - metricsEntries.add(new SimpleMeasurementMetricsEntry("QueueLargest", stats.getQueueLargestCount())); - - return metricsEntries; - } -} diff --git a/agent/src/test/java/com/tracelytics/agent/FrameworkRecorderTest.java b/agent/src/test/java/com/tracelytics/agent/FrameworkRecorderTest.java deleted file mode 100644 index 1e7794ab..00000000 --- a/agent/src/test/java/com/tracelytics/agent/FrameworkRecorderTest.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.tracelytics.agent; - -import com.tracelytics.agent.FrameworkRecorder.FrameworkInfo; -import com.tracelytics.joboe.JoboeTest; - -import java.util.jar.Attributes; - -public class FrameworkRecorderTest extends JoboeTest { - public void testExtractNoFramework() { - //manifest from ognl - Attributes attributes = new Attributes(); - attributes.putValue("Manifest-Version", "1.0"); - attributes.putValue("Archiver-Version", "Plexus Archiver"); - attributes.putValue("Created-By", "Apache Maven"); - attributes.putValue("Built-By", "lukaszlenart"); - attributes.putValue("Build-Jdk", "1.6.0_37"); - - FrameworkInfo frameworkInfo = FrameworkRecorder.extractInfoFromAttributes(attributes); - assertEquals(null, frameworkInfo); - } - - public void testExtractBundleFramework() { - //manifest from mongodb - - Attributes attributes = new Attributes(); - attributes.putValue("Manifest-Version", "1.0"); - attributes.putValue("Ant-Version", "Apache Ant 1.7.0"); - attributes.putValue("Created-By", "1.7.0-b21 (Sun Microsystems Inc.)"); - attributes.putValue("Bundle-ManifestVersion", "2"); - attributes.putValue("Bundle-Name", "MongoDB"); - attributes.putValue("Bundle-SymbolicName", "com.mongodb"); - attributes.putValue("Bundle-Version", "2.1.0"); - attributes.putValue("Export-Package", "com.mongodb, com.mongodb.io, com.mongodb.util, com.mongodb.gridfs, org.bson, org.bson.util, org.bson.types, org.bson.io"); - - FrameworkInfo frameworkInfo = FrameworkRecorder.extractInfoFromAttributes(attributes); - assertEquals("com.mongodb", frameworkInfo.getId()); - assertEquals("2.1.0", frameworkInfo.getVersion()); - } - - public void testExtractSpecificationFramework() { - //manifest from javassist - Attributes attributes = new Attributes(); - attributes.putValue("Manifest-Version", "1.1"); - attributes.putValue("Ant-Version", "Apache Ant 1.6.5"); - attributes.putValue("Created-By", "Shigeru Chiba, Tokyo Institute of Technology"); - attributes.putValue("Specification-Title", "Javassist"); - attributes.putValue("Specification-Vendor", "Shigeru Chiba, Tokyo Institute of Technology"); - attributes.putValue("Specification-Version", "3.11.0.GA"); - attributes.putValue("Main-Class", "javassist.CtClass"); - attributes.putValue("Name", "javassist/"); - - - FrameworkInfo frameworkInfo = FrameworkRecorder.extractInfoFromAttributes(attributes); - assertEquals("Javassist", frameworkInfo.getId()); - assertEquals("3.11.0.GA", frameworkInfo.getVersion()); - } - - public void testExtractImplementationFramework() { - //manifest from freemarker - Attributes attributes = new Attributes(); - attributes.putValue("Manifest-Version", "1.0"); - attributes.putValue("Ant-Version", "Apache Ant 1.8.1"); - attributes.putValue("Created-By", "1.6.0_22-b04 (Sun Microsystems Inc.)"); - attributes.putValue("Main-Class", "freemarker.core.CommandLine"); - attributes.putValue("Extension-name", "FreeMarker"); - attributes.putValue("Specification-Title", "FreeMarker"); - attributes.putValue("Specification-Version", "2.3.19"); - attributes.putValue("Specification-Vendor", "Visigoth Software Society"); - attributes.putValue("Implementation-Title", "VSS Java FreeMarker"); - attributes.putValue("Implementation-Version", "2.3.19"); - attributes.putValue("Implementation-Vendor", "Visigoth Software Society"); - - FrameworkInfo frameworkInfo = FrameworkRecorder.extractInfoFromAttributes(attributes); - assertEquals("VSS Java FreeMarker", frameworkInfo.getId()); - assertEquals("2.3.19", frameworkInfo.getVersion()); - } -} diff --git a/agent/src/test/java/com/tracelytics/joboe/AgentHostInfoReaderTest.java b/agent/src/test/java/com/tracelytics/joboe/AgentHostInfoReaderTest.java deleted file mode 100644 index e672c9c8..00000000 --- a/agent/src/test/java/com/tracelytics/joboe/AgentHostInfoReaderTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.tracelytics.joboe; - -import com.tracelytics.util.HostInfoUtils.NetworkAddressInfo; -import junit.framework.TestCase; - -import java.io.*; -import java.util.Map; - -public class AgentHostInfoReaderTest extends TestCase { - private static final String TEST_FILE_FOLDER = "src/test/java/com/tracelytics/joboe/"; //using a rather static path. Using Class.getResourceAsStream does not work in test (vs main) - private AgentHostInfoReader reader = AgentHostInfoReader.INSTANCE; - - public void testGetDistroParsing() throws IOException { - assertEquals("Red Hat Enterprise Linux Server release 6.5 (Santiago)", AgentHostInfoReader.getRedHatBasedDistro(getFileReader(AgentHostInfoReader.DistroType.REDHAT_BASED))); - assertEquals("Amzn Linux 2015.09", AgentHostInfoReader.getAmazonLinuxDistro(getFileReader(AgentHostInfoReader.DistroType.AMAZON))); - assertEquals("Ubuntu 10.04.2 LTS", AgentHostInfoReader.getUbuntuDistro(getFileReader(AgentHostInfoReader.DistroType.UBUNTU))); - assertEquals("Debian 7.7", AgentHostInfoReader.getDebianDistro(getFileReader(AgentHostInfoReader.DistroType.DEBIAN))); - assertEquals("SUSE Linux Enterprise Server 10 (x86_64)", AgentHostInfoReader.getNovellSuseDistro(getFileReader(AgentHostInfoReader.DistroType.SUSE))); - assertEquals("Slackware-x86_64 13.0", AgentHostInfoReader.getSlackwareDistro(getFileReader(AgentHostInfoReader.DistroType.SLACKWARE))); - assertEquals("Gentoo Base System release 2.1", AgentHostInfoReader.getGentooDistro(getFileReader(AgentHostInfoReader.DistroType.GENTOO))); - } - - private BufferedReader getFileReader(AgentHostInfoReader.DistroType distroType) throws FileNotFoundException { - String path = AgentHostInfoReader.DISTRO_FILE_NAMES.get(distroType); - String fileName = new File(path).getName(); - - return new BufferedReader(new FileReader(TEST_FILE_FOLDER + fileName)); - } - - public void testGetHostMetadata() { - Map hostMetadata = reader.getHostMetadata(); - - assert(hostMetadata.containsKey("UnameSysName")); - assert(hostMetadata.containsKey("UnameVersion")); - assert(hostMetadata.containsKey("Distro")); - NetworkAddressInfo networkInfo = reader.getNetworkAddressInfo(); - if (networkInfo != null) { - if (!networkInfo.getIpAddresses().isEmpty()) { - assert(hostMetadata.containsKey("IPAddresses")); - } - } - } - - public void testGetHostId() { - HostId hostId = reader.getHostId(); - assertEquals(reader.getHostName(), hostId.getHostname()); - assertEquals(reader.getAwsInstanceId(), hostId.getEc2InstanceId()); - assertEquals(reader.getAwsAvailabilityZone(), hostId.getEc2AvailabilityZone()); - assertEquals(reader.getDockerContainerId(), hostId.getDockerContainerId()); - assertEquals(reader.getHerokuDynoId(), hostId.getHerokuDynoId()); - assertEquals(reader.getNetworkAddressInfo().getMacAddresses(), hostId.getMacAddresses()); - - } - - - - -} diff --git a/agent/src/test/java/com/tracelytics/joboe/DockerInfoReaderTest.java b/agent/src/test/java/com/tracelytics/joboe/DockerInfoReaderTest.java deleted file mode 100644 index b326cf89..00000000 --- a/agent/src/test/java/com/tracelytics/joboe/DockerInfoReaderTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.tracelytics.joboe; - -import java.io.IOException; - -import com.tracelytics.joboe.AgentHostInfoReader.DockerInfoReader; - -import junit.framework.TestCase; - -public class DockerInfoReaderTest extends TestCase { - private static final String TEST_FILE_PREFIX = "src/test/java/com/tracelytics/joboe/docker-cgroup-"; //using a rather static path. Using Class.getResourceAsStream does not work in test (vs main) - - @Override - protected void tearDown() throws Exception { - DockerInfoReader.SINGLETON.initializeLinux(DockerInfoReader.DEFAULT_LINUX_DOCKER_FILE_LOCATION); //reset to default - super.tearDown(); - } - - public void testReadDockerContainerId() throws IOException { - DockerInfoReader.SINGLETON.initializeLinux(TEST_FILE_PREFIX + "standard"); - assertEquals("0531ff3c6395131175507ac7e94fdf387f2a2dea81961e6c96f6ac5ccd7ede3f", DockerInfoReader.getDockerId()); - - DockerInfoReader.SINGLETON.initializeLinux(TEST_FILE_PREFIX + "standard-2"); - assertEquals("0531ff3c6395131175507ac7e94fdf387f2a2dea81961e6c96f6ac5ccd7ede3f", DockerInfoReader.getDockerId()); - - DockerInfoReader.SINGLETON.initializeLinux(TEST_FILE_PREFIX + "ce"); - assertEquals("93d377d55070d2463493706ba7194d119c3efb1c2e7929f36da183ffe71d72a8", DockerInfoReader.getDockerId()); - - DockerInfoReader.SINGLETON.initializeLinux(TEST_FILE_PREFIX + "ecs"); - assertEquals("93d377d55070d2463493706ba7194d119c3efb1c2e7929f36da183ffe71d72a8", DockerInfoReader.getDockerId()); - - DockerInfoReader.SINGLETON.initializeLinux(TEST_FILE_PREFIX + "empty"); - assertEquals(null, DockerInfoReader.getDockerId()); - - DockerInfoReader.SINGLETON.initializeLinux(TEST_FILE_PREFIX + "non-docker"); - assertEquals(null, DockerInfoReader.getDockerId()); - - DockerInfoReader.SINGLETON.initializeLinux(TEST_FILE_PREFIX + "invalid"); - assertEquals(null, DockerInfoReader.getDockerId()); - } -} diff --git a/agent/src/test/java/com/tracelytics/joboe/SuSE-release b/agent/src/test/java/com/tracelytics/joboe/SuSE-release deleted file mode 100644 index c7841938..00000000 --- a/agent/src/test/java/com/tracelytics/joboe/SuSE-release +++ /dev/null @@ -1,3 +0,0 @@ -SUSE Linux Enterprise Server 10 (x86_64) -VERSION = 10 -PATCHLEVEL = 4 \ No newline at end of file diff --git a/agent/src/test/java/com/tracelytics/joboe/TestSubmitRejectionRpcClient.java b/agent/src/test/java/com/tracelytics/joboe/TestSubmitRejectionRpcClient.java deleted file mode 100644 index 1eb615fc..00000000 --- a/agent/src/test/java/com/tracelytics/joboe/TestSubmitRejectionRpcClient.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.tracelytics.joboe; - -import com.tracelytics.joboe.rpc.*; - -import java.util.List; -import java.util.Map; -import java.util.concurrent.Future; -import java.util.concurrent.RejectedExecutionException; - -public class TestSubmitRejectionRpcClient implements Client { - public Future postEvents(List events, Callback callback) throws ClientException { - throw new ClientRejectedExecutionException(new RejectedExecutionException("Testing submit client exception")); - } - - public Future postMetrics(List> messages, Callback callback) throws ClientException { - throw new ClientRejectedExecutionException(new RejectedExecutionException("Testing submit client exception")); - } - - public Future postStatus(List> messages, Callback callback) throws ClientException { - throw new ClientRejectedExecutionException(new RejectedExecutionException("Testing submit client exception")); - } - - public Future getSettings(String version, Callback callback) throws ClientException { - throw new ClientRejectedExecutionException(new RejectedExecutionException("Testing submit client exception")); - } - - public void close() { - } - - public Status getStatus() { - return Status.OK; - } -} \ No newline at end of file diff --git a/agent/src/test/java/com/tracelytics/joboe/debian_version b/agent/src/test/java/com/tracelytics/joboe/debian_version deleted file mode 100644 index 120096f1..00000000 --- a/agent/src/test/java/com/tracelytics/joboe/debian_version +++ /dev/null @@ -1 +0,0 @@ -7.7 \ No newline at end of file diff --git a/agent/src/test/java/com/tracelytics/joboe/docker-cgroup-ce b/agent/src/test/java/com/tracelytics/joboe/docker-cgroup-ce deleted file mode 100644 index 0a5cdaf5..00000000 --- a/agent/src/test/java/com/tracelytics/joboe/docker-cgroup-ce +++ /dev/null @@ -1,13 +0,0 @@ -13:name=systemd:/docker-ce/docker/93d377d55070d2463493706ba7194d119c3efb1c2e7929f36da183ffe71d72a8 -12:pids:/docker-ce/docker/93d377d55070d2463493706ba7194d119c3efb1c2e7929f36da183ffe71d72a8 -11:hugetlb:/docker-ce/docker/93d377d55070d2463493706ba7194d119c3efb1c2e7929f36da183ffe71d72a8 -10:net_prio:/docker-ce/docker/93d377d55070d2463493706ba7194d119c3efb1c2e7929f36da183ffe71d72a8 -9:perf_event:/docker-ce/docker/93d377d55070d2463493706ba7194d119c3efb1c2e7929f36da183ffe71d72a8 -8:net_cls:/docker-ce/docker/93d377d55070d2463493706ba7194d119c3efb1c2e7929f36da183ffe71d72a8 -7:freezer:/docker-ce/docker/93d377d55070d2463493706ba7194d119c3efb1c2e7929f36da183ffe71d72a8 -6:devices:/docker-ce/docker/93d377d55070d2463493706ba7194d119c3efb1c2e7929f36da183ffe71d72a8 -5:memory:/docker-ce/docker/93d377d55070d2463493706ba7194d119c3efb1c2e7929f36da183ffe71d72a8 -4:blkio:/docker-ce/docker/93d377d55070d2463493706ba7194d119c3efb1c2e7929f36da183ffe71d72a8 -3:cpuacct:/docker-ce/docker/93d377d55070d2463493706ba7194d119c3efb1c2e7929f36da183ffe71d72a8 -2:cpu:/docker-ce/docker/93d377d55070d2463493706ba7194d119c3efb1c2e7929f36da183ffe71d72a8 -1:cpuset:/docker-ce/docker/93d377d55070d2463493706ba7194d119c3efb1c2e7929f36da183ffe71d72a8 \ No newline at end of file diff --git a/agent/src/test/java/com/tracelytics/joboe/docker-cgroup-ecs b/agent/src/test/java/com/tracelytics/joboe/docker-cgroup-ecs deleted file mode 100644 index ed78ea3e..00000000 --- a/agent/src/test/java/com/tracelytics/joboe/docker-cgroup-ecs +++ /dev/null @@ -1,13 +0,0 @@ -13:name=systemd:/ecs/task-arn/93d377d55070d2463493706ba7194d119c3efb1c2e7929f36da183ffe71d72a8 -12:pids:/ecs/task-arn/93d377d55070d2463493706ba7194d119c3efb1c2e7929f36da183ffe71d72a8 -11:hugetlb:/ecs/task-arn/93d377d55070d2463493706ba7194d119c3efb1c2e7929f36da183ffe71d72a8 -10:net_prio:/ecs/task-arn/93d377d55070d2463493706ba7194d119c3efb1c2e7929f36da183ffe71d72a8 -9:perf_event:/ecs/task-arn/93d377d55070d2463493706ba7194d119c3efb1c2e7929f36da183ffe71d72a8 -8:net_cls:/ecs/task-arn/93d377d55070d2463493706ba7194d119c3efb1c2e7929f36da183ffe71d72a8 -7:freezer:/ecs/task-arn/93d377d55070d2463493706ba7194d119c3efb1c2e7929f36da183ffe71d72a8 -6:devices:/ecs/task-arn/93d377d55070d2463493706ba7194d119c3efb1c2e7929f36da183ffe71d72a8 -5:memory:/ecs/task-arn/93d377d55070d2463493706ba7194d119c3efb1c2e7929f36da183ffe71d72a8 -4:blkio:/ecs/task-arn/93d377d55070d2463493706ba7194d119c3efb1c2e7929f36da183ffe71d72a8 -3:cpuacct:/ecs/task-arn/93d377d55070d2463493706ba7194d119c3efb1c2e7929f36da183ffe71d72a8 -2:cpu:/ecs/task-arn/93d377d55070d2463493706ba7194d119c3efb1c2e7929f36da183ffe71d72a8 -1:cpuset:/ecs/task-arn/93d377d55070d2463493706ba7194d119c3efb1c2e7929f36da183ffe71d72a8 \ No newline at end of file diff --git a/agent/src/test/java/com/tracelytics/joboe/docker-cgroup-empty b/agent/src/test/java/com/tracelytics/joboe/docker-cgroup-empty deleted file mode 100644 index e69de29b..00000000 diff --git a/agent/src/test/java/com/tracelytics/joboe/docker-cgroup-invalid b/agent/src/test/java/com/tracelytics/joboe/docker-cgroup-invalid deleted file mode 100644 index ec00544e..00000000 --- a/agent/src/test/java/com/tracelytics/joboe/docker-cgroup-invalid +++ /dev/null @@ -1 +0,0 @@ -10:memory:/docker/non-container-id diff --git a/agent/src/test/java/com/tracelytics/joboe/docker-cgroup-non-docker b/agent/src/test/java/com/tracelytics/joboe/docker-cgroup-non-docker deleted file mode 100644 index c93c71ea..00000000 --- a/agent/src/test/java/com/tracelytics/joboe/docker-cgroup-non-docker +++ /dev/null @@ -1,10 +0,0 @@ -10:memory:/user.slice/user-1000.slice -9:blkio:/user.slice/user-1000.slice -8:net_cls,net_prio:/ -7:cpu,cpuacct:/user.slice/user-1000.slice -6:perf_event:/ -5:freezer:/ -4:cpuset:/ -3:pids:/user.slice/user-1000.slice -2:devices:/user.slice/user-1000.slice -1:name=systemd:/user.slice/user-1000.slice/session-3.scope \ No newline at end of file diff --git a/agent/src/test/java/com/tracelytics/joboe/docker-cgroup-standard b/agent/src/test/java/com/tracelytics/joboe/docker-cgroup-standard deleted file mode 100644 index 6434495c..00000000 --- a/agent/src/test/java/com/tracelytics/joboe/docker-cgroup-standard +++ /dev/null @@ -1,11 +0,0 @@ -11:cpuset:/docker/0531ff3c6395131175507ac7e94fdf387f2a2dea81961e6c96f6ac5ccd7ede3f -10:memory:/docker/0531ff3c6395131175507ac7e94fdf387f2a2dea81961e6c96f6ac5ccd7ede3f -9:net_cls,net_prio:/docker/0531ff3c6395131175507ac7e94fdf387f2a2dea81961e6c96f6ac5ccd7ede3f -8:pids:/docker/0531ff3c6395131175507ac7e94fdf387f2a2dea81961e6c96f6ac5ccd7ede3f -7:blkio:/docker/0531ff3c6395131175507ac7e94fdf387f2a2dea81961e6c96f6ac5ccd7ede3f -6:cpu,cpuacct:/docker/0531ff3c6395131175507ac7e94fdf387f2a2dea81961e6c96f6ac5ccd7ede3f -5:perf_event:/docker/0531ff3c6395131175507ac7e94fdf387f2a2dea81961e6c96f6ac5ccd7ede3f -4:freezer:/docker/0531ff3c6395131175507ac7e94fdf387f2a2dea81961e6c96f6ac5ccd7ede3f -3:hugetlb:/docker/0531ff3c6395131175507ac7e94fdf387f2a2dea81961e6c96f6ac5ccd7ede3f -2:devices:/docker/0531ff3c6395131175507ac7e94fdf387f2a2dea81961e6c96f6ac5ccd7ede3f -1:name=systemd:/docker/0531ff3c6395131175507ac7e94fdf387f2a2dea81961e6c96f6ac5ccd7ede3f \ No newline at end of file diff --git a/agent/src/test/java/com/tracelytics/joboe/docker-cgroup-standard-2 b/agent/src/test/java/com/tracelytics/joboe/docker-cgroup-standard-2 deleted file mode 100644 index 6938c567..00000000 --- a/agent/src/test/java/com/tracelytics/joboe/docker-cgroup-standard-2 +++ /dev/null @@ -1,11 +0,0 @@ -11:cpuset:abc -10:memory:abc -9:net_cls,net_prio:abc -8:pids:abc -7:blkio:abc -6:cpu,cpuacct:abc -5:perf_event:abc -4:freezer:abc -3:hugetlb:abc -2:devices:abc -1:name=systemd:/docker/0531ff3c6395131175507ac7e94fdf387f2a2dea81961e6c96f6ac5ccd7ede3f \ No newline at end of file diff --git a/agent/src/test/java/com/tracelytics/joboe/gentoo-release b/agent/src/test/java/com/tracelytics/joboe/gentoo-release deleted file mode 100644 index e3636f5b..00000000 --- a/agent/src/test/java/com/tracelytics/joboe/gentoo-release +++ /dev/null @@ -1 +0,0 @@ -Gentoo Base System release 2.1 \ No newline at end of file diff --git a/agent/src/test/java/com/tracelytics/joboe/lsb-release b/agent/src/test/java/com/tracelytics/joboe/lsb-release deleted file mode 100644 index 3a9d6913..00000000 --- a/agent/src/test/java/com/tracelytics/joboe/lsb-release +++ /dev/null @@ -1,4 +0,0 @@ -DISTRIB_ID=Ubuntu -DISTRIB_RELEASE=10.04 -DISTRIB_CODENAME=lucid -DISTRIB_DESCRIPTION="Ubuntu 10.04.2 LTS" \ No newline at end of file diff --git a/agent/src/test/java/com/tracelytics/joboe/redhat-release b/agent/src/test/java/com/tracelytics/joboe/redhat-release deleted file mode 100644 index 0fa975a2..00000000 --- a/agent/src/test/java/com/tracelytics/joboe/redhat-release +++ /dev/null @@ -1 +0,0 @@ -Red Hat Enterprise Linux Server release 6.5 (Santiago) \ No newline at end of file diff --git a/agent/src/test/java/com/tracelytics/joboe/slackware-version b/agent/src/test/java/com/tracelytics/joboe/slackware-version deleted file mode 100644 index fb17e310..00000000 --- a/agent/src/test/java/com/tracelytics/joboe/slackware-version +++ /dev/null @@ -1 +0,0 @@ -Slackware-x86_64 13.0 \ No newline at end of file diff --git a/agent/src/test/java/com/tracelytics/joboe/system-release-cpe b/agent/src/test/java/com/tracelytics/joboe/system-release-cpe deleted file mode 100644 index a4522960..00000000 --- a/agent/src/test/java/com/tracelytics/joboe/system-release-cpe +++ /dev/null @@ -1 +0,0 @@ -cpe:/o:amazon:linux:2015.09:ga \ No newline at end of file diff --git a/agent/src/test/java/com/tracelytics/metrics/histogram/HdrHistrogramAdapterTest.java b/agent/src/test/java/com/tracelytics/metrics/histogram/HdrHistrogramAdapterTest.java deleted file mode 100644 index 6564cd97..00000000 --- a/agent/src/test/java/com/tracelytics/metrics/histogram/HdrHistrogramAdapterTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.tracelytics.metrics.histogram; - -import java.nio.ByteBuffer; - -import com.tracelytics.ext.base64.Base64; -import com.tracelytics.joboe.JoboeTest; -import com.tracelytics.metrics.histogram.HdrHistogramAdapter; -import com.tracelytics.metrics.histogram.HistogramFactory; -import com.tracelytics.metrics.histogram.HistogramOutOfRangeException; - -public class HdrHistrogramAdapterTest extends JoboeTest { - private static long MAX_VALUE = 60L * 60 * 1000 * 1000; - public void testEncode() throws Exception { - HdrHistogramAdapter testHistogram = new HdrHistogramAdapter(MAX_VALUE, HistogramFactory.NUMBER_OF_SIGNIFICANT_VALUE_DIGITS); - - testHistogram.recordValue(3335); - testHistogram.recordValue(3108); - testHistogram.recordValue(2638); - testHistogram.recordValue(2567); - testHistogram.recordValue(2470); - - byte[] encoded = testHistogram.encodeBase64(); - - String expectedEncodedString = "HISTFAAAAC14nJNpmSzMwMDAywABzFCaEURcm7yEwf4DRGCpMlMskyvTZWam+4xMAKW6B74="; //extracted from encode call of above values from c-lib - assertEquals(expectedEncodedString, new String(encoded)); - - ByteBuffer buffer = ByteBuffer.allocate(encoded.length); - buffer.put(Base64.decode(encoded)); - buffer.rewind(); - - com.tracelytics.ext.hdrHistogram.Histogram readHistogram = com.tracelytics.ext.hdrHistogram.Histogram.decodeFromCompressedByteBuffer(buffer, 0); - - assertEquals(testHistogram.getUnderlyingHistogram(), readHistogram); - } - - public void testRange() throws Exception { - - HdrHistogramAdapter testHistogram = new HdrHistogramAdapter(MAX_VALUE, HistogramFactory.NUMBER_OF_SIGNIFICANT_VALUE_DIGITS); - - testHistogram.recordValue(111); //ok - testHistogram.recordValue(0); //MIN_VALUE ok - testHistogram.recordValue(MAX_VALUE); //MAX_VALUE OK - - try { - testHistogram.recordValue(-1); //negative value not ok - fail("Expect exception " + HistogramOutOfRangeException.class.getName() + " to be thrown"); - } catch (HistogramOutOfRangeException e) { - //expected - } - - try { - testHistogram.recordValue(MAX_VALUE + 1); //greater than MAX_VALUE not ok - fail("Expect exception " + HistogramOutOfRangeException.class.getName() + " to be thrown"); - } catch (HistogramOutOfRangeException e) { - //expected - } - - } -} diff --git a/agent/src/test/java/com/tracelytics/metrics/histogram/MockHistogramAdapter.java b/agent/src/test/java/com/tracelytics/metrics/histogram/MockHistogramAdapter.java deleted file mode 100644 index 75f23c62..00000000 --- a/agent/src/test/java/com/tracelytics/metrics/histogram/MockHistogramAdapter.java +++ /dev/null @@ -1,122 +0,0 @@ -package com.tracelytics.metrics.histogram; - -public class MockHistogramAdapter implements Histogram { - private Double percentile; - private long totalCount; - private long sum; - private long max; - private long min; - private Double standardDeviation; - private Long last; - private Long countHigherThanValue; - - public MockHistogramAdapter(Double percentile, long totalCount, long sum, long max, long min, Double standardDeviation, long last, long countHigherThanValue) { - super(); - this.percentile = percentile; - this.totalCount = totalCount; - this.sum = sum; - this.max = max; - this.min = min; - this.standardDeviation = standardDeviation; - this.last = last; - this.countHigherThanValue = countHigherThanValue; - } - - public Double getPercentile(double percentile) { - return percentile; - } - public long getTotalCount() { - return totalCount; - } - public long getSum() { - return sum; - } - public long getMax() { - return max; - } - public long getMin() { - return min; - } - public Double getStandardDeviation() { - return standardDeviation; - } - public Long getLast() { - return last; - } - public Long getCountHigherThanValue(long value) { - return countHigherThanValue; - } - - public void recordValue(long value) { - // TODO Auto-generated method stub - - } - public void reset() { - // TODO Auto-generated method stub - - } - - - - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((countHigherThanValue == null) ? 0 : countHigherThanValue.hashCode()); - result = prime * result + ((last == null) ? 0 : last.hashCode()); - result = prime * result + (int) (max ^ (max >>> 32)); - result = prime * result + (int) (min ^ (min >>> 32)); - result = prime * result + ((percentile == null) ? 0 : percentile.hashCode()); - result = prime * result + ((standardDeviation == null) ? 0 : standardDeviation.hashCode()); - result = prime * result + (int) (sum ^ (sum >>> 32)); - result = prime * result + (int) (totalCount ^ (totalCount >>> 32)); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - MockHistogramAdapter other = (MockHistogramAdapter) obj; - if (countHigherThanValue == null) { - if (other.countHigherThanValue != null) - return false; - } else if (!countHigherThanValue.equals(other.countHigherThanValue)) - return false; - if (last == null) { - if (other.last != null) - return false; - } else if (!last.equals(other.last)) - return false; - if (max != other.max) - return false; - if (min != other.min) - return false; - if (percentile == null) { - if (other.percentile != null) - return false; - } else if (!percentile.equals(other.percentile)) - return false; - if (standardDeviation == null) { - if (other.standardDeviation != null) - return false; - } else if (!standardDeviation.equals(other.standardDeviation)) - return false; - if (sum != other.sum) - return false; - if (totalCount != other.totalCount) - return false; - return true; - } - - public byte[] encodeBase64() { - return new byte[0]; - } - - -} diff --git a/agent/src/test/java/com/tracelytics/monitor/SystemMonitorControllerTest.java b/agent/src/test/java/com/tracelytics/monitor/SystemMonitorControllerTest.java deleted file mode 100644 index 9f0ee203..00000000 --- a/agent/src/test/java/com/tracelytics/monitor/SystemMonitorControllerTest.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.tracelytics.monitor; - -import com.tracelytics.joboe.JoboeTest; -import com.tracelytics.joboe.config.ConfigContainer; - -public class SystemMonitorControllerTest extends JoboeTest { - - public void testStart() throws InterruptedException { - SystemMonitorController.start(); - SystemMonitorController.stop(); - } -} diff --git a/agent/src/test/java/com/tracelytics/monitor/SystemMonitorFactoryTest.java b/agent/src/test/java/com/tracelytics/monitor/SystemMonitorFactoryTest.java deleted file mode 100644 index d4dab044..00000000 --- a/agent/src/test/java/com/tracelytics/monitor/SystemMonitorFactoryTest.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.tracelytics.monitor; - -import java.util.List; - -import com.tracelytics.joboe.JoboeTest; -import com.tracelytics.joboe.config.ConfigContainer; -import com.tracelytics.joboe.config.ConfigProperty; -import com.tracelytics.joboe.config.InvalidConfigException; - -public class SystemMonitorFactoryTest extends JoboeTest { - - /** - * Test with empty config - * @throws InvalidConfigException - */ - public void testBuildCollectors1() throws InvalidConfigException { - ConfigContainer configs = new ConfigContainer(); - - configs.putByStringValue(ConfigProperty.MONITOR_JMX_MAX_ENTRY, "200"); - configs.putByStringValue(ConfigProperty.MONITOR_JMX_SCOPES, "{\"java.lang:type=MemoryPool,*\":[\"Usage\"],\"java.lang:type=Memory\":[\"HeapMemoryUsage\",\"NonHeapMemoryUsage\"]}"); - configs.putByStringValue(ConfigProperty.MONITOR_JMX_ENABLE, "true"); - - SystemMonitorFactory factory = new SystemMonitorFactoryImpl(configs); - - List> monitors = factory.buildMonitors(); - - //FrameworkInfoMonitor and MetricsMonitor - assertEquals(2, monitors.size()); - } - - /** - * Test with config that disables the JMX monitoring - * @throws InvalidConfigException - */ - public void testBuildCollectors2() throws InvalidConfigException { - ConfigContainer configs = new ConfigContainer(); - - configs.putByStringValue(ConfigProperty.MONITOR_JMX_MAX_ENTRY, "200"); - configs.putByStringValue(ConfigProperty.MONITOR_JMX_SCOPES, "{\"java.lang:type=MemoryPool,*\":[\"Usage\"],\"java.lang:type=Memory\":[\"HeapMemoryUsage\",\"NonHeapMemoryUsage\"]}"); - configs.putByStringValue(ConfigProperty.MONITOR_JMX_ENABLE, "false"); - - SystemMonitorFactory factory = new SystemMonitorFactoryImpl(configs); - - List monitors = factory.buildMonitors(); - - //build 2 monitors. As Metric monitor is still required for other metrics - assertEquals(2, monitors.size()); - } -} diff --git a/agent/src/test/java/com/tracelytics/monitor/SystemMonitorWithFrequencyTest.java b/agent/src/test/java/com/tracelytics/monitor/SystemMonitorWithFrequencyTest.java deleted file mode 100644 index 70d737f8..00000000 --- a/agent/src/test/java/com/tracelytics/monitor/SystemMonitorWithFrequencyTest.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.tracelytics.monitor; - -import java.lang.reflect.Method; -import java.text.SimpleDateFormat; -import java.util.Locale; - -import com.tracelytics.joboe.JoboeTest; -import com.tracelytics.joboe.config.InvalidConfigException; -import com.tracelytics.monitor.SystemMonitorWithFrequency.TimeUnit; - -public class SystemMonitorWithFrequencyTest extends JoboeTest { - - public void testGetSleep() throws Exception { - Method getSleepTimeMethod = SystemMonitorWithFrequency.class.getDeclaredMethod("getSleepTime", long.class); - getSleepTimeMethod.setAccessible(true); - - SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.CANADA); - long testTime; - - //set at the midnight - testTime = dataFormat.parse("2000-01-01 00:00:00.000").getTime(); - assertEquals((long)6 * 60 * 1000, getSleepTimeMethod.invoke(new TestingSystemMonitorWithFequency(TimeUnit.PER_HOUR, 10), testTime)); //report at next mark - assertEquals((long)30 * 1000, getSleepTimeMethod.invoke(new TestingSystemMonitorWithFequency(TimeUnit.PER_MINUTE, 2), testTime)); //report at next mark - assertEquals((long)100, getSleepTimeMethod.invoke(new TestingSystemMonitorWithFequency(TimeUnit.PER_SECOND, 10), testTime)); //report at next mark - - //set at the 01:00:00 - testTime = dataFormat.parse("2000-01-01 01:00:00.000").getTime(); - assertEquals((long)6 * 60 * 1000, getSleepTimeMethod.invoke(new TestingSystemMonitorWithFequency(TimeUnit.PER_HOUR, 10), testTime)); //report at next mark - assertEquals((long)30 * 1000, getSleepTimeMethod.invoke(new TestingSystemMonitorWithFequency(TimeUnit.PER_MINUTE, 2), testTime)); //report at next mark - assertEquals((long)100, getSleepTimeMethod.invoke(new TestingSystemMonitorWithFequency(TimeUnit.PER_SECOND, 10), testTime)); //report at next mark - - //set at the 00:01:00 - testTime = dataFormat.parse("2000-01-01 00:01:00.000").getTime(); - assertEquals((long)5 * 60 * 1000, getSleepTimeMethod.invoke(new TestingSystemMonitorWithFequency(TimeUnit.PER_HOUR, 10), testTime)); //should report at 00:06:00, sleep for 5 mins - assertEquals((long)30 * 1000, getSleepTimeMethod.invoke(new TestingSystemMonitorWithFequency(TimeUnit.PER_MINUTE, 2), testTime)); //report at next mark - assertEquals((long)100, getSleepTimeMethod.invoke(new TestingSystemMonitorWithFequency(TimeUnit.PER_SECOND, 10), testTime)); //report at next mark - - //set at the 00:00:01 - testTime = dataFormat.parse("2000-01-01 00:00:01.000").getTime(); - assertEquals((long)(6 * 60 -1) * 1000, getSleepTimeMethod.invoke(new TestingSystemMonitorWithFequency(TimeUnit.PER_HOUR, 10), testTime)); //should report at 00:06:00, sleep for 5 mins 59 secs - assertEquals((long)29 * 1000, getSleepTimeMethod.invoke(new TestingSystemMonitorWithFequency(TimeUnit.PER_MINUTE, 2), testTime)); //should report at 00:00:30, sleep for 29 secs - assertEquals((long)100, getSleepTimeMethod.invoke(new TestingSystemMonitorWithFequency(TimeUnit.PER_SECOND, 10), testTime)); //report at next mark - - //set at the 00:00:00.001 - testTime = dataFormat.parse("2000-01-01 00:00:00.001").getTime(); - assertEquals((long)6 * 60 * 1000 - 1, getSleepTimeMethod.invoke(new TestingSystemMonitorWithFequency(TimeUnit.PER_HOUR, 10), testTime)); //should report at 00:06:00, sleep for 5 mins 59.999 secs - assertEquals((long)30 * 1000 - 1, getSleepTimeMethod.invoke(new TestingSystemMonitorWithFequency(TimeUnit.PER_MINUTE, 2), testTime)); //should report at 00:00:30, sleep for 29.999 secs - assertEquals((long)99, getSleepTimeMethod.invoke(new TestingSystemMonitorWithFequency(TimeUnit.PER_SECOND, 10), testTime)); //should report at 00:00:00.100, sleep for 99 ms - - - //set at the 23:59:59.999 - testTime = dataFormat.parse("2000-01-01 23:59:59.999").getTime(); - assertEquals((long)1, getSleepTimeMethod.invoke(new TestingSystemMonitorWithFequency(TimeUnit.PER_HOUR, 10), testTime)); //sleep for 1 ms - assertEquals((long)1, getSleepTimeMethod.invoke(new TestingSystemMonitorWithFequency(TimeUnit.PER_MINUTE, 2), testTime)); //sleep for 1 ms - assertEquals((long)1, getSleepTimeMethod.invoke(new TestingSystemMonitorWithFequency(TimeUnit.PER_SECOND, 10), testTime)); //sleep for 1 ms - } - - public void testSetInterval() throws Exception { - Method getSleepTimeMethod = SystemMonitorWithFrequency.class.getDeclaredMethod("getSleepTime", long.class); - getSleepTimeMethod.setAccessible(true); - - SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.CANADA); - long testTime = dataFormat.parse("2000-01-01 00:00:01.000").getTime(); - TestingSystemMonitorWithFequency monitor = new TestingSystemMonitorWithFequency(TimeUnit.PER_MINUTE, 2); - monitor.setInterval(10 * 1000); //10 secs - assertEquals((long) (10 - 1) * 1000, getSleepTimeMethod.invoke(monitor, testTime)); //sleep for 9 sec - monitor.setInterval(60 * 1000); // 1 min - assertEquals((long) (60 - 1) * 1000, getSleepTimeMethod.invoke(monitor, testTime)); //sleep for 59 sec - monitor.setInterval(10 * 60 * 1000); // 10 min - assertEquals((long) (10 * 60 - 1) * 1000, getSleepTimeMethod.invoke(monitor, testTime)); //sleep for 599 sec - try { - monitor.setInterval(7 * 1000); //7 secs, not valid - fail(); - } catch (InvalidConfigException e) { - //expected - } - } - - private class TestingSystemMonitorWithFequency extends SystemMonitorWithFrequency { - public TestingSystemMonitorWithFequency(TimeUnit timeUnit, int frequency) throws InvalidConfigException { - super(timeUnit, frequency, null, null); - } - - @Override - protected String getMonitorName() { - // TODO Auto-generated method stub - return null; - } - } - - - - -} diff --git a/agent/src/test/java/com/tracelytics/monitor/framework/FrameworkInfoReporterTest.java b/agent/src/test/java/com/tracelytics/monitor/framework/FrameworkInfoReporterTest.java deleted file mode 100644 index de97a835..00000000 --- a/agent/src/test/java/com/tracelytics/monitor/framework/FrameworkInfoReporterTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.tracelytics.monitor.framework; - -import com.tracelytics.joboe.JoboeTest; -import com.tracelytics.joboe.TestRpcClient; -import com.tracelytics.joboe.config.ConfigManager; -import com.tracelytics.joboe.config.ConfigProperty; -import com.tracelytics.monitor.SystemReporterException; - -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - - -public class FrameworkInfoReporterTest extends JoboeTest { - - private FrameworkInfoReporter reporter; - private TestRpcClient testRpcClient = new TestRpcClient(0); - - @Override - protected void setUp() throws Exception { - super.setUp(); - reporter = new FrameworkInfoReporter(testRpcClient); - } - - @Override - protected void tearDown() throws Exception { - testRpcClient.reset(); - } - - - - public void testReportEmpty() throws SystemReporterException { - reporter.preReportData(); - reporter.reportData(new HashMap(), 0); - reporter.postReportData(); - - assertTrue(testRpcClient.getPostedStatus().isEmpty()); - } - - public void testReport() throws SystemReporterException { - Map info = new HashMap(); - - info.put("Java.a.Version", "1"); - info.put("Java.b.Version", ""); - - reporter.preReportData(); - reporter.reportData(info, 0); - reporter.postReportData(); - - Map sentStatusMessage = testRpcClient.getPostedStatus().get(0); - - assertEquals(true, sentStatusMessage.get("__Init")); - assertEquals(ConfigManager.getConfig(ConfigProperty.AGENT_LAYER), sentStatusMessage.get("Layer")); - - for (Entry infoEntry : info.entrySet()) { - assertEquals(infoEntry.getValue(), sentStatusMessage.get(infoEntry.getKey())); - } - - - } -} diff --git a/agent/src/test/java/com/tracelytics/monitor/metrics/CustomMetricsCollectorTest.java b/agent/src/test/java/com/tracelytics/monitor/metrics/CustomMetricsCollectorTest.java deleted file mode 100644 index 9f19a105..00000000 --- a/agent/src/test/java/com/tracelytics/monitor/metrics/CustomMetricsCollectorTest.java +++ /dev/null @@ -1,166 +0,0 @@ -package com.tracelytics.monitor.metrics; - -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.tracelytics.agent.Agent; -import com.tracelytics.joboe.JoboeTest; -import com.tracelytics.joboe.TracingMode; -import com.tracelytics.joboe.settings.SettingsArg; -import com.tracelytics.joboe.settings.SettingsManager; -import com.tracelytics.joboe.settings.SimpleSettingsFetcher; -import com.tracelytics.joboe.settings.TestSettingsReader.SettingsMockupBuilder; -import com.tracelytics.metrics.MetricKey; -import com.tracelytics.metrics.MetricsEntry; -import com.tracelytics.metrics.measurement.SummaryDoubleMeasurement; - -/** - * Test sub metrics collector from custom metrics - * @author pluk - * - */ -public class CustomMetricsCollectorTest extends JoboeTest { - @Override - protected void setUp() throws Exception { - super.setUp(); - CustomMetricsCollector.INSTANCE.collectMetricsEntries(); //clear everything - } - - @Override - protected void tearDown() throws Exception { - CustomMetricsCollector.INSTANCE.reset(); - super.tearDown(); - } - - public void testIncrementMetrics() throws Exception { - CustomMetricsCollector.INSTANCE.recordIncrementMetrics("test-1", 1, null); - CustomMetricsCollector.INSTANCE.recordIncrementMetrics("test-1", 2, null); - - CustomMetricsCollector.INSTANCE.recordIncrementMetrics("test-1", 1, Collections.singletonMap("key-1", "1")); - CustomMetricsCollector.INSTANCE.recordIncrementMetrics("test-1", 2, Collections.singletonMap("key-1", "1")); - CustomMetricsCollector.INSTANCE.recordIncrementMetrics("test-1", 3, Collections.singletonMap("key-1", "1")); - - CustomMetricsCollector.INSTANCE.recordIncrementMetrics("test-1", 2, Collections.singletonMap("key-1", "2")); - - Map tags = new HashMap(); - tags.put("key-1", "1"); - tags.put("key-2", "2"); - CustomMetricsCollector.INSTANCE.recordIncrementMetrics("test-1", 3, tags); - - CustomMetricsCollector.INSTANCE.recordIncrementMetrics("test-2", 1,null); - - List> collectMetricsEntries = CustomMetricsCollector.INSTANCE.collectMetricsEntries(); - assertEquals(5, collectMetricsEntries.size()); - Map entriesByMetricsKey = new HashMap(); - - for (MetricsEntry entry : collectMetricsEntries) { - entriesByMetricsKey.put(entry.getKey(), (Long) entry.getValue()); - } - - assertEquals(3, (long) entriesByMetricsKey.get(new MetricKey("test-1", null))); - assertEquals(6, (long) entriesByMetricsKey.get(new MetricKey("test-1", Collections.singletonMap("key-1", "1")))); - assertEquals(2, (long) entriesByMetricsKey.get(new MetricKey("test-1", Collections.singletonMap("key-1", "2")))); - assertEquals(3, (long) entriesByMetricsKey.get(new MetricKey("test-1", tags))); - assertEquals(1, (long) entriesByMetricsKey.get(new MetricKey("test-2", null))); - } - - public void testSummaryMetrics() throws Exception { - CustomMetricsCollector.INSTANCE.recordSummaryMetric("test-1", 1, 1, null); - CustomMetricsCollector.INSTANCE.recordSummaryMetric("test-1", 1, 2, null); - - CustomMetricsCollector.INSTANCE.recordSummaryMetric("test-1", 1, 1, Collections.singletonMap("key-1", "1")); - CustomMetricsCollector.INSTANCE.recordSummaryMetric("test-1", 1, 2, Collections.singletonMap("key-1", "1")); - CustomMetricsCollector.INSTANCE.recordSummaryMetric("test-1", 1, 3, Collections.singletonMap("key-1", "1")); - - CustomMetricsCollector.INSTANCE.recordSummaryMetric("test-1", 1, 2, Collections.singletonMap("key-1", "2")); - - Map tags = new HashMap(); - tags.put("key-1", "1"); - tags.put("key-2", "2"); - CustomMetricsCollector.INSTANCE.recordSummaryMetric("test-1", 3, 1, tags); - - CustomMetricsCollector.INSTANCE.recordSummaryMetric("test-2", 4, 1, null); - - List> collectMetricsEntries = CustomMetricsCollector.INSTANCE.collectMetricsEntries(); - assertEquals(5, collectMetricsEntries.size()); - Map entriesByMetricsKey = new HashMap(); - - for (MetricsEntry entry : collectMetricsEntries) { - entriesByMetricsKey.put(entry.getKey(), (SummaryDoubleMeasurement) entry.getValue()); - } - - assertEquals(2.0, entriesByMetricsKey.get(new MetricKey("test-1", null)).getSum()); - assertEquals(3, entriesByMetricsKey.get(new MetricKey("test-1", null)).getCount()); - assertEquals(3.0, entriesByMetricsKey.get(new MetricKey("test-1", Collections.singletonMap("key-1", "1"))).getSum()); - assertEquals(6, entriesByMetricsKey.get(new MetricKey("test-1", Collections.singletonMap("key-1", "1"))).getCount()); - assertEquals(1.0, entriesByMetricsKey.get(new MetricKey("test-1", Collections.singletonMap("key-1", "2"))).getSum()); - assertEquals(2, entriesByMetricsKey.get(new MetricKey("test-1", Collections.singletonMap("key-1", "2"))).getCount()); - assertEquals(3.0, entriesByMetricsKey.get(new MetricKey("test-1", tags)).getSum()); - assertEquals(1, entriesByMetricsKey.get(new MetricKey("test-1", tags)).getCount()); - assertEquals(4.0, entriesByMetricsKey.get(new MetricKey("test-2", null)).getSum()); - assertEquals(1, entriesByMetricsKey.get(new MetricKey("test-2", null)).getCount()); - } - - public void testMetricLimit() { - for (int i = 0 ; i < CustomMetricsCollector.limit; i ++) { - CustomMetricsCollector.INSTANCE.recordIncrementMetrics("test" + i, 1, null); - } - - CustomMetricsCollector.INSTANCE.recordIncrementMetrics("test0", 1, null); //OK as this name already exists - CustomMetricsCollector.INSTANCE.recordIncrementMetrics("test" + CustomMetricsCollector.limit, 1, null); //NOT OK as this name is new and limit has reached - - List> collectMetricsEntries = CustomMetricsCollector.INSTANCE.collectMetricsEntries(); - - assertEquals(CustomMetricsCollector.limit, collectMetricsEntries.size()); - - Map entriesByMetricsKey = new HashMap(); - - for (MetricsEntry entry : collectMetricsEntries) { - entriesByMetricsKey.put(entry.getKey(), (Long) entry.getValue()); - } - - assertEquals(2, (long) entriesByMetricsKey.get(new MetricKey("test0", null))); //once from loop and another one in the manual increment - assertTrue(!entriesByMetricsKey.containsKey(new MetricKey("test" + CustomMetricsCollector.limit, null))); //not exist as the entry should be dropped due to limit - - //simulate a limit change (lower) - SimpleSettingsFetcher fetcher = (SimpleSettingsFetcher) SettingsManager.getFetcher(); - testSettingsReader.put(new SettingsMockupBuilder().withFlags(TracingMode.ALWAYS).withSampleRate(Agent.SAMPLE_RESOLUTION).withSettingsArg(SettingsArg.MAX_CUSTOM_METRICS, 1).build()); - CustomMetricsCollector.INSTANCE.recordIncrementMetrics("test-1", 1, null); //ok - CustomMetricsCollector.INSTANCE.recordIncrementMetrics("test-2", 1, null); //not ok, limit exceeded - - //simulate a limit change (no override, reverts back to default limit) - testSettingsReader.put(new SettingsMockupBuilder().withFlags(TracingMode.ALWAYS).withSampleRate(Agent.SAMPLE_RESOLUTION).build()); - CustomMetricsCollector.INSTANCE.recordIncrementMetrics("test-3", 1, null); //ok now as limit has increased (reverted to default) - - collectMetricsEntries = CustomMetricsCollector.INSTANCE.collectMetricsEntries(); - entriesByMetricsKey = new HashMap(); - - for (MetricsEntry entry : collectMetricsEntries) { - entriesByMetricsKey.put(entry.getKey(), (Long) entry.getValue()); - } - - assertTrue(entriesByMetricsKey.containsKey(new MetricKey("test-1", null))); - assertTrue(!entriesByMetricsKey.containsKey(new MetricKey("test-2", null))); - assertTrue(entriesByMetricsKey.containsKey(new MetricKey("test-3", null))); - } - - public void testTagLimit() { - Map tags = new HashMap(); - for (int i = 0 ; i < CustomMetricsCollector.TAGS_LIMIT; i ++) { - tags.put(String.valueOf(i), String.valueOf(i)); - } - - CustomMetricsCollector.INSTANCE.recordIncrementMetrics("test", 1, tags); //OK as the tags limit is not exceeded yet - List> collectMetricsEntries = CustomMetricsCollector.INSTANCE.collectMetricsEntries(); - assertEquals(1, collectMetricsEntries.size()); - assertEquals(tags, collectMetricsEntries.get(0).getTags()); - - //now add 1 more tag - tags.put("extra", "tag"); - CustomMetricsCollector.INSTANCE.recordIncrementMetrics("test", 1, tags); //NOT OK as the tags limit exceeded - collectMetricsEntries = CustomMetricsCollector.INSTANCE.collectMetricsEntries(); - assertTrue(collectMetricsEntries.isEmpty()); - } -} diff --git a/agent/src/test/java/com/tracelytics/monitor/metrics/JMXCollectorTest.java b/agent/src/test/java/com/tracelytics/monitor/metrics/JMXCollectorTest.java deleted file mode 100644 index 258b733a..00000000 --- a/agent/src/test/java/com/tracelytics/monitor/metrics/JMXCollectorTest.java +++ /dev/null @@ -1,464 +0,0 @@ -package com.tracelytics.monitor.metrics; - -import com.tracelytics.joboe.JoboeTest; -import com.tracelytics.joboe.config.ConfigContainer; -import com.tracelytics.joboe.config.ConfigProperty; -import com.tracelytics.joboe.config.InvalidConfigException; -import com.tracelytics.metrics.MetricKey; - -import javax.management.*; -import javax.management.loading.ClassLoaderRepository; -import java.io.ObjectInputStream; -import java.lang.reflect.Field; -import java.util.*; - -public class JMXCollectorTest extends JoboeTest { - /** - * Test with valid config - * @throws InvalidConfigException - */ - public void testBuildCollector1() throws Exception { - ConfigContainer configs = new ConfigContainer(); - - configs.putByStringValue(ConfigProperty.MONITOR_JMX_SCOPES, "{\"java.lang:type=MemoryPool,*\":[\"Usage\"],\"java.lang:type=Memory\":[\"HeapMemoryUsage\",\"NonHeapMemoryUsage\"]}"); - - JMXCollector collector = new JMXCollector(configs); - - Field maxEntryCountField = JMXCollector.class.getDeclaredField("maxEntryCount"); - maxEntryCountField.setAccessible(true); - - assertEquals(JMXCollector.DEFAULT_MAX_ENTRY_COUNT, maxEntryCountField.getInt(collector)); - - Field scopesField = JMXCollector.class.getDeclaredField("scopes"); - scopesField.setAccessible(true); - - Map> scopesByObjectName = new HashMap>(); - for (JMXScope scope : (List) scopesField.get(collector)) { - scopesByObjectName.put(scope.getObjectName(), scope.getAttributes()); - } - - assertEquals(2, scopesByObjectName.size()); - - assertTrue(scopesByObjectName.containsKey("java.lang:type=MemoryPool,*")); - assertEquals(Arrays.asList("Usage"), scopesByObjectName.get("java.lang:type=MemoryPool,*")); - - assertTrue(scopesByObjectName.containsKey("java.lang:type=Memory")); - assertEquals(Arrays.asList("HeapMemoryUsage", "NonHeapMemoryUsage"), scopesByObjectName.get("java.lang:type=Memory")); - } - - /** - * Test with config that disables the JMX monitoring - * @throws InvalidConfigException - */ - public void testBuildCollectors2() throws Exception { - ConfigContainer configs = new ConfigContainer(); - - configs.putByStringValue(ConfigProperty.MONITOR_JMX_MAX_ENTRY, "200"); - configs.putByStringValue(ConfigProperty.MONITOR_JMX_SCOPES, "{\"java.lang:type=MemoryPool,*\":[\"Usage\"],\"java.lang:type=Memory\":[\"HeapMemoryUsage\",\"NonHeapMemoryUsage\"]}"); - - JMXCollector collector = new JMXCollector(configs); - - Field maxEntryCountField = JMXCollector.class.getDeclaredField("maxEntryCount"); - maxEntryCountField.setAccessible(true); - - assertEquals(200, maxEntryCountField.getInt(collector)); - } - - /** - * Test with config with invalid values - */ - public void testBuildCollectors3() throws Exception { - ConfigContainer configs = new ConfigContainer(); - - configs.putByStringValue(ConfigProperty.MONITOR_JMX_MAX_ENTRY, "-1"); - configs.putByStringValue(ConfigProperty.MONITOR_JMX_SCOPES, "{\"java.lang:type=MemoryPool,*\":[\"Usage\"],\"java.lang:type=Memory\":[\"HeapMemoryUsage\",\"NonHeapMemoryUsage\"]}"); - - try { - JMXCollector collector = new JMXCollector(configs); - fail("Expect " + InvalidConfigException.class.getName()); - } catch (InvalidConfigException e) { - //expected - } - } - - /** - * Test with config with invalid scope - */ - public void testBuildCollectors4() throws Exception { - ConfigContainer configs = new ConfigContainer(); - - configs.putByStringValue(ConfigProperty.MONITOR_JMX_SCOPES, "{"); //invalid json format - - try { - JMXCollector collector = new JMXCollector(configs); - fail("Expect " + InvalidConfigException.class.getName()); - } catch (InvalidConfigException e) { - //expected - } - } - - /** - * Tests JMXCollector with valid scopes - * @throws InvalidConfigException - */ - public void testCollectInformation1() throws InvalidConfigException { - ConfigContainer configs = new ConfigContainer(); - - //configs.putByStringValue(ConfigProperty.MONITOR_JMX_SCOPES, "java.lang:type=MemoryPool,name=PS Eden Space[Usage];java.lang:type=Memory[HeapMemoryUsage,NonHeapMemoryUsage]"); - configs.putByStringValue(ConfigProperty.MONITOR_JMX_SCOPES, "{\"java.lang:type=MemoryPool,*\":[\"Usage\"],\"java.lang:type=Memory\":[\"HeapMemoryUsage\",\"NonHeapMemoryUsage\"]}"); - - - JMXCollector collector = new JMXCollector(configs); - - try { - Map information = collectAll(collector); - -// assertTrue(information.containsKey("JMX.java.lang:type=MemoryPool,name=PS_Eden_Space.Usage.committed")); -// assertFalse(information.containsKey("JMX.java.lang:type=MemoryPool,name=PS_Survivor_Space.Usage.committed")); -// assertTrue(information.containsKey("JMX.java.lang:type=Memory.NonHeapMemoryUsage.committed")); -// assertFalse(information.containsKey("JMX.java.lang:type=OperatingSystem.ProcessCpuLoad")); - assertFalse(information.isEmpty()); //data returned could be different JVM from JVM and also newer jre 1.7 version seems to use different name of MemoryPoll (Eden Space VS PS Eden Space) - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Tests JMXCollector with no scopes - */ - public void testCollectInformation2() { - try { - JMXCollector collector = new JMXCollector(new ConfigContainer()); //test defaults - - fail("Except InvalidConfigException to be thrown. Empty scope is not allowed"); - } catch (InvalidConfigException e) { - //expected - } - } - - /** - * Tests JMXCollector with Invalid scopes - * @throws InvalidConfigException - */ - public void testCollectInformation3() throws InvalidConfigException { - ConfigContainer configs = new ConfigContainer(); - - configs.putByStringValue(ConfigProperty.MONITOR_JMX_SCOPES, "{\"XYZ;ZZZ\":\"*\"}"); - - JMXCollector collector = new JMXCollector(configs); - try { - Map information = collectAll(collector); - - assertTrue(information.isEmpty()); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Tests JMXCollector with wild card - * @throws InvalidConfigException - */ - public void testCollectInformation4() throws InvalidConfigException { - ConfigContainer configs = new ConfigContainer(); - - configs.putByStringValue(ConfigProperty.MONITOR_JMX_SCOPES, "{\"*:*\":\"*\"}"); - - JMXCollector collector = new JMXCollector(configs); - try { - Map information = collectAll(collector); - - assertFalse(information.isEmpty()); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Test with default scopes - * @throws Exception - */ - public void testCollectInformation5() throws Exception { - ConfigContainer configs = new ConfigContainer(); - - //configs.putByStringValue(ConfigProperty.MONITOR_JMX_SCOPES, "java.lang:type=MemoryPool,name=PS Eden Space[Usage];java.lang:type=Memory[HeapMemoryUsage,NonHeapMemoryUsage]"); - configs.putByStringValue(ConfigProperty.MONITOR_JMX_SCOPES, "{" + - "\"java.lang:type=MemoryPool,*\":[\"Usage\"]," + - "\"java.lang:type=Memory\":[\"HeapMemoryUsage\", \"NonHeapMemoryUsage\"]," + - "\"java.lang:type=GarbageCollector,*\":[\"CollectionTime\"]," + - "\"java.lang:type=Threading\":[\"ThreadCount\"]," + - "\"java.lang:type=OperatingSystem\":[\"ProcessCpuTime\", \"AvailableProcessors\", \"ProcessCpuLoad\"]," + - "\"java.lang:type=Runtime,*\":[\"Uptime\"]" + - "}"); - - MetricsInfo[] definedMetricsInfo = new MetricsInfo[] { - new MetricsInfo("MemoryPool", "Usage"), - new MetricsInfo("Memory", "HeapMemoryUsage", "NonHeapMemoryUsage"), - new MetricsInfo("GarbageCollector", "CollectionTime"), - new MetricsInfo("Threading", "ThreadCount"), - new MetricsInfo("OperatingSystem", "ProcessCpuTime", "AvailableProcessors", "ProcessCpuLoad"), - new MetricsInfo("Runtime", "Uptime") - }; - - - JMXCollector collector = new JMXCollector(configs); - Map collectedMetrics = collectAll(collector); - - assertCollectedMetrics(collectedMetrics, definedMetricsInfo); - } - - /** - * Test with hitting maxEntryCount - * @throws Exception - */ - public void testMaxEntryCount() throws Exception { - ConfigContainer configs = new ConfigContainer(); - - //configs.putByStringValue(ConfigProperty.MONITOR_JMX_SCOPES, "java.lang:type=MemoryPool,name=PS Eden Space[Usage];java.lang:type=Memory[HeapMemoryUsage,NonHeapMemoryUsage]"); - configs.putByStringValue(ConfigProperty.MONITOR_JMX_MAX_ENTRY, "250"); - configs.putByStringValue(ConfigProperty.MONITOR_JMX_SCOPES, "{" + - "\"test:type=A,*\":\"*\"," + - "\"test:type=B,*\":\"*\"," + - "\"test:type=C,*\":\"*\"," + - "\"test:type=D,*\":\"*\"," + - "\"test:type=E,*\":\"*\"," + - "\"test:type=F,*\":\"*\"," + - "}"); - - JMXCollector collector = new JMXCollector(configs); - Map collectedMetrics = collector.collect(new TestMBeanServer(100)); - - assertEquals(250, collectedMetrics.size()); - } - - - private Map collectAll(JMXCollector collector) throws IntrospectionException, InstanceNotFoundException, AttributeNotFoundException, ReflectionException, MBeanException { - return collector.collect(); - } - - /** - * Assert the the metrics collected matches the metricsInfo defined - * @param collectedMetrics - * @param metricsInfo - */ - private void assertCollectedMetrics(Map collectedMetrics, MetricsInfo[] definedMetricsInfo) { - for (MetricsInfo definedMetricsEntry : definedMetricsInfo) { - for (String definedAttribute : definedMetricsEntry.attributes) { - boolean found = false; - for (MetricKey key : collectedMetrics.keySet()) { - String stringKey = key.getStringKey(); - - String expectedPrefix = JMXCollector.JMX_LABEL + "."; - stringKey = stringKey.substring(expectedPrefix.length()); //trim the first part out - - if (stringKey.contains(definedAttribute)) { - found = true; - } - } - assertTrue(found); - } - } - } - - private class MetricsInfo { - private String type; - private String[] attributes; - - private MetricsInfo(String type, String...attributes) { - this.type = type; - this.attributes = attributes; - } - - } - - private class TestMBeanServer implements MBeanServer { - private int entriesPerObjectName; - public TestMBeanServer(int entriesPerObjectName) { - this.entriesPerObjectName = entriesPerObjectName; - } - - - public ObjectInstance createMBean(String className, ObjectName name) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException { - // TODO Auto-generated method stub - return null; - } - - public ObjectInstance createMBean(String className, ObjectName name, ObjectName loaderName) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException { - // TODO Auto-generated method stub - return null; - } - - public ObjectInstance createMBean(String className, ObjectName name, Object[] params, String[] signature) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException { - // TODO Auto-generated method stub - return null; - } - - public ObjectInstance createMBean(String className, ObjectName name, ObjectName loaderName, Object[] params, String[] signature) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException { - // TODO Auto-generated method stub - return null; - } - - public ObjectInstance registerMBean(Object object, ObjectName name) throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException { - // TODO Auto-generated method stub - return null; - } - - public void unregisterMBean(ObjectName name) throws InstanceNotFoundException, MBeanRegistrationException { - // TODO Auto-generated method stub - - } - - public ObjectInstance getObjectInstance(ObjectName name) throws InstanceNotFoundException { - // TODO Auto-generated method stub - return null; - } - - public Set queryMBeans(ObjectName name, QueryExp query) { - // TODO Auto-generated method stub - return null; - } - - public Set queryNames(ObjectName name, QueryExp query) { - return Collections.singleton(name); - } - - public boolean isRegistered(ObjectName name) { - // TODO Auto-generated method stub - return false; - } - - public Integer getMBeanCount() { - // TODO Auto-generated method stub - return null; - } - - public Object getAttribute(ObjectName name, String attribute) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException { - return Integer.valueOf(attribute); - } - - public AttributeList getAttributes(ObjectName name, String[] attributes) throws InstanceNotFoundException, ReflectionException { - // TODO Auto-generated method stub - return null; - } - - public void setAttribute(ObjectName name, Attribute attribute) throws InstanceNotFoundException, AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { - // TODO Auto-generated method stub - - } - - public AttributeList setAttributes(ObjectName name, AttributeList attributes) throws InstanceNotFoundException, ReflectionException { - // TODO Auto-generated method stub - return null; - } - - public Object invoke(ObjectName name, String operationName, Object[] params, String[] signature) throws InstanceNotFoundException, MBeanException, ReflectionException { - // TODO Auto-generated method stub - return null; - } - - public String getDefaultDomain() { - // TODO Auto-generated method stub - return null; - } - - public String[] getDomains() { - // TODO Auto-generated method stub - return null; - } - - public void addNotificationListener(ObjectName name, NotificationListener listener, NotificationFilter filter, Object handback) throws InstanceNotFoundException { - // TODO Auto-generated method stub - - } - - public void addNotificationListener(ObjectName name, ObjectName listener, NotificationFilter filter, Object handback) throws InstanceNotFoundException { - // TODO Auto-generated method stub - - } - - public void removeNotificationListener(ObjectName name, ObjectName listener) throws InstanceNotFoundException, ListenerNotFoundException { - // TODO Auto-generated method stub - - } - - public void removeNotificationListener(ObjectName name, ObjectName listener, NotificationFilter filter, Object handback) throws InstanceNotFoundException, ListenerNotFoundException { - // TODO Auto-generated method stub - - } - - public void removeNotificationListener(ObjectName name, NotificationListener listener) throws InstanceNotFoundException, ListenerNotFoundException { - // TODO Auto-generated method stub - - } - - public void removeNotificationListener(ObjectName name, NotificationListener listener, NotificationFilter filter, Object handback) throws InstanceNotFoundException, ListenerNotFoundException { - // TODO Auto-generated method stub - - } - - public MBeanInfo getMBeanInfo(ObjectName name) throws InstanceNotFoundException, IntrospectionException, ReflectionException { - MBeanAttributeInfo[] attributeInfo = new MBeanAttributeInfo[entriesPerObjectName]; - for (int i = 0 ; i < entriesPerObjectName ; i++) { - attributeInfo[i] = new MBeanAttributeInfo(String.valueOf(i), "int", "test-attribute-" + i, true, true, false); - } - return new MBeanInfo(name.toString(), name.toString(), attributeInfo, null, null, null); - } - - public boolean isInstanceOf(ObjectName name, String className) throws InstanceNotFoundException { - // TODO Auto-generated method stub - return false; - } - - public Object instantiate(String className) throws ReflectionException, MBeanException { - // TODO Auto-generated method stub - return null; - } - - public Object instantiate(String className, ObjectName loaderName) throws ReflectionException, MBeanException, InstanceNotFoundException { - // TODO Auto-generated method stub - return null; - } - - public Object instantiate(String className, Object[] params, String[] signature) throws ReflectionException, MBeanException { - // TODO Auto-generated method stub - return null; - } - - public Object instantiate(String className, ObjectName loaderName, Object[] params, String[] signature) throws ReflectionException, MBeanException, InstanceNotFoundException { - // TODO Auto-generated method stub - return null; - } - - public ObjectInputStream deserialize(ObjectName name, byte[] data) throws InstanceNotFoundException, OperationsException { - // TODO Auto-generated method stub - return null; - } - - public ObjectInputStream deserialize(String className, byte[] data) throws OperationsException, ReflectionException { - // TODO Auto-generated method stub - return null; - } - - public ObjectInputStream deserialize(String className, ObjectName loaderName, byte[] data) throws InstanceNotFoundException, OperationsException, ReflectionException { - // TODO Auto-generated method stub - return null; - } - - public ClassLoader getClassLoaderFor(ObjectName mbeanName) throws InstanceNotFoundException { - // TODO Auto-generated method stub - return null; - } - - public ClassLoader getClassLoader(ObjectName loaderName) throws InstanceNotFoundException { - // TODO Auto-generated method stub - return null; - } - - public ClassLoaderRepository getClassLoaderRepository() { - // TODO Auto-generated method stub - return null; - } - - } - -} diff --git a/agent/src/test/java/com/tracelytics/monitor/metrics/MetricsCollectorTest.java b/agent/src/test/java/com/tracelytics/monitor/metrics/MetricsCollectorTest.java deleted file mode 100644 index ac553b5d..00000000 --- a/agent/src/test/java/com/tracelytics/monitor/metrics/MetricsCollectorTest.java +++ /dev/null @@ -1,144 +0,0 @@ -package com.tracelytics.monitor.metrics; - -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import com.tracelytics.joboe.JoboeTest; -import com.tracelytics.joboe.config.ConfigContainer; -import com.tracelytics.joboe.config.ConfigProperty; -import com.tracelytics.metrics.MetricKey; -import com.tracelytics.metrics.MetricsEntry; -import com.tracelytics.metrics.histogram.HistogramMetricsEntry; -import com.tracelytics.metrics.histogram.MockHistogramAdapter; -import com.tracelytics.metrics.measurement.SimpleMeasurementMetricsEntry; - -/** - * Test collecting from multiple source, we do not have to test specifically each of the actual collector as tests will created for each of them correspondingly - * @author pluk - * - */ -public class MetricsCollectorTest extends JoboeTest { - public void testCollectorsInit() throws Exception { - ConfigContainer configs = new ConfigContainer(); - configs.putByStringValue(ConfigProperty.MONITOR_JMX_SCOPES, "{}"); - MetricsCollector metricsCollector = new MetricsCollector(configs); - - //modify the collector to use our testing source collectors - Field collectorsField = MetricsCollector.class.getDeclaredField("collectors"); - collectorsField.setAccessible(true); - Map collectorsMap = (Map) collectorsField.get(metricsCollector); - - for (MetricsCategory category : MetricsCategory.values()) { - collectorsMap.containsKey(category); - } - - configs.putByStringValue(ConfigProperty.MONITOR_JMX_ENABLE, "false"); - metricsCollector = new MetricsCollector(configs); - collectorsMap = (Map) collectorsField.get(metricsCollector); - assertFalse(collectorsMap.containsKey(MetricsCategory.JMX)); //should no longer has the JMX monitor - - configs.putByStringValue(ConfigProperty.MONITOR_SPAN_METRICS_ENABLE, "false"); - metricsCollector = new MetricsCollector(configs); - collectorsMap = (Map) collectorsField.get(metricsCollector); - assertFalse(collectorsMap.containsKey(MetricsCategory.SPAN_METRICS)); //should no longer has the historgram collector - } - - - - public void testCollect() throws Exception { - ConfigContainer configs = new ConfigContainer(); - configs.putByStringValue(ConfigProperty.MONITOR_JMX_SCOPES, "{}"); - MetricsCollector metricsCollector = new MetricsCollector(configs); - - //modify the collector to use our testing source collectors - Field collectorsField = MetricsCollector.class.getDeclaredField("collectors"); - collectorsField.setAccessible(true); - Map collectorsMap = (Map) collectorsField.get(metricsCollector); - - collectorsMap.clear(); - - //test collector that returns a mix of measurement and histogram - final List> testLayerCountMetrics = new ArrayList>(); - testLayerCountMetrics.add(new SimpleMeasurementMetricsEntry("a", null, 1)); - testLayerCountMetrics.add(new SimpleMeasurementMetricsEntry("b", Collections.singletonMap("Layer", "b"), 100.123)); - testLayerCountMetrics.add(new HistogramMetricsEntry(new MetricKey("c", null), new MockHistogramAdapter(1.0, 2, 3, 4, 5, 6.0, 7, 8))); - - //test collector that only returns histograms - final List testLayerHistogramMetrics = new ArrayList(); - testLayerHistogramMetrics.add(new HistogramMetricsEntry(new MetricKey("a", Collections.singletonMap("Layer", "a")), new MockHistogramAdapter(10.0, 20, 30, 40, 50, 60.0, 70, 80))); - testLayerHistogramMetrics.add(new HistogramMetricsEntry(new MetricKey("b", null), new MockHistogramAdapter(100.0, 200, 300, 400, 500, 600.0, 700, 800))); - - collectorsMap.put(MetricsCategory.LAYER_COUNT, new AbstractMetricsEntryCollector() { - @Override - List> collectMetricsEntries() throws Exception { - return testLayerCountMetrics; - } - }); - - collectorsMap.put(MetricsCategory.SPAN_METRICS, new AbstractMetricsEntryCollector() { - @Override - List collectMetricsEntries() throws Exception { - return testLayerHistogramMetrics; - } - }); - - Map>> collectedEntries = metricsCollector.collect(); - - assertEquals(testLayerCountMetrics, collectedEntries.get(MetricsCategory.LAYER_COUNT)); - assertEquals(testLayerHistogramMetrics, collectedEntries.get(MetricsCategory.SPAN_METRICS)); - } - - /** - * Test if one source of collection takes too long to complete - * @throws Exception - */ - public void testCollectTimeout() throws Exception { - ConfigContainer configs = new ConfigContainer(); - configs.putByStringValue(ConfigProperty.MONITOR_JMX_SCOPES, "{}"); - MetricsCollector metricsCollector = new MetricsCollector(configs); - - //modify the collector to use our testing source collectors - Field collectorsField = MetricsCollector.class.getDeclaredField("collectors"); - collectorsField.setAccessible(true); - Map collectorsMap = (Map) collectorsField.get(metricsCollector); - - collectorsMap.clear(); - - //test collector that returns a mix of measurement and histogram - final List> testLayerCountMetrics = new ArrayList>(); - testLayerCountMetrics.add(new SimpleMeasurementMetricsEntry("a", null, 1)); - testLayerCountMetrics.add(new SimpleMeasurementMetricsEntry("b", Collections.singletonMap("Layer", "b"), 100.123)); - testLayerCountMetrics.add(new HistogramMetricsEntry(new MetricKey("c", null), new MockHistogramAdapter(1.0, 2, 3, 4, 5, 6.0, 7, 8))); - - //test collector that only returns histograms - final List testLayerHistogramMetrics = new ArrayList(); - testLayerHistogramMetrics.add(new HistogramMetricsEntry(new MetricKey("a", Collections.singletonMap("Layer", "a")), new MockHistogramAdapter(10.0, 20, 30, 40, 50, 60.0, 70, 80))); - testLayerHistogramMetrics.add(new HistogramMetricsEntry(new MetricKey("b", null), new MockHistogramAdapter(100.0, 200, 300, 400, 500, 600.0, 700, 800))); - - collectorsMap.put(MetricsCategory.LAYER_COUNT, new AbstractMetricsEntryCollector() { - @Override - List> collectMetricsEntries() throws Exception { - //make this really slow - Thread.sleep(30000); //30 secs - return testLayerCountMetrics; - } - }); - - collectorsMap.put(MetricsCategory.SPAN_METRICS, new AbstractMetricsEntryCollector() { - @Override - List collectMetricsEntries() throws Exception { - return testLayerHistogramMetrics; - } - }); - - Map>> collectedEntries = metricsCollector.collect(); - - assertFalse(collectedEntries.containsKey(MetricsCategory.LAYER_COUNT)); - assertEquals(testLayerHistogramMetrics, collectedEntries.get(MetricsCategory.SPAN_METRICS)); //should still have histograms - } - - -} diff --git a/agent/src/test/java/com/tracelytics/monitor/metrics/MetricsMonitorTest.java b/agent/src/test/java/com/tracelytics/monitor/metrics/MetricsMonitorTest.java deleted file mode 100644 index ec676e74..00000000 --- a/agent/src/test/java/com/tracelytics/monitor/metrics/MetricsMonitorTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.tracelytics.monitor.metrics; - -import java.util.Collections; - -import com.tracelytics.agent.Agent; -import com.tracelytics.joboe.JoboeTest; -import com.tracelytics.joboe.TracingMode; -import com.tracelytics.joboe.config.ConfigContainer; -import com.tracelytics.joboe.config.ConfigProperty; -import com.tracelytics.joboe.config.InvalidConfigException; -import com.tracelytics.joboe.rpc.ClientException; -import com.tracelytics.joboe.settings.SettingsArg; -import com.tracelytics.joboe.settings.SettingsManager; -import com.tracelytics.joboe.settings.SimpleSettingsFetcher; -import com.tracelytics.joboe.settings.TestSettingsReader.SettingsMockup; -import com.tracelytics.joboe.settings.TestSettingsReader.SettingsMockupBuilder; - -public class MetricsMonitorTest extends JoboeTest { - private ConfigContainer config = new ConfigContainer(); - { - try { - config.putByStringValue(ConfigProperty.MONITOR_JMX_SCOPES, "{}"); - } catch (InvalidConfigException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - - public void testSingleton() throws Exception { - MetricsMonitor monitor1 = MetricsMonitor.buildInstance(config); - MetricsMonitor monitor2 = MetricsMonitor.buildInstance(config); - - //should be same instance - assertTrue(monitor1 == monitor2); - } - - public void testUpdateInterval() throws InvalidConfigException, ClientException { - long defaultInterval = MetricsMonitor.DEFAULT_TIME_UNIT.getInterval(MetricsMonitor.DEFAULT_FREQUENCY); - MetricsMonitor monitor = MetricsMonitor.buildInstance(config); - assertEquals(defaultInterval, monitor.getInterval()); //no updates - - //simulate an update on metrics flush interval - SimpleSettingsFetcher fetcher = (SimpleSettingsFetcher) SettingsManager.getFetcher(); - //every 10 secs, valid - testSettingsReader.put(new SettingsMockupBuilder().withFlags(TracingMode.ALWAYS).withSampleRate(Agent.SAMPLE_RESOLUTION).withSettingsArg(SettingsArg.METRIC_FLUSH_INTERVAL, 10).build()); - assertEquals(10 * 1000, monitor.getInterval()); //should update to new metrics flush interval in millisec - - //every 40 secs, invalid, not divisible to 60 secs nor a divisor to 60 secs - testSettingsReader.put(new SettingsMockupBuilder().withFlags(TracingMode.ALWAYS).withSampleRate(Agent.SAMPLE_RESOLUTION).withSettingsArg(SettingsArg.METRIC_FLUSH_INTERVAL, 40).build()); - assertEquals(10 * 1000, monitor.getInterval()); //should ignore this value, so still show last value : 10 sec - - //every 2 mins, valid - testSettingsReader.put(new SettingsMockupBuilder().withFlags(TracingMode.ALWAYS).withSampleRate(Agent.SAMPLE_RESOLUTION).withSettingsArg(SettingsArg.METRIC_FLUSH_INTERVAL, 120).build()); - assertEquals(120 * 1000, monitor.getInterval()); //should update to new metrics flush interval in millisec - - - //if the arg is not found, revert back to default - testSettingsReader.put(new SettingsMockupBuilder().withFlags(TracingMode.ALWAYS).withSampleRate(Agent.SAMPLE_RESOLUTION).build()); - assertEquals(defaultInterval, monitor.getInterval()); //should set back to default - } -} diff --git a/agent/src/test/java/com/tracelytics/monitor/metrics/MetricsReportTest.java b/agent/src/test/java/com/tracelytics/monitor/metrics/MetricsReportTest.java deleted file mode 100644 index e50e4adf..00000000 --- a/agent/src/test/java/com/tracelytics/monitor/metrics/MetricsReportTest.java +++ /dev/null @@ -1,304 +0,0 @@ -package com.tracelytics.monitor.metrics; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import com.tracelytics.joboe.JoboeTest; -import com.tracelytics.joboe.TestRpcClient; -import com.tracelytics.joboe.TestSubmitRejectionRpcClient; -import com.tracelytics.joboe.rpc.Client; -import com.tracelytics.metrics.MetricKey; -import com.tracelytics.metrics.MetricsEntry; -import com.tracelytics.metrics.TopLevelMetricsEntry; -import com.tracelytics.metrics.histogram.HistogramMetricsEntry; -import com.tracelytics.metrics.histogram.MockHistogramAdapter; -import com.tracelytics.metrics.measurement.MeasurementMetricsEntry; -import com.tracelytics.metrics.measurement.SimpleMeasurementMetricsEntry; -import com.tracelytics.metrics.measurement.SummaryDoubleMeasurement; -import com.tracelytics.metrics.measurement.SummaryMeasurement; -import com.tracelytics.metrics.measurement.SummaryMeasurementMetricsEntry; -import com.tracelytics.util.HostInfoUtils; -import com.tracelytics.util.HostInfoUtils.NetworkAddressInfo; - -public class MetricsReportTest extends JoboeTest { - private static final int INTERVAL = 30000; //30 sec - - public void testReport() throws Exception { - TestRpcClient client = new TestRpcClient(0); - MetricsReporter reporter = new MetricsReporter(client); - - Map>> collectedEntries = new HashMap>>(); - - List> measurementEntries = new ArrayList>(); - List histogramEntries = new ArrayList(); - - - final List> testSpanMetrics = new ArrayList>(); - HistogramMetricsEntry histogramEntry; - - histogramEntry = new HistogramMetricsEntry("a", Collections.singletonMap("layer", "a"), new MockHistogramAdapter(10.0, 20, 30, 40, 50, 60.0, 70, 80)); - testSpanMetrics.add(histogramEntry); - histogramEntries.add(histogramEntry); - - histogramEntry = new HistogramMetricsEntry("b", null, new MockHistogramAdapter(100.0, 200, 300, 400, 500, 600.0, 700, 800)); - testSpanMetrics.add(histogramEntry); - histogramEntries.add(histogramEntry); - - testSpanMetrics.add(new TopLevelMetricsEntry(SpanMetricsCollector.TRANSACTION_NAME_OVERFLOW_LABEL, true)); - - - final List> testLayerCountMetrics = new ArrayList>(); - - SimpleMeasurementMetricsEntry measurementEntry; - - measurementEntry = new SimpleMeasurementMetricsEntry("a", null, 1); - testLayerCountMetrics.add(measurementEntry); - measurementEntries.add(measurementEntry); - - measurementEntry = new SimpleMeasurementMetricsEntry("b", Collections.singletonMap("layer", "b"), 100.123); - testLayerCountMetrics.add(measurementEntry); - measurementEntries.add(measurementEntry); - - histogramEntry = new HistogramMetricsEntry("c", null, new MockHistogramAdapter(1.0, 2, 3, 4, 5, 6.0, 7, 8)); - testLayerCountMetrics.add(histogramEntry); - histogramEntries.add(histogramEntry); - - //Custom metric entries - final List> testCustomMetrics = new ArrayList>(); - SummaryMeasurement customMeasurement = new SummaryDoubleMeasurement(); - customMeasurement.recordValue(5.5); - SummaryMeasurementMetricsEntry summaryMeasurementMetricsEntry = new SummaryMeasurementMetricsEntry(new MetricKey("custom-1", Collections.singletonMap("tag-1", "A")), customMeasurement); - testCustomMetrics.add(summaryMeasurementMetricsEntry); - - //test collector that only returns histograms - - collectedEntries.put(MetricsCategory.SPAN_METRICS, testSpanMetrics); - collectedEntries.put(MetricsCategory.LAYER_COUNT, testLayerCountMetrics); - collectedEntries.put(MetricsCategory.CUSTOM, testCustomMetrics); - - reporter.reportData(collectedEntries, INTERVAL); - - Thread.sleep(1000); //give it some time to finish as it's asynchronous - - List> postedMessages = client.getPostedMetrics(); - - assertEquals(2, postedMessages.size()); //one for built-in metrics, and one for custom metrics - - Map postedBuiltinMetrics = postedMessages.get(0); - - assertBasicKeys(postedBuiltinMetrics); - - assertEquals(true, postedBuiltinMetrics.get(SpanMetricsCollector.TRANSACTION_NAME_OVERFLOW_LABEL)); - assertMetricEntries(measurementEntries, (List>) postedBuiltinMetrics.get("measurements")); - assertMetricEntries(histogramEntries, (List>) postedBuiltinMetrics.get("histograms")); - - Map postedCustomMetrics = postedMessages.get(1); - - assertBasicKeys(postedCustomMetrics); - - assertEquals(null, postedCustomMetrics.get(SpanMetricsCollector.TRANSACTION_NAME_OVERFLOW_LABEL)); - assertMetricEntries(testCustomMetrics, (List>) postedCustomMetrics.get("measurements")); - assertEquals(null, (List>) postedCustomMetrics.get("histograms")); - } - - /** - * when there are too many metric entry (exceeding MAX_MEASUREMENT_ENTRY_COUNT), it will then drop some entries. It will drop according to the natural ordering as defined in - * MetricsCategory (the last category will get dropped first etc), which in this case the jmx entries will be dropped first - * - * - * @throws Exception - */ - public void testReportTooManyJmx() throws Exception { - TestRpcClient client = new TestRpcClient(0); - MetricsReporter reporter = new MetricsReporter(client); - - Map>> collectedEntries = new HashMap>>(); - - - - List testJmxEntries = new ArrayList(); - for (int i = 0 ; i < MetricsReporter.MAX_MEASUREMENT_ENTRY_COUNT; i ++) { - testJmxEntries.add(new SimpleMeasurementMetricsEntry("jmx." + i, null, i)); - } - - List testLayerEntries = new ArrayList(); - final int layerMetricCount = 50; - for (int i = 0 ; i < 50; i ++) { - testLayerEntries.add(new SimpleMeasurementMetricsEntry("layer." + i, null, i)); - } - - //test collector that only returns histograms - collectedEntries.put(MetricsCategory.JMX, testJmxEntries); - collectedEntries.put(MetricsCategory.LAYER_COUNT, testLayerEntries); - - reporter.reportData(collectedEntries, INTERVAL); - - Thread.sleep(1000); //give it some time to finish as it's asynchronous - - List> postedMessages = client.getPostedMetrics(); - - assertEquals(1, postedMessages.size()); - - Map postedMetrics = postedMessages.get(0); - - assertBasicKeys(postedMetrics); //basic keys should always be there - - List> postedMeasurements = (List>) postedMetrics.get("measurements"); - - assertMetricEntries(testLayerEntries, postedMeasurements.subList(0, layerMetricCount)); //the layer entries should all make it as it has higher priority than JMX - int expectedPostedJmxEntriesCount = MetricsReporter.MAX_MEASUREMENT_ENTRY_COUNT - layerMetricCount; //only a sublist of jmx entries can make it, the remaining counts left after the layer entries - assertMetricEntries(testJmxEntries.subList(0, expectedPostedJmxEntriesCount), postedMeasurements.subList(layerMetricCount, postedMeasurements.size())); //only a sublist of jmx entries can make it - - } - - public void testLongTags() throws Exception { - final String longName = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789" + - "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789" + - "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"; //300 characters - final String longValue = "9876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210" + - "9876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210" + - "9876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210"; //300 characters - TestRpcClient client = new TestRpcClient(0); - MetricsReporter reporter = new MetricsReporter(client); - - Map>> collectedEntries = new HashMap>>(); - - List measurementEntries = new ArrayList(); - List histogramEntries = new ArrayList(); - - - final List testLayerHistogramMetrics = new ArrayList(); - HistogramMetricsEntry histogramEntry; - - histogramEntry = new HistogramMetricsEntry("a", Collections.singletonMap(longName, longValue), new MockHistogramAdapter(10.0, 20, 30, 40, 50, 60.0, 70, 80)); - testLayerHistogramMetrics.add(histogramEntry); - histogramEntries.add(histogramEntry); - - final List> testLayerCountMetrics = new ArrayList>(); - SimpleMeasurementMetricsEntry measurementEntry; - - measurementEntry = new SimpleMeasurementMetricsEntry(longName, Collections.singletonMap(longName, longValue), 100.123); - testLayerCountMetrics.add(measurementEntry); - measurementEntries.add(measurementEntry); - - collectedEntries.put(MetricsCategory.SPAN_METRICS, testLayerHistogramMetrics); - collectedEntries.put(MetricsCategory.LAYER_COUNT, testLayerCountMetrics); - - reporter.reportData(collectedEntries, INTERVAL); - - Thread.sleep(1000); //give it some time to finish as it's asynchronous - - List> postedMessages = client.getPostedMetrics(); - - assertEquals(1, postedMessages.size()); - - Map postedMetrics = postedMessages.get(0); - - assertBasicKeys(postedMetrics); - - assertMetricEntries(measurementEntries, (List>) postedMetrics.get("measurements")); - assertMetricEntries(histogramEntries, (List>) postedMetrics.get("histograms")); - } - - - public void testReportException() throws Exception { - Client client = new TestSubmitRejectionRpcClient(); - MetricsReporter reporter = new MetricsReporter(client); - - Map>> collectedEntries = new HashMap>>(); - - List measurementEntries = new ArrayList(); - List histogramEntries = new ArrayList(); - - final List testLayerHistogramMetrics = new ArrayList(); - HistogramMetricsEntry histogramEntry; - - histogramEntry = new HistogramMetricsEntry("a", Collections.singletonMap("layer", "a"), new MockHistogramAdapter(10.0, 20, 30, 40, 50, 60.0, 70, 80)); - testLayerHistogramMetrics.add(histogramEntry); - histogramEntries.add(histogramEntry); - - histogramEntry = new HistogramMetricsEntry("b", null, new MockHistogramAdapter(100.0, 200, 300, 400, 500, 600.0, 700, 800)); - testLayerHistogramMetrics.add(histogramEntry); - histogramEntries.add(histogramEntry); - - final List> testLayerCountMetrics = new ArrayList>(); - SimpleMeasurementMetricsEntry measurementEntry; - - measurementEntry = new SimpleMeasurementMetricsEntry("a", null, 1); - testLayerCountMetrics.add(measurementEntry); - measurementEntries.add(measurementEntry); - - measurementEntry = new SimpleMeasurementMetricsEntry("b", Collections.singletonMap("layer", "b"), 100.123); - testLayerCountMetrics.add(measurementEntry); - measurementEntries.add(measurementEntry); - - measurementEntry = new SimpleMeasurementMetricsEntry("b", Collections.singletonMap("layer", "b"), 100.123); - testLayerCountMetrics.add(measurementEntry); - measurementEntries.add(measurementEntry); - - histogramEntry = new HistogramMetricsEntry("c", null, new MockHistogramAdapter(1.0, 2, 3, 4, 5, 6.0, 7, 8)); - testLayerCountMetrics.add(histogramEntry); - histogramEntries.add(histogramEntry); - - - //client rejection is considered a minor problem and should not throw SystemReporterException - reporter.reportData(collectedEntries, INTERVAL); - } - - private void assertMetricEntries(List> expectedEntries, List> list) { - assertEquals(expectedEntries.size(), list.size()); - for (int i = 0 ; i < expectedEntries.size(); i ++) { - MetricsEntry expectedMeasurement = expectedEntries.get(i); - Map postedMeasurement = list.get(i); - - String expectedName = expectedMeasurement.getName(); - if (expectedName.length() > MetricsReporter.MAX_METRIC_NAME_LENGTH) { - expectedName = expectedName.substring(0, MetricsReporter.MAX_METRIC_NAME_LENGTH); - } - assertEquals(expectedName, postedMeasurement.get("name")); - for (Entry expectedKv : expectedMeasurement.getSerializedKvs().entrySet()) { - assertEquals(expectedKv.getValue(), postedMeasurement.get(expectedKv.getKey())); - } - - //check tags - Map postedTags = (Map) postedMeasurement.get("tags"); - if (expectedMeasurement.getTags() == null) { - assertNull(postedTags); - } else { - assertEquals(expectedMeasurement.getTags().size(), postedTags.size()); - for (String expectedTagKey : expectedMeasurement.getTags().keySet()) { - Object expectedTagValue = expectedMeasurement.getTags().get(expectedTagKey); - if (expectedTagKey.length() > MetricsReporter.MAX_TAG_NAME_LENGTH) { - expectedTagKey = expectedTagKey.substring(0, MetricsReporter.MAX_TAG_NAME_LENGTH); - } - - if (expectedTagValue instanceof String) { - if (((String) expectedTagValue).length() > MetricsReporter.MAX_TAG_VALUE_LENGTH) { - expectedTagValue = ((String) expectedTagValue).substring(0, MetricsReporter.MAX_TAG_VALUE_LENGTH); - } - } - assertEquals(expectedTagValue, postedTags.get(expectedTagKey)); - } - } - } - } - - private void assertBasicKeys(Map postedMetrics) { - assertTrue(postedMetrics.containsKey("Timestamp_u")); - assertTrue(postedMetrics.containsKey("UnameSysName")); - assertTrue(postedMetrics.containsKey("UnameVersion")); - assertTrue(postedMetrics.containsKey("Distro")); - NetworkAddressInfo networkInfo = HostInfoUtils.getNetworkAddressInfo(); - if (networkInfo != null) { - if (!networkInfo.getIpAddresses().isEmpty()) { - assertEquals(networkInfo.getIpAddresses(), postedMetrics.get("IPAddresses")); - } - } - - assertEquals(INTERVAL / 1000, postedMetrics.get("MetricsFlushInterval")); //from millisec to sec - } -} diff --git a/agent/src/test/java/com/tracelytics/monitor/metrics/SpanMetricsCollectorTest.java b/agent/src/test/java/com/tracelytics/monitor/metrics/SpanMetricsCollectorTest.java deleted file mode 100644 index 520fb456..00000000 --- a/agent/src/test/java/com/tracelytics/monitor/metrics/SpanMetricsCollectorTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.tracelytics.monitor.metrics; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import com.tracelytics.joboe.JoboeTest; -import com.tracelytics.joboe.span.impl.MetricSpanReporter; -import com.tracelytics.joboe.span.impl.Span; -import com.tracelytics.joboe.span.impl.TransactionNameManager; -import com.tracelytics.metrics.MetricsEntry; -import com.tracelytics.metrics.TopLevelMetricsEntry; -import com.tracelytics.metrics.measurement.SimpleMeasurementMetricsEntry; - -/** - * Test collecting metrics from Span reporter/actor and the "TransactionNameOverflow" flag - * @author pluk - * - */ -public class SpanMetricsCollectorTest extends JoboeTest { - @Override - protected void setUp() throws Exception { - super.setUp(); - TransactionNameManager.clearTransactionNames(); - } - - public void testCollect() throws Exception { - final List> testMetricEntries = new ArrayList>(); - testMetricEntries.add(new SimpleMeasurementMetricsEntry("test-key", 1)); - - MetricSpanReporter testSpanReporter =new MetricSpanReporter() { - @Override - protected void reportMetrics(Span span, long duration) { - } - - @Override - public List> consumeMetricEntries() { - return testMetricEntries; - } - }; - - SpanMetricsCollector collector = new SpanMetricsCollector(); - assertEquals(testMetricEntries, collector.collectMetricsEntries(Collections.singleton(testSpanReporter))); - - //now test the extra transaction name limit kv - for (int i = 0 ; i < TransactionNameManager.DEFAULT_MAX_NAME_COUNT + 1; i++) { - TransactionNameManager.addTransactionName(String.valueOf(i)); //trigger overflow - } - - List> collectedMetricsEntries = collector.collectMetricsEntries(Collections.singleton(testSpanReporter)); - assertEquals(testMetricEntries.size() + 1, collectedMetricsEntries.size()); //+1 as it should have the extra overflow KV - assertTrue(collectedMetricsEntries.contains(new TopLevelMetricsEntry(SpanMetricsCollector.TRANSACTION_NAME_OVERFLOW_LABEL, true))); - - //collect again, that overflow flag should be reset - assertEquals(testMetricEntries, collector.collectMetricsEntries(Collections.singleton(testSpanReporter))); - } -} diff --git a/agent/src/test/java/com/tracelytics/monitor/metrics/SystemMetricsCollectorTest.java b/agent/src/test/java/com/tracelytics/monitor/metrics/SystemMetricsCollectorTest.java deleted file mode 100644 index 872aeb5c..00000000 --- a/agent/src/test/java/com/tracelytics/monitor/metrics/SystemMetricsCollectorTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.tracelytics.monitor.metrics; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.tracelytics.joboe.JoboeTest; -import com.tracelytics.metrics.measurement.SimpleMeasurementMetricsEntry; - -public class SystemMetricsCollectorTest extends JoboeTest { - public void testCollect() throws Exception { - SystemMetricsCollector collector = new SystemMetricsCollector(); - - List entries = collector.collectMetricsEntries(); - Map entriesByName = new HashMap(); - - for (SimpleMeasurementMetricsEntry entry : entries) { - entriesByName.put(entry.getName(), entry); - } - - assertTrue(entriesByName.containsKey("TotalRAM")); - assertTrue(entriesByName.containsKey("FreeRAM")); - assertTrue(entriesByName.containsKey("Load1")); - assertTrue(entriesByName.containsKey("ProcessLoad")); - assertTrue(entriesByName.containsKey("ProcessRAM")); - } -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ConnectionClosedException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/ConnectionClosedException.java deleted file mode 100644 index 01cf09d2..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ConnectionClosedException.java +++ /dev/null @@ -1,50 +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 com.tracelytics.ext.apache.http; - -import java.io.IOException; - -/** - * Signals that the connection has been closed unexpectedly. - * - * @since 4.0 - */ -public class ConnectionClosedException extends IOException { - - private static final long serialVersionUID = 617550366255636674L; - - /** - * Creates a new ConnectionClosedException with the specified detail message. - * - * @param message The exception detail message - */ - public ConnectionClosedException(final String message) { - super(message); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ConnectionReuseStrategy.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/ConnectionReuseStrategy.java deleted file mode 100644 index d5bc3921..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ConnectionReuseStrategy.java +++ /dev/null @@ -1,72 +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 com.tracelytics.ext.apache.http; - -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -/** - * Interface for deciding whether a connection can be re-used for - * subsequent requests and should be kept alive. - *

- * Implementations of this interface must be thread-safe. Access to shared - * data must be synchronized as methods of this interface may be executed - * from multiple threads. - * - * @since 4.0 - */ -public interface ConnectionReuseStrategy { - - /** - * Decides whether a connection can be kept open after a request. - * If this method returns {@code false}, the caller MUST - * close the connection to correctly comply with the HTTP protocol. - * If it returns {@code true}, the caller SHOULD attempt to - * keep the connection open for reuse with another request. - *

- * One can use the HTTP context to retrieve additional objects that - * may be relevant for the keep-alive strategy: the actual HTTP - * connection, the original HTTP request, target host if known, - * number of times the connection has been reused already and so on. - *

- *

- * If the connection is already closed, {@code false} is returned. - * The stale connection check MUST NOT be triggered by a - * connection reuse strategy. - *

- * - * @param response - * The last response received over that connection. - * @param context the context in which the connection is being - * used. - * - * @return {@code true} if the connection is allowed to be reused, or - * {@code false} if it MUST NOT be reused - */ - boolean keepAlive(HttpResponse response, HttpContext context); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/Consts.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/Consts.java deleted file mode 100644 index 7d8e3381..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/Consts.java +++ /dev/null @@ -1,51 +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 com.tracelytics.ext.apache.http; - -import java.nio.charset.Charset; - -/** - * Commons constants. - * - * @since 4.2 - */ -public final class Consts { - - public static final int CR = 13; // - public static final int LF = 10; // - public static final int SP = 32; // - public static final int HT = 9; // - - public static final Charset UTF_8 = Charset.forName("UTF-8"); - public static final Charset ASCII = Charset.forName("US-ASCII"); - public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1"); - - private Consts() { - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ContentTooLongException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/ContentTooLongException.java deleted file mode 100644 index e421bc4e..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ContentTooLongException.java +++ /dev/null @@ -1,50 +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 com.tracelytics.ext.apache.http; - -import java.io.IOException; - -/** - * Signals that HTTP entity content is too long. - * - * @since 4.2 - */ -public class ContentTooLongException extends IOException { - - private static final long serialVersionUID = -924287689552495383L; - - /** - * Creates a new ContentTooLongException with the specified detail message. - * - * @param message exception message - */ - public ContentTooLongException(final String message) { - super(message); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ExceptionLogger.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/ExceptionLogger.java deleted file mode 100644 index 54787390..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ExceptionLogger.java +++ /dev/null @@ -1,53 +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 com.tracelytics.ext.apache.http; - -/** - * @since 4.4 - */ -public interface ExceptionLogger { - - public static final ExceptionLogger NO_OP = new ExceptionLogger() { - - @Override - public void log(final Exception ex) { - } - - }; - - public static final ExceptionLogger STD_ERR = new ExceptionLogger() { - - @Override - public void log(final Exception ex) { - ex.printStackTrace(); - } - - }; - - void log(Exception ex); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/FormattedHeader.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/FormattedHeader.java deleted file mode 100644 index 79cbf340..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/FormattedHeader.java +++ /dev/null @@ -1,60 +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 com.tracelytics.ext.apache.http; - -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -/** - * An HTTP header which is already formatted. - * For example when headers are received, the original formatting - * can be preserved. This allows for the header to be sent without - * another formatting step. - * - * @since 4.0 - */ -public interface FormattedHeader extends Header { - - /** - * Obtains the buffer with the formatted header. - * The returned buffer MUST NOT be modified. - * - * @return the formatted header, in a buffer that must not be modified - */ - CharArrayBuffer getBuffer(); - - /** - * Obtains the start of the header value in the {@link #getBuffer buffer}. - * By accessing the value in the buffer, creation of a temporary string - * can be avoided. - * - * @return index of the first character of the header value - * in the buffer returned by {@link #getBuffer getBuffer}. - */ - int getValuePos(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/Header.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/Header.java deleted file mode 100644 index 1b995785..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/Header.java +++ /dev/null @@ -1,74 +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 com.tracelytics.ext.apache.http; - -/** - * Represents an HTTP header field. - * - *

The HTTP header fields follow the same generic format as - * that given in Section 3.1 of RFC 822. Each header field consists - * of a name followed by a colon (":") and the field value. Field names - * are case-insensitive. The field value MAY be preceded by any amount - * of LWS, though a single SP is preferred. - * - *

- *     message-header = field-name ":" [ field-value ]
- *     field-name     = token
- *     field-value    = *( field-content | LWS )
- *     field-content  = <the OCTETs making up the field-value
- *                      and consisting of either *TEXT or combinations
- *                      of token, separators, and quoted-string>
- *
- * - * @since 4.0 - */ -public interface Header { - - /** - * Get the name of the Header. - * - * @return the name of the Header, never {@code null} - */ - String getName(); - - /** - * Get the value of the Header. - * - * @return the value of the Header, may be {@code null} - */ - String getValue(); - - /** - * Parses the value. - * - * @return an array of {@link HeaderElement} entries, may be empty, but is never {@code null} - * @throws ParseException in case of a parsing error - */ - HeaderElement[] getElements() throws ParseException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HeaderElement.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/HeaderElement.java deleted file mode 100644 index 6ee39f2e..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HeaderElement.java +++ /dev/null @@ -1,108 +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 com.tracelytics.ext.apache.http; - -/** - * One element of an HTTP {@link Header header} value consisting of - * a name / value pair and a number of optional name / value parameters. - *

- * Some HTTP headers (such as the set-cookie header) have values that - * can be decomposed into multiple elements. Such headers must be in the - * following form: - *

- *
- * header  = [ element ] *( "," [ element ] )
- * element = name [ "=" [ value ] ] *( ";" [ param ] )
- * param   = name [ "=" [ value ] ]
- *
- * name    = token
- * value   = ( token | quoted-string )
- *
- * token         = 1*<any char except "=", ",", ";", <"> and
- *                       white space>
- * quoted-string = <"> *( text | quoted-char ) <">
- * text          = any char except <">
- * quoted-char   = "\" char
- * 
- *

- * Any amount of white space is allowed between any part of the - * header, element or param and is ignored. A missing value in any - * element or param will be stored as the empty {@link String}; - * if the "=" is also missing null will be stored instead. - * - * @since 4.0 - */ -public interface HeaderElement { - - /** - * Returns header element name. - * - * @return header element name - */ - String getName(); - - /** - * Returns header element value. - * - * @return header element value - */ - String getValue(); - - /** - * Returns an array of name / value pairs. - * - * @return array of name / value pairs - */ - NameValuePair[] getParameters(); - - /** - * Returns the first parameter with the given name. - * - * @param name parameter name - * - * @return name / value pair - */ - NameValuePair getParameterByName(String name); - - /** - * Returns the total count of parameters. - * - * @return parameter count - */ - int getParameterCount(); - - /** - * Returns parameter with the given index. - * - * @param index index - * @return name / value pair - */ - NameValuePair getParameter(int index); - -} - diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HeaderElementIterator.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/HeaderElementIterator.java deleted file mode 100644 index bebe03dd..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HeaderElementIterator.java +++ /dev/null @@ -1,58 +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 com.tracelytics.ext.apache.http; - -import java.util.Iterator; - -/** - * A type-safe iterator for {@link HeaderElement} objects. - * - * @since 4.0 - */ -public interface HeaderElementIterator extends Iterator { - - /** - * Indicates whether there is another header element in this - * iteration. - * - * @return {@code true} if there is another header element, - * {@code false} otherwise - */ - @Override - boolean hasNext(); - - /** - * Obtains the next header element from this iteration. - * This method should only be called while {@link #hasNext hasNext} - * is true. - * - * @return the next header element in this iteration - */ - HeaderElement nextElement(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HeaderIterator.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/HeaderIterator.java deleted file mode 100644 index 58dbb471..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HeaderIterator.java +++ /dev/null @@ -1,57 +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 com.tracelytics.ext.apache.http; - -import java.util.Iterator; - -/** - * A type-safe iterator for {@link Header} objects. - * - * @since 4.0 - */ -public interface HeaderIterator extends Iterator { - - /** - * Indicates whether there is another header in this iteration. - * - * @return {@code true} if there is another header, - * {@code false} otherwise - */ - @Override - boolean hasNext(); - - /** - * Obtains the next header from this iteration. - * This method should only be called while {@link #hasNext hasNext} - * is true. - * - * @return the next header in this iteration - */ - Header nextHeader(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpClientConnection.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpClientConnection.java deleted file mode 100644 index ec19813b..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpClientConnection.java +++ /dev/null @@ -1,102 +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 com.tracelytics.ext.apache.http; - -import java.io.IOException; - -/** - * A client-side HTTP connection, which can be used for sending - * requests and receiving responses. - * - * @since 4.0 - */ -public interface HttpClientConnection extends HttpConnection { - - /** - * Checks if response data is available from the connection. May wait for - * the specified time until some data becomes available. Note that some - * implementations may completely ignore the timeout parameter. - * - * @param timeout the maximum time in milliseconds to wait for data - * @return true if data is available; false if there was no data available - * even after waiting for {@code timeout} milliseconds. - * @throws IOException if an error happens on the connection - */ - boolean isResponseAvailable(int timeout) - throws IOException; - - /** - * Sends the request line and all headers over the connection. - * @param request the request whose headers to send. - * @throws HttpException in case of HTTP protocol violation - * @throws IOException in case of an I/O error - */ - void sendRequestHeader(HttpRequest request) - throws HttpException, IOException; - - /** - * Sends the request entity over the connection. - * @param request the request whose entity to send. - * @throws HttpException in case of HTTP protocol violation - * @throws IOException in case of an I/O error - */ - void sendRequestEntity(HttpEntityEnclosingRequest request) - throws HttpException, IOException; - - /** - * Receives the request line and headers of the next response available from - * this connection. The caller should examine the HttpResponse object to - * find out if it should try to receive a response entity as well. - * - * @return a new HttpResponse object with status line and headers - * initialized. - * @throws HttpException in case of HTTP protocol violation - * @throws IOException in case of an I/O error - */ - HttpResponse receiveResponseHeader() - throws HttpException, IOException; - - /** - * Receives the next response entity available from this connection and - * attaches it to an existing HttpResponse object. - * - * @param response the response to attach the entity to - * @throws HttpException in case of HTTP protocol violation - * @throws IOException in case of an I/O error - */ - void receiveResponseEntity(HttpResponse response) - throws HttpException, IOException; - - /** - * Writes out all pending buffered data over the open connection. - * - * @throws IOException in case of an I/O error - */ - void flush() throws IOException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpConnection.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpConnection.java deleted file mode 100644 index e2858693..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpConnection.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 com.tracelytics.ext.apache.http; - -import java.io.Closeable; -import java.io.IOException; - -/** - * A generic HTTP connection, useful on client and server side. - * - * @since 4.0 - */ -public interface HttpConnection extends Closeable { - - /** - * Closes this connection gracefully. - * This method will attempt to flush the internal output - * buffer prior to closing the underlying socket. - * This method MUST NOT be called from a different thread to force - * shutdown of the connection. Use {@link #shutdown shutdown} instead. - */ - @Override - void close() throws IOException; - - /** - * Checks if this connection is open. - * @return true if it is open, false if it is closed. - */ - boolean isOpen(); - - /** - * Checks whether this connection has gone down. - * Network connections may get closed during some time of inactivity - * for several reasons. The next time a read is attempted on such a - * connection it will throw an IOException. - * This method tries to alleviate this inconvenience by trying to - * find out if a connection is still usable. Implementations may do - * that by attempting a read with a very small timeout. Thus this - * method may block for a small amount of time before returning a result. - * It is therefore an expensive operation. - * - * @return {@code true} if attempts to use this connection are - * likely to succeed, or {@code false} if they are likely - * to fail and this connection should be closed - */ - boolean isStale(); - - /** - * Sets the socket timeout value. - * - * @param timeout timeout value in milliseconds - */ - void setSocketTimeout(int timeout); - - /** - * Returns the socket timeout value. - * - * @return positive value in milliseconds if a timeout is set, - * {@code 0} if timeout is disabled or {@code -1} if - * timeout is undefined. - */ - int getSocketTimeout(); - - /** - * Force-closes this connection. - * This is the only method of a connection which may be called - * from a different thread to terminate the connection. - * This method will not attempt to flush the transmitter's - * internal buffer prior to closing the underlying socket. - */ - void shutdown() throws IOException; - - /** - * Returns a collection of connection metrics. - * - * @return HttpConnectionMetrics - */ - HttpConnectionMetrics getMetrics(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpConnectionFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpConnectionFactory.java deleted file mode 100644 index c5daffb7..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpConnectionFactory.java +++ /dev/null @@ -1,42 +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 com.tracelytics.ext.apache.http; - -import java.io.IOException; -import java.net.Socket; - -/** - * Factory for {@link HttpConnection} instances. - * - * @since 4.3 - */ -public interface HttpConnectionFactory { - - T createConnection(Socket socket) throws IOException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpConnectionMetrics.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpConnectionMetrics.java deleted file mode 100644 index 247f0ca5..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpConnectionMetrics.java +++ /dev/null @@ -1,77 +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 com.tracelytics.ext.apache.http; - -/** - * The point of access to the statistics of an {@link HttpConnection}. - * - * @since 4.0 - */ -public interface HttpConnectionMetrics { - - /** - * Returns the number of requests transferred over the connection, - * 0 if not available. - */ - long getRequestCount(); - - /** - * Returns the number of responses transferred over the connection, - * 0 if not available. - */ - long getResponseCount(); - - /** - * Returns the number of bytes transferred over the connection, - * 0 if not available. - */ - long getSentBytesCount(); - - /** - * Returns the number of bytes transferred over the connection, - * 0 if not available. - */ - long getReceivedBytesCount(); - - /** - * Return the value for the specified metric. - * - *@param metricName the name of the metric to query. - * - *@return the object representing the metric requested, - * {@code null} if the metric cannot not found. - */ - Object getMetric(String metricName); - - /** - * Resets the counts - * - */ - void reset(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpEntity.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpEntity.java deleted file mode 100644 index 22744a80..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpEntity.java +++ /dev/null @@ -1,199 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package com.tracelytics.ext.apache.http; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - * An entity that can be sent or received with an HTTP message. - * Entities can be found in some - * {@link HttpEntityEnclosingRequest requests} and in - * {@link HttpResponse responses}, where they are optional. - *

- * There are three distinct types of entities in HttpCore, - * depending on where their {@link #getContent content} originates: - *

    - *
  • streamed: The content is received from a stream, or - * generated on the fly. In particular, this category includes - * entities being received from a {@link HttpConnection connection}. - * {@link #isStreaming Streamed} entities are generally not - * {@link #isRepeatable repeatable}. - *
  • - *
  • self-contained: The content is in memory or obtained by - * means that are independent from a connection or other entity. - * Self-contained entities are generally {@link #isRepeatable repeatable}. - *
  • - *
  • wrapping: The content is obtained from another entity. - *
  • - *
- * This distinction is important for connection management with incoming - * entities. For entities that are created by an application and only sent - * using the HTTP components framework, the difference between streamed - * and self-contained is of little importance. In that case, it is suggested - * to consider non-repeatable entities as streamed, and those that are - * repeatable (without a huge effort) as self-contained. - * - * @since 4.0 - */ -public interface HttpEntity { - - /** - * Tells if the entity is capable of producing its data more than once. - * A repeatable entity's getContent() and writeTo(OutputStream) methods - * can be called more than once whereas a non-repeatable entity's can not. - * @return true if the entity is repeatable, false otherwise. - */ - boolean isRepeatable(); - - /** - * Tells about chunked encoding for this entity. - * The primary purpose of this method is to indicate whether - * chunked encoding should be used when the entity is sent. - * For entities that are received, it can also indicate whether - * the entity was received with chunked encoding. - *

- * The behavior of wrapping entities is implementation dependent, - * but should respect the primary purpose. - *

- * - * @return {@code true} if chunked encoding is preferred for this - * entity, or {@code false} if it is not - */ - boolean isChunked(); - - /** - * Tells the length of the content, if known. - * - * @return the number of bytes of the content, or - * a negative number if unknown. If the content length is known - * but exceeds {@link java.lang.Long#MAX_VALUE Long.MAX_VALUE}, - * a negative number is returned. - */ - long getContentLength(); - - /** - * Obtains the Content-Type header, if known. - * This is the header that should be used when sending the entity, - * or the one that was received with the entity. It can include a - * charset attribute. - * - * @return the Content-Type header for this entity, or - * {@code null} if the content type is unknown - */ - Header getContentType(); - - /** - * Obtains the Content-Encoding header, if known. - * This is the header that should be used when sending the entity, - * or the one that was received with the entity. - * Wrapping entities that modify the content encoding should - * adjust this header accordingly. - * - * @return the Content-Encoding header for this entity, or - * {@code null} if the content encoding is unknown - */ - Header getContentEncoding(); - - /** - * Returns a content stream of the entity. - * {@link #isRepeatable Repeatable} entities are expected - * to create a new instance of {@link InputStream} for each invocation - * of this method and therefore can be consumed multiple times. - * Entities that are not {@link #isRepeatable repeatable} are expected - * to return the same {@link InputStream} instance and therefore - * may not be consumed more than once. - *

- * IMPORTANT: Please note all entity implementations must ensure that - * all allocated resources are properly deallocated after - * the {@link InputStream#close()} method is invoked. - * - * @return content stream of the entity. - * - * @throws IOException if the stream could not be created - * @throws UnsupportedOperationException - * if entity content cannot be represented as {@link java.io.InputStream}. - * - * @see #isRepeatable() - */ - InputStream getContent() throws IOException, UnsupportedOperationException; - - /** - * Writes the entity content out to the output stream. - *

- * IMPORTANT: Please note all entity implementations must ensure that - * all allocated resources are properly deallocated when this method - * returns. - * - * @param outstream the output stream to write entity content to - * - * @throws IOException if an I/O error occurs - */ - void writeTo(OutputStream outstream) throws IOException; - - /** - * Tells whether this entity depends on an underlying stream. - * Streamed entities that read data directly from the socket should - * return {@code true}. Self-contained entities should return - * {@code false}. Wrapping entities should delegate this call - * to the wrapped entity. - * - * @return {@code true} if the entity content is streamed, - * {@code false} otherwise - */ - boolean isStreaming(); // don't expect an exception here - - /** - * This method is deprecated since version 4.1. Please use standard - * java convention to ensure resource deallocation by calling - * {@link InputStream#close()} on the input stream returned by - * {@link #getContent()} - *

- * This method is called to indicate that the content of this entity - * is no longer required. All entity implementations are expected to - * release all allocated resources as a result of this method - * invocation. Content streaming entities are also expected to - * dispose of the remaining content, if any. Wrapping entities should - * delegate this call to the wrapped entity. - *

- * This method is of particular importance for entities being - * received from a {@link HttpConnection connection}. The entity - * needs to be consumed completely in order to re-use the connection - * with keep-alive. - * - * @throws IOException if an I/O error occurs. - * - * @deprecated (4.1) Use {@link com.tracelytics.ext.apache.http.util.EntityUtils#consume(HttpEntity)} - * - * @see #getContent() and #writeTo(OutputStream) - */ - @Deprecated - void consumeContent() throws IOException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpEntityEnclosingRequest.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpEntityEnclosingRequest.java deleted file mode 100644 index 844e191e..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpEntityEnclosingRequest.java +++ /dev/null @@ -1,60 +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 com.tracelytics.ext.apache.http; - -/** - * A request with an entity. - * - * @since 4.0 - */ -public interface HttpEntityEnclosingRequest extends HttpRequest { - - /** - * Tells if this request should use the expect-continue handshake. - * The expect continue handshake gives the server a chance to decide - * whether to accept the entity enclosing request before the possibly - * lengthy entity is sent across the wire. - * @return true if the expect continue handshake should be used, false if - * not. - */ - boolean expectContinue(); - - /** - * Associates the entity with this request. - * - * @param entity the entity to send. - */ - void setEntity(HttpEntity entity); - - /** - * Returns the entity associated with this request. - * - * @return entity - */ - HttpEntity getEntity(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpException.java deleted file mode 100644 index 0daa1901..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpException.java +++ /dev/null @@ -1,67 +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 com.tracelytics.ext.apache.http; - -/** - * Signals that an HTTP exception has occurred. - * - * @since 4.0 - */ -public class HttpException extends Exception { - - private static final long serialVersionUID = -5437299376222011036L; - - /** - * Creates a new HttpException with a {@code null} detail message. - */ - public HttpException() { - super(); - } - - /** - * Creates a new HttpException with the specified detail message. - * - * @param message the exception detail message - */ - public HttpException(final String message) { - super(message); - } - - /** - * Creates a new HttpException with the specified detail message and cause. - * - * @param message the exception detail message - * @param cause the {@code Throwable} that caused this exception, or {@code null} - * if the cause is unavailable, unknown, or not a {@code Throwable} - */ - public HttpException(final String message, final Throwable cause) { - super(message); - initCause(cause); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpHeaders.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpHeaders.java deleted file mode 100644 index c68ff089..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpHeaders.java +++ /dev/null @@ -1,206 +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 com.tracelytics.ext.apache.http; - -/** - * Constants enumerating the HTTP headers. All headers defined in RFC1945 (HTTP/1.0), RFC2616 (HTTP/1.1), and RFC2518 - * (WebDAV) are listed. - * - * @since 4.1 - */ -public final class HttpHeaders { - - private HttpHeaders() { - } - - /** RFC 2616 (HTTP/1.1) Section 14.1 */ - public static final String ACCEPT = "Accept"; - - /** RFC 2616 (HTTP/1.1) Section 14.2 */ - public static final String ACCEPT_CHARSET = "Accept-Charset"; - - /** RFC 2616 (HTTP/1.1) Section 14.3 */ - public static final String ACCEPT_ENCODING = "Accept-Encoding"; - - /** RFC 2616 (HTTP/1.1) Section 14.4 */ - public static final String ACCEPT_LANGUAGE = "Accept-Language"; - - /** RFC 2616 (HTTP/1.1) Section 14.5 */ - public static final String ACCEPT_RANGES = "Accept-Ranges"; - - /** RFC 2616 (HTTP/1.1) Section 14.6 */ - public static final String AGE = "Age"; - - /** RFC 1945 (HTTP/1.0) Section 10.1, RFC 2616 (HTTP/1.1) Section 14.7 */ - public static final String ALLOW = "Allow"; - - /** RFC 1945 (HTTP/1.0) Section 10.2, RFC 2616 (HTTP/1.1) Section 14.8 */ - public static final String AUTHORIZATION = "Authorization"; - - /** RFC 2616 (HTTP/1.1) Section 14.9 */ - public static final String CACHE_CONTROL = "Cache-Control"; - - /** RFC 2616 (HTTP/1.1) Section 14.10 */ - public static final String CONNECTION = "Connection"; - - /** RFC 1945 (HTTP/1.0) Section 10.3, RFC 2616 (HTTP/1.1) Section 14.11 */ - public static final String CONTENT_ENCODING = "Content-Encoding"; - - /** RFC 2616 (HTTP/1.1) Section 14.12 */ - public static final String CONTENT_LANGUAGE = "Content-Language"; - - /** RFC 1945 (HTTP/1.0) Section 10.4, RFC 2616 (HTTP/1.1) Section 14.13 */ - public static final String CONTENT_LENGTH = "Content-Length"; - - /** RFC 2616 (HTTP/1.1) Section 14.14 */ - public static final String CONTENT_LOCATION = "Content-Location"; - - /** RFC 2616 (HTTP/1.1) Section 14.15 */ - public static final String CONTENT_MD5 = "Content-MD5"; - - /** RFC 2616 (HTTP/1.1) Section 14.16 */ - public static final String CONTENT_RANGE = "Content-Range"; - - /** RFC 1945 (HTTP/1.0) Section 10.5, RFC 2616 (HTTP/1.1) Section 14.17 */ - public static final String CONTENT_TYPE = "Content-Type"; - - /** RFC 1945 (HTTP/1.0) Section 10.6, RFC 2616 (HTTP/1.1) Section 14.18 */ - public static final String DATE = "Date"; - - /** RFC 2518 (WevDAV) Section 9.1 */ - public static final String DAV = "Dav"; - - /** RFC 2518 (WevDAV) Section 9.2 */ - public static final String DEPTH = "Depth"; - - /** RFC 2518 (WevDAV) Section 9.3 */ - public static final String DESTINATION = "Destination"; - - /** RFC 2616 (HTTP/1.1) Section 14.19 */ - public static final String ETAG = "ETag"; - - /** RFC 2616 (HTTP/1.1) Section 14.20 */ - public static final String EXPECT = "Expect"; - - /** RFC 1945 (HTTP/1.0) Section 10.7, RFC 2616 (HTTP/1.1) Section 14.21 */ - public static final String EXPIRES = "Expires"; - - /** RFC 1945 (HTTP/1.0) Section 10.8, RFC 2616 (HTTP/1.1) Section 14.22 */ - public static final String FROM = "From"; - - /** RFC 2616 (HTTP/1.1) Section 14.23 */ - public static final String HOST = "Host"; - - /** RFC 2518 (WevDAV) Section 9.4 */ - public static final String IF = "If"; - - /** RFC 2616 (HTTP/1.1) Section 14.24 */ - public static final String IF_MATCH = "If-Match"; - - /** RFC 1945 (HTTP/1.0) Section 10.9, RFC 2616 (HTTP/1.1) Section 14.25 */ - public static final String IF_MODIFIED_SINCE = "If-Modified-Since"; - - /** RFC 2616 (HTTP/1.1) Section 14.26 */ - public static final String IF_NONE_MATCH = "If-None-Match"; - - /** RFC 2616 (HTTP/1.1) Section 14.27 */ - public static final String IF_RANGE = "If-Range"; - - /** RFC 2616 (HTTP/1.1) Section 14.28 */ - public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since"; - - /** RFC 1945 (HTTP/1.0) Section 10.10, RFC 2616 (HTTP/1.1) Section 14.29 */ - public static final String LAST_MODIFIED = "Last-Modified"; - - /** RFC 1945 (HTTP/1.0) Section 10.11, RFC 2616 (HTTP/1.1) Section 14.30 */ - public static final String LOCATION = "Location"; - - /** RFC 2518 (WevDAV) Section 9.5 */ - public static final String LOCK_TOKEN = "Lock-Token"; - - /** RFC 2616 (HTTP/1.1) Section 14.31 */ - public static final String MAX_FORWARDS = "Max-Forwards"; - - /** RFC 2518 (WevDAV) Section 9.6 */ - public static final String OVERWRITE = "Overwrite"; - - /** RFC 1945 (HTTP/1.0) Section 10.12, RFC 2616 (HTTP/1.1) Section 14.32 */ - public static final String PRAGMA = "Pragma"; - - /** RFC 2616 (HTTP/1.1) Section 14.33 */ - public static final String PROXY_AUTHENTICATE = "Proxy-Authenticate"; - - /** RFC 2616 (HTTP/1.1) Section 14.34 */ - public static final String PROXY_AUTHORIZATION = "Proxy-Authorization"; - - /** RFC 2616 (HTTP/1.1) Section 14.35 */ - public static final String RANGE = "Range"; - - /** RFC 1945 (HTTP/1.0) Section 10.13, RFC 2616 (HTTP/1.1) Section 14.36 */ - public static final String REFERER = "Referer"; - - /** RFC 2616 (HTTP/1.1) Section 14.37 */ - public static final String RETRY_AFTER = "Retry-After"; - - /** RFC 1945 (HTTP/1.0) Section 10.14, RFC 2616 (HTTP/1.1) Section 14.38 */ - public static final String SERVER = "Server"; - - /** RFC 2518 (WevDAV) Section 9.7 */ - public static final String STATUS_URI = "Status-URI"; - - /** RFC 2616 (HTTP/1.1) Section 14.39 */ - public static final String TE = "TE"; - - /** RFC 2518 (WevDAV) Section 9.8 */ - public static final String TIMEOUT = "Timeout"; - - /** RFC 2616 (HTTP/1.1) Section 14.40 */ - public static final String TRAILER = "Trailer"; - - /** RFC 2616 (HTTP/1.1) Section 14.41 */ - public static final String TRANSFER_ENCODING = "Transfer-Encoding"; - - /** RFC 2616 (HTTP/1.1) Section 14.42 */ - public static final String UPGRADE = "Upgrade"; - - /** RFC 1945 (HTTP/1.0) Section 10.15, RFC 2616 (HTTP/1.1) Section 14.43 */ - public static final String USER_AGENT = "User-Agent"; - - /** RFC 2616 (HTTP/1.1) Section 14.44 */ - public static final String VARY = "Vary"; - - /** RFC 2616 (HTTP/1.1) Section 14.45 */ - public static final String VIA = "Via"; - - /** RFC 2616 (HTTP/1.1) Section 14.46 */ - public static final String WARNING = "Warning"; - - /** RFC 1945 (HTTP/1.0) Section 10.16, RFC 2616 (HTTP/1.1) Section 14.47 */ - public static final String WWW_AUTHENTICATE = "WWW-Authenticate"; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpHost.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpHost.java deleted file mode 100644 index 41b72336..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpHost.java +++ /dev/null @@ -1,338 +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 com.tracelytics.ext.apache.http; - -import java.io.Serializable; -import java.net.InetAddress; -import java.util.Locale; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.LangUtils; - -/** - * Holds all of the variables needed to describe an HTTP connection to a host. - * This includes remote host name, port and scheme. - * - * - * @since 4.0 - */ -@Immutable -public final class HttpHost implements Cloneable, Serializable { - - private static final long serialVersionUID = -7529410654042457626L; - - /** The default scheme is "http". */ - public static final String DEFAULT_SCHEME_NAME = "http"; - - /** The host to use. */ - protected final String hostname; - - /** The lowercase host, for {@link #equals} and {@link #hashCode}. */ - protected final String lcHostname; - - - /** The port to use, defaults to -1 if not set. */ - protected final int port; - - /** The scheme (lowercased) */ - protected final String schemeName; - - protected final InetAddress address; - - /** - * Creates {@code HttpHost} instance with the given scheme, hostname and port. - * - * @param hostname the hostname (IP or DNS name) - * @param port the port number. - * {@code -1} indicates the scheme default port. - * @param scheme the name of the scheme. - * {@code null} indicates the - * {@link #DEFAULT_SCHEME_NAME default scheme} - */ - public HttpHost(final String hostname, final int port, final String scheme) { - super(); - this.hostname = Args.containsNoBlanks(hostname, "Host name"); - this.lcHostname = hostname.toLowerCase(Locale.ROOT); - if (scheme != null) { - this.schemeName = scheme.toLowerCase(Locale.ROOT); - } else { - this.schemeName = DEFAULT_SCHEME_NAME; - } - this.port = port; - this.address = null; - } - - /** - * Creates {@code HttpHost} instance with the default scheme and the given hostname and port. - * - * @param hostname the hostname (IP or DNS name) - * @param port the port number. - * {@code -1} indicates the scheme default port. - */ - public HttpHost(final String hostname, final int port) { - this(hostname, port, null); - } - - /** - * Creates {@code HttpHost} instance from string. Text may not contain any blanks. - * - * @since 4.4 - */ - public static HttpHost create(final String s) { - Args.containsNoBlanks(s, "HTTP Host"); - String text = s; - String scheme = null; - final int schemeIdx = text.indexOf("://"); - if (schemeIdx > 0) { - scheme = text.substring(0, schemeIdx); - text = text.substring(schemeIdx + 3); - } - int port = -1; - final int portIdx = text.lastIndexOf(":"); - if (portIdx > 0) { - try { - port = Integer.parseInt(text.substring(portIdx + 1)); - } catch (NumberFormatException ex) { - throw new IllegalArgumentException("Invalid HTTP host: " + text); - } - text = text.substring(0, portIdx); - } - return new HttpHost(text, port, scheme); - } - - /** - * Creates {@code HttpHost} instance with the default scheme and port and the given hostname. - * - * @param hostname the hostname (IP or DNS name) - */ - public HttpHost(final String hostname) { - this(hostname, -1, null); - } - - /** - * Creates {@code HttpHost} instance with the given scheme, inet address and port. - * - * @param address the inet address. - * @param port the port number. - * {@code -1} indicates the scheme default port. - * @param scheme the name of the scheme. - * {@code null} indicates the - * {@link #DEFAULT_SCHEME_NAME default scheme} - * - * @since 4.3 - */ - public HttpHost(final InetAddress address, final int port, final String scheme) { - this(Args.notNull(address,"Inet address"), address.getHostName(), port, scheme); - } - /** - * Creates a new {@link HttpHost HttpHost}, specifying all values. - * Constructor for HttpHost. - * - * @param address the inet address. - * @param hostname the hostname (IP or DNS name) - * @param port the port number. - * {@code -1} indicates the scheme default port. - * @param scheme the name of the scheme. - * {@code null} indicates the - * {@link #DEFAULT_SCHEME_NAME default scheme} - * - * @since 4.4 - */ - public HttpHost(final InetAddress address, final String hostname, final int port, final String scheme) { - super(); - this.address = Args.notNull(address, "Inet address"); - this.hostname = Args.notNull(hostname, "Hostname"); - this.lcHostname = this.hostname.toLowerCase(Locale.ROOT); - if (scheme != null) { - this.schemeName = scheme.toLowerCase(Locale.ROOT); - } else { - this.schemeName = DEFAULT_SCHEME_NAME; - } - this.port = port; - } - - /** - * Creates {@code HttpHost} instance with the default scheme and the given inet address - * and port. - * - * @param address the inet address. - * @param port the port number. - * {@code -1} indicates the scheme default port. - * - * @since 4.3 - */ - public HttpHost(final InetAddress address, final int port) { - this(address, port, null); - } - - /** - * Creates {@code HttpHost} instance with the default scheme and port and the given inet - * address. - * - * @param address the inet address. - * - * @since 4.3 - */ - public HttpHost(final InetAddress address) { - this(address, -1, null); - } - - /** - * Copy constructor for {@link HttpHost HttpHost}. - * - * @param httphost the HTTP host to copy details from - */ - public HttpHost (final HttpHost httphost) { - super(); - Args.notNull(httphost, "HTTP host"); - this.hostname = httphost.hostname; - this.lcHostname = httphost.lcHostname; - this.schemeName = httphost.schemeName; - this.port = httphost.port; - this.address = httphost.address; - } - - /** - * Returns the host name. - * - * @return the host name (IP or DNS name) - */ - public String getHostName() { - return this.hostname; - } - - /** - * Returns the port. - * - * @return the host port, or {@code -1} if not set - */ - public int getPort() { - return this.port; - } - - /** - * Returns the scheme name. - * - * @return the scheme name - */ - public String getSchemeName() { - return this.schemeName; - } - - /** - * Returns the inet address if explicitly set by a constructor, - * {@code null} otherwise. - * @return the inet address - * - * @since 4.3 - */ - public InetAddress getAddress() { - return this.address; - } - - /** - * Return the host URI, as a string. - * - * @return the host URI - */ - public String toURI() { - final StringBuilder buffer = new StringBuilder(); - buffer.append(this.schemeName); - buffer.append("://"); - buffer.append(this.hostname); - if (this.port != -1) { - buffer.append(':'); - buffer.append(Integer.toString(this.port)); - } - return buffer.toString(); - } - - - /** - * Obtains the host string, without scheme prefix. - * - * @return the host string, for example {@code localhost:8080} - */ - public String toHostString() { - if (this.port != -1) { - //the highest port number is 65535, which is length 6 with the addition of the colon - final StringBuilder buffer = new StringBuilder(this.hostname.length() + 6); - buffer.append(this.hostname); - buffer.append(":"); - buffer.append(Integer.toString(this.port)); - return buffer.toString(); - } else { - return this.hostname; - } - } - - - @Override - public String toString() { - return toURI(); - } - - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof HttpHost) { - final HttpHost that = (HttpHost) obj; - return this.lcHostname.equals(that.lcHostname) - && this.port == that.port - && this.schemeName.equals(that.schemeName) - && (this.address==null ? that.address== null : this.address.equals(that.address)); - } else { - return false; - } - } - - /** - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - int hash = LangUtils.HASH_SEED; - hash = LangUtils.hashCode(hash, this.lcHostname); - hash = LangUtils.hashCode(hash, this.port); - hash = LangUtils.hashCode(hash, this.schemeName); - if (address!=null) { - hash = LangUtils.hashCode(hash, address); - } - return hash; - } - - @Override - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpInetConnection.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpInetConnection.java deleted file mode 100644 index fce0d353..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpInetConnection.java +++ /dev/null @@ -1,47 +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 com.tracelytics.ext.apache.http; - -import java.net.InetAddress; - -/** - * An HTTP connection over the Internet Protocol (IP). - * - * @since 4.0 - */ -public interface HttpInetConnection extends HttpConnection { - - InetAddress getLocalAddress(); - - int getLocalPort(); - - InetAddress getRemoteAddress(); - - int getRemotePort(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpMessage.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpMessage.java deleted file mode 100644 index 50399589..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpMessage.java +++ /dev/null @@ -1,210 +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 com.tracelytics.ext.apache.http; - -import com.tracelytics.ext.apache.http.params.HttpParams; - -/** - * HTTP messages consist of requests from client to server and responses - * from server to client. - *

- *     HTTP-message   = Request | Response     ; HTTP/1.1 messages
- * 
- *

- * HTTP messages use the generic message format of RFC 822 for - * transferring entities (the payload of the message). Both types - * of message consist of a start-line, zero or more header fields - * (also known as "headers"), an empty line (i.e., a line with nothing - * preceding the CRLF) indicating the end of the header fields, - * and possibly a message-body. - *

- *
- *      generic-message = start-line
- *                        *(message-header CRLF)
- *                        CRLF
- *                        [ message-body ]
- *      start-line      = Request-Line | Status-Line
- * 
- * - * @since 4.0 - */ -@SuppressWarnings("deprecation") -public interface HttpMessage { - - /** - * Returns the protocol version this message is compatible with. - */ - ProtocolVersion getProtocolVersion(); - - /** - * Checks if a certain header is present in this message. Header values are - * ignored. - * - * @param name the header name to check for. - * @return true if at least one header with this name is present. - */ - boolean containsHeader(String name); - - /** - * Returns all the headers with a specified name of this message. Header values - * are ignored. Headers are orderd in the sequence they will be sent over a - * connection. - * - * @param name the name of the headers to return. - * @return the headers whose name property equals {@code name}. - */ - Header[] getHeaders(String name); - - /** - * Returns the first header with a specified name of this message. Header - * values are ignored. If there is more than one matching header in the - * message the first element of {@link #getHeaders(String)} is returned. - * If there is no matching header in the message {@code null} is - * returned. - * - * @param name the name of the header to return. - * @return the first header whose name property equals {@code name} - * or {@code null} if no such header could be found. - */ - Header getFirstHeader(String name); - - /** - * Returns the last header with a specified name of this message. Header values - * are ignored. If there is more than one matching header in the message the - * last element of {@link #getHeaders(String)} is returned. If there is no - * matching header in the message {@code null} is returned. - * - * @param name the name of the header to return. - * @return the last header whose name property equals {@code name}. - * or {@code null} if no such header could be found. - */ - Header getLastHeader(String name); - - /** - * Returns all the headers of this message. Headers are orderd in the sequence - * they will be sent over a connection. - * - * @return all the headers of this message - */ - Header[] getAllHeaders(); - - /** - * Adds a header to this message. The header will be appended to the end of - * the list. - * - * @param header the header to append. - */ - void addHeader(Header header); - - /** - * Adds a header to this message. The header will be appended to the end of - * the list. - * - * @param name the name of the header. - * @param value the value of the header. - */ - void addHeader(String name, String value); - - /** - * Overwrites the first header with the same name. The new header will be appended to - * the end of the list, if no header with the given name can be found. - * - * @param header the header to set. - */ - void setHeader(Header header); - - /** - * Overwrites the first header with the same name. The new header will be appended to - * the end of the list, if no header with the given name can be found. - * - * @param name the name of the header. - * @param value the value of the header. - */ - void setHeader(String name, String value); - - /** - * Overwrites all the headers in the message. - * - * @param headers the array of headers to set. - */ - void setHeaders(Header[] headers); - - /** - * Removes a header from this message. - * - * @param header the header to remove. - */ - void removeHeader(Header header); - - /** - * Removes all headers with a certain name from this message. - * - * @param name The name of the headers to remove. - */ - void removeHeaders(String name); - - /** - * Returns an iterator of all the headers. - * - * @return Iterator that returns Header objects in the sequence they are - * sent over a connection. - */ - HeaderIterator headerIterator(); - - /** - * Returns an iterator of the headers with a given name. - * - * @param name the name of the headers over which to iterate, or - * {@code null} for all headers - * - * @return Iterator that returns Header objects with the argument name - * in the sequence they are sent over a connection. - */ - HeaderIterator headerIterator(String name); - - /** - * Returns the parameters effective for this message as set by - * {@link #setParams(HttpParams)}. - * - * @deprecated (4.3) use configuration classes provided 'com.tracelytics.ext.apache.http.config' - * and 'com.tracelytics.ext.apache.http.client.config' - */ - @Deprecated - HttpParams getParams(); - - /** - * Provides parameters to be used for the processing of this message. - * @param params the parameters - * - * @deprecated (4.3) use configuration classes provided 'com.tracelytics.ext.apache.http.config' - * and 'com.tracelytics.ext.apache.http.client.config' - */ - @Deprecated - void setParams(HttpParams params); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpRequest.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpRequest.java deleted file mode 100644 index 32d9c5f7..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpRequest.java +++ /dev/null @@ -1,53 +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 com.tracelytics.ext.apache.http; - -/** - * A request message from a client to a server includes, within the - * first line of that message, the method to be applied to the resource, - * the identifier of the resource, and the protocol version in use. - *
- *      Request       = Request-Line
- *                      *(( general-header
- *                       | request-header
- *                       | entity-header ) CRLF)
- *                      CRLF
- *                      [ message-body ]
- * 
- * - * @since 4.0 - */ -public interface HttpRequest extends HttpMessage { - - /** - * Returns the request line of this request. - * @return the request line. - */ - RequestLine getRequestLine(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpRequestFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpRequestFactory.java deleted file mode 100644 index 850b9f70..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpRequestFactory.java +++ /dev/null @@ -1,43 +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 com.tracelytics.ext.apache.http; - -/** - * A factory for {@link HttpRequest HttpRequest} objects. - * - * @since 4.0 - */ -public interface HttpRequestFactory { - - HttpRequest newHttpRequest(RequestLine requestline) - throws MethodNotSupportedException; - - HttpRequest newHttpRequest(String method, String uri) - throws MethodNotSupportedException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpRequestInterceptor.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpRequestInterceptor.java deleted file mode 100644 index 11a47b37..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpRequestInterceptor.java +++ /dev/null @@ -1,68 +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 com.tracelytics.ext.apache.http; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -/** - * HTTP protocol interceptor is a routine that implements a specific aspect of - * the HTTP protocol. Usually protocol interceptors are expected to act upon - * one specific header or a group of related headers of the incoming message - * or populate the outgoing message with one specific header or a group of - * related headers. - *

- * Protocol Interceptors can also manipulate content entities enclosed with messages. - * Usually this is accomplished by using the 'Decorator' pattern where a wrapper - * entity class is used to decorate the original entity. - *

- * Protocol interceptors must be implemented as thread-safe. Similarly to - * servlets, protocol interceptors should not use instance variables unless - * access to those variables is synchronized. - * - * @since 4.0 - */ -public interface HttpRequestInterceptor { - - /** - * Processes a request. - * On the client side, this step is performed before the request is - * sent to the server. On the server side, this step is performed - * on incoming messages before the message body is evaluated. - * - * @param request the request to preprocess - * @param context the context for the request - * - * @throws HttpException in case of an HTTP protocol violation - * @throws IOException in case of an I/O error - */ - void process(HttpRequest request, HttpContext context) - throws HttpException, IOException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpResponse.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpResponse.java deleted file mode 100644 index d80d7236..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpResponse.java +++ /dev/null @@ -1,155 +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 com.tracelytics.ext.apache.http; - -import java.util.Locale; - -/** - * After receiving and interpreting a request message, a server responds - * with an HTTP response message. - *

- *     Response      = Status-Line
- *                     *(( general-header
- *                      | response-header
- *                      | entity-header ) CRLF)
- *                     CRLF
- *                     [ message-body ]
- * 
- * - * @since 4.0 - */ -public interface HttpResponse extends HttpMessage { - - /** - * Obtains the status line of this response. - * The status line can be set using one of the - * {@link #setStatusLine setStatusLine} methods, - * or it can be initialized in a constructor. - * - * @return the status line, or {@code null} if not yet set - */ - StatusLine getStatusLine(); - - /** - * Sets the status line of this response. - * - * @param statusline the status line of this response - */ - void setStatusLine(StatusLine statusline); - - /** - * Sets the status line of this response. - * The reason phrase will be determined based on the current - * {@link #getLocale locale}. - * - * @param ver the HTTP version - * @param code the status code - */ - void setStatusLine(ProtocolVersion ver, int code); - - /** - * Sets the status line of this response with a reason phrase. - * - * @param ver the HTTP version - * @param code the status code - * @param reason the reason phrase, or {@code null} to omit - */ - void setStatusLine(ProtocolVersion ver, int code, String reason); - - /** - * Updates the status line of this response with a new status code. - * - * @param code the HTTP status code. - * - * @throws IllegalStateException - * if the status line has not be set - * - * @see HttpStatus - * @see #setStatusLine(StatusLine) - * @see #setStatusLine(ProtocolVersion,int) - */ - void setStatusCode(int code) - throws IllegalStateException; - - /** - * Updates the status line of this response with a new reason phrase. - * - * @param reason the new reason phrase as a single-line string, or - * {@code null} to unset the reason phrase - * - * @throws IllegalStateException - * if the status line has not be set - * - * @see #setStatusLine(StatusLine) - * @see #setStatusLine(ProtocolVersion,int) - */ - void setReasonPhrase(String reason) - throws IllegalStateException; - - /** - * Obtains the message entity of this response, if any. - * The entity is provided by calling {@link #setEntity setEntity}. - * - * @return the response entity, or - * {@code null} if there is none - */ - HttpEntity getEntity(); - - /** - * Associates a response entity with this response. - *

- * Please note that if an entity has already been set for this response and it depends on - * an input stream ({@link HttpEntity#isStreaming()} returns {@code true}), - * it must be fully consumed in order to ensure release of resources. - * - * @param entity the entity to associate with this response, or - * {@code null} to unset - * - * @see HttpEntity#isStreaming() - * @see com.tracelytics.ext.apache.http.util.EntityUtils#updateEntity(HttpResponse, HttpEntity) - */ - void setEntity(HttpEntity entity); - - /** - * Obtains the locale of this response. - * The locale is used to determine the reason phrase - * for the {@link #setStatusCode status code}. - * It can be changed using {@link #setLocale setLocale}. - * - * @return the locale of this response, never {@code null} - */ - Locale getLocale(); - - /** - * Changes the locale of this response. - * - * @param loc the new locale - */ - void setLocale(Locale loc); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpResponseFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpResponseFactory.java deleted file mode 100644 index d3de29ca..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpResponseFactory.java +++ /dev/null @@ -1,67 +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 com.tracelytics.ext.apache.http; - -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -/** - * A factory for {@link HttpResponse HttpResponse} objects. - * - * @since 4.0 - */ -public interface HttpResponseFactory { - - /** - * Creates a new response from status line elements. - * - * @param ver the protocol version - * @param status the status code - * @param context the context from which to determine the locale - * for looking up a reason phrase to the status code, or - * {@code null} to use the default locale - * - * @return the new response with an initialized status line - */ - HttpResponse newHttpResponse(ProtocolVersion ver, int status, - HttpContext context); - - /** - * Creates a new response from a status line. - * - * @param statusline the status line - * @param context the context from which to determine the locale - * for looking up a reason phrase if the status code - * is updated, or - * {@code null} to use the default locale - * - * @return the new response with the argument status line - */ - HttpResponse newHttpResponse(StatusLine statusline, - HttpContext context); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpResponseInterceptor.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpResponseInterceptor.java deleted file mode 100644 index ce5b277f..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpResponseInterceptor.java +++ /dev/null @@ -1,68 +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 com.tracelytics.ext.apache.http; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -/** - * HTTP protocol interceptor is a routine that implements a specific aspect of - * the HTTP protocol. Usually protocol interceptors are expected to act upon - * one specific header or a group of related headers of the incoming message - * or populate the outgoing message with one specific header or a group of - * related headers. Protocol - *

- * Interceptors can also manipulate content entities enclosed with messages. - * Usually this is accomplished by using the 'Decorator' pattern where a wrapper - * entity class is used to decorate the original entity. - *

- * Protocol interceptors must be implemented as thread-safe. Similarly to - * servlets, protocol interceptors should not use instance variables unless - * access to those variables is synchronized. - * - * @since 4.0 - */ -public interface HttpResponseInterceptor { - - /** - * Processes a response. - * On the server side, this step is performed before the response is - * sent to the client. On the client side, this step is performed - * on incoming messages before the message body is evaluated. - * - * @param response the response to postprocess - * @param context the context for the request - * - * @throws HttpException in case of an HTTP protocol violation - * @throws IOException in case of an I/O error - */ - void process(HttpResponse response, HttpContext context) - throws HttpException, IOException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpServerConnection.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpServerConnection.java deleted file mode 100644 index 7e030b8b..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpServerConnection.java +++ /dev/null @@ -1,88 +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 com.tracelytics.ext.apache.http; - -import java.io.IOException; - -/** - * A server-side HTTP connection, which can be used for receiving - * requests and sending responses. - * - * @since 4.0 - */ -public interface HttpServerConnection extends HttpConnection { - - /** - * Receives the request line and all headers available from this connection. - * The caller should examine the returned request and decide if to receive a - * request entity as well. - * - * @return a new HttpRequest object whose request line and headers are - * initialized. - * @throws HttpException in case of HTTP protocol violation - * @throws IOException in case of an I/O error - */ - HttpRequest receiveRequestHeader() - throws HttpException, IOException; - - /** - * Receives the next request entity available from this connection and attaches it to - * an existing request. - * @param request the request to attach the entity to. - * @throws HttpException in case of HTTP protocol violation - * @throws IOException in case of an I/O error - */ - void receiveRequestEntity(HttpEntityEnclosingRequest request) - throws HttpException, IOException; - - /** - * Sends the response line and headers of a response over this connection. - * @param response the response whose headers to send. - * @throws HttpException in case of HTTP protocol violation - * @throws IOException in case of an I/O error - */ - void sendResponseHeader(HttpResponse response) - throws HttpException, IOException; - - /** - * Sends the response entity of a response over this connection. - * @param response the response whose entity to send. - * @throws HttpException in case of HTTP protocol violation - * @throws IOException in case of an I/O error - */ - void sendResponseEntity(HttpResponse response) - throws HttpException, IOException; - - /** - * Sends all pending buffered data over this connection. - * @throws IOException in case of an I/O error - */ - void flush() - throws IOException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpStatus.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpStatus.java deleted file mode 100644 index bc910e42..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpStatus.java +++ /dev/null @@ -1,176 +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 com.tracelytics.ext.apache.http; - -/** - * Constants enumerating the HTTP status codes. - * All status codes defined in RFC1945 (HTTP/1.0), RFC2616 (HTTP/1.1), and - * RFC2518 (WebDAV) are listed. - * - * @see StatusLine - * - * @since 4.0 - */ -public interface HttpStatus { - - // --- 1xx Informational --- - - /** {@code 100 Continue} (HTTP/1.1 - RFC 2616) */ - public static final int SC_CONTINUE = 100; - /** {@code 101 Switching Protocols} (HTTP/1.1 - RFC 2616)*/ - public static final int SC_SWITCHING_PROTOCOLS = 101; - /** {@code 102 Processing} (WebDAV - RFC 2518) */ - public static final int SC_PROCESSING = 102; - - // --- 2xx Success --- - - /** {@code 200 OK} (HTTP/1.0 - RFC 1945) */ - public static final int SC_OK = 200; - /** {@code 201 Created} (HTTP/1.0 - RFC 1945) */ - public static final int SC_CREATED = 201; - /** {@code 202 Accepted} (HTTP/1.0 - RFC 1945) */ - public static final int SC_ACCEPTED = 202; - /** {@code 203 Non Authoritative Information} (HTTP/1.1 - RFC 2616) */ - public static final int SC_NON_AUTHORITATIVE_INFORMATION = 203; - /** {@code 204 No Content} (HTTP/1.0 - RFC 1945) */ - public static final int SC_NO_CONTENT = 204; - /** {@code 205 Reset Content} (HTTP/1.1 - RFC 2616) */ - public static final int SC_RESET_CONTENT = 205; - /** {@code 206 Partial Content} (HTTP/1.1 - RFC 2616) */ - public static final int SC_PARTIAL_CONTENT = 206; - /** - * {@code 207 Multi-Status} (WebDAV - RFC 2518) - * or - * {@code 207 Partial Update OK} (HTTP/1.1 - draft-ietf-http-v11-spec-rev-01?) - */ - public static final int SC_MULTI_STATUS = 207; - - // --- 3xx Redirection --- - - /** {@code 300 Mutliple Choices} (HTTP/1.1 - RFC 2616) */ - public static final int SC_MULTIPLE_CHOICES = 300; - /** {@code 301 Moved Permanently} (HTTP/1.0 - RFC 1945) */ - public static final int SC_MOVED_PERMANENTLY = 301; - /** {@code 302 Moved Temporarily} (Sometimes {@code Found}) (HTTP/1.0 - RFC 1945) */ - public static final int SC_MOVED_TEMPORARILY = 302; - /** {@code 303 See Other} (HTTP/1.1 - RFC 2616) */ - public static final int SC_SEE_OTHER = 303; - /** {@code 304 Not Modified} (HTTP/1.0 - RFC 1945) */ - public static final int SC_NOT_MODIFIED = 304; - /** {@code 305 Use Proxy} (HTTP/1.1 - RFC 2616) */ - public static final int SC_USE_PROXY = 305; - /** {@code 307 Temporary Redirect} (HTTP/1.1 - RFC 2616) */ - public static final int SC_TEMPORARY_REDIRECT = 307; - - // --- 4xx Client Error --- - - /** {@code 400 Bad Request} (HTTP/1.1 - RFC 2616) */ - public static final int SC_BAD_REQUEST = 400; - /** {@code 401 Unauthorized} (HTTP/1.0 - RFC 1945) */ - public static final int SC_UNAUTHORIZED = 401; - /** {@code 402 Payment Required} (HTTP/1.1 - RFC 2616) */ - public static final int SC_PAYMENT_REQUIRED = 402; - /** {@code 403 Forbidden} (HTTP/1.0 - RFC 1945) */ - public static final int SC_FORBIDDEN = 403; - /** {@code 404 Not Found} (HTTP/1.0 - RFC 1945) */ - public static final int SC_NOT_FOUND = 404; - /** {@code 405 Method Not Allowed} (HTTP/1.1 - RFC 2616) */ - public static final int SC_METHOD_NOT_ALLOWED = 405; - /** {@code 406 Not Acceptable} (HTTP/1.1 - RFC 2616) */ - public static final int SC_NOT_ACCEPTABLE = 406; - /** {@code 407 Proxy Authentication Required} (HTTP/1.1 - RFC 2616)*/ - public static final int SC_PROXY_AUTHENTICATION_REQUIRED = 407; - /** {@code 408 Request Timeout} (HTTP/1.1 - RFC 2616) */ - public static final int SC_REQUEST_TIMEOUT = 408; - /** {@code 409 Conflict} (HTTP/1.1 - RFC 2616) */ - public static final int SC_CONFLICT = 409; - /** {@code 410 Gone} (HTTP/1.1 - RFC 2616) */ - public static final int SC_GONE = 410; - /** {@code 411 Length Required} (HTTP/1.1 - RFC 2616) */ - public static final int SC_LENGTH_REQUIRED = 411; - /** {@code 412 Precondition Failed} (HTTP/1.1 - RFC 2616) */ - public static final int SC_PRECONDITION_FAILED = 412; - /** {@code 413 Request Entity Too Large} (HTTP/1.1 - RFC 2616) */ - public static final int SC_REQUEST_TOO_LONG = 413; - /** {@code 414 Request-URI Too Long} (HTTP/1.1 - RFC 2616) */ - public static final int SC_REQUEST_URI_TOO_LONG = 414; - /** {@code 415 Unsupported Media Type} (HTTP/1.1 - RFC 2616) */ - public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415; - /** {@code 416 Requested Range Not Satisfiable} (HTTP/1.1 - RFC 2616) */ - public static final int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416; - /** {@code 417 Expectation Failed} (HTTP/1.1 - RFC 2616) */ - public static final int SC_EXPECTATION_FAILED = 417; - - /** - * Static constant for a 418 error. - * {@code 418 Unprocessable Entity} (WebDAV drafts?) - * or {@code 418 Reauthentication Required} (HTTP/1.1 drafts?) - */ - // not used - // public static final int SC_UNPROCESSABLE_ENTITY = 418; - - /** - * Static constant for a 419 error. - * {@code 419 Insufficient Space on Resource} - * (WebDAV - draft-ietf-webdav-protocol-05?) - * or {@code 419 Proxy Reauthentication Required} - * (HTTP/1.1 drafts?) - */ - public static final int SC_INSUFFICIENT_SPACE_ON_RESOURCE = 419; - /** - * Static constant for a 420 error. - * {@code 420 Method Failure} - * (WebDAV - draft-ietf-webdav-protocol-05?) - */ - public static final int SC_METHOD_FAILURE = 420; - /** {@code 422 Unprocessable Entity} (WebDAV - RFC 2518) */ - public static final int SC_UNPROCESSABLE_ENTITY = 422; - /** {@code 423 Locked} (WebDAV - RFC 2518) */ - public static final int SC_LOCKED = 423; - /** {@code 424 Failed Dependency} (WebDAV - RFC 2518) */ - public static final int SC_FAILED_DEPENDENCY = 424; - - // --- 5xx Server Error --- - - /** {@code 500 Server Error} (HTTP/1.0 - RFC 1945) */ - public static final int SC_INTERNAL_SERVER_ERROR = 500; - /** {@code 501 Not Implemented} (HTTP/1.0 - RFC 1945) */ - public static final int SC_NOT_IMPLEMENTED = 501; - /** {@code 502 Bad Gateway} (HTTP/1.0 - RFC 1945) */ - public static final int SC_BAD_GATEWAY = 502; - /** {@code 503 Service Unavailable} (HTTP/1.0 - RFC 1945) */ - public static final int SC_SERVICE_UNAVAILABLE = 503; - /** {@code 504 Gateway Timeout} (HTTP/1.1 - RFC 2616) */ - public static final int SC_GATEWAY_TIMEOUT = 504; - /** {@code 505 HTTP Version Not Supported} (HTTP/1.1 - RFC 2616) */ - public static final int SC_HTTP_VERSION_NOT_SUPPORTED = 505; - - /** {@code 507 Insufficient Storage} (WebDAV - RFC 2518) */ - public static final int SC_INSUFFICIENT_STORAGE = 507; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpVersion.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpVersion.java deleted file mode 100644 index 1fd5849d..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/HttpVersion.java +++ /dev/null @@ -1,110 +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 com.tracelytics.ext.apache.http; - -import java.io.Serializable; - -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * Represents an HTTP version. HTTP uses a "major.minor" numbering - * scheme to indicate versions of the protocol. - *

- * The version of an HTTP message is indicated by an HTTP-Version field - * in the first line of the message. - *

- *
- *     HTTP-Version   = "HTTP" "/" 1*DIGIT "." 1*DIGIT
- * 
- * - * @since 4.0 - */ -@Immutable -public final class HttpVersion extends ProtocolVersion - implements Serializable { - - private static final long serialVersionUID = -5856653513894415344L; - - /** The protocol name. */ - public static final String HTTP = "HTTP"; - - /** HTTP protocol version 0.9 */ - public static final HttpVersion HTTP_0_9 = new HttpVersion(0, 9); - - /** HTTP protocol version 1.0 */ - public static final HttpVersion HTTP_1_0 = new HttpVersion(1, 0); - - /** HTTP protocol version 1.1 */ - public static final HttpVersion HTTP_1_1 = new HttpVersion(1, 1); - - - /** - * Create an HTTP protocol version designator. - * - * @param major the major version number of the HTTP protocol - * @param minor the minor version number of the HTTP protocol - * - * @throws IllegalArgumentException if either major or minor version number is negative - */ - public HttpVersion(final int major, final int minor) { - super(HTTP, major, minor); - } - - - /** - * Obtains a specific HTTP version. - * - * @param major the major version - * @param minor the minor version - * - * @return an instance of {@link HttpVersion} with the argument version - */ - @Override - public ProtocolVersion forVersion(final int major, final int minor) { - - if ((major == this.major) && (minor == this.minor)) { - return this; - } - - if (major == 1) { - if (minor == 0) { - return HTTP_1_0; - } - if (minor == 1) { - return HTTP_1_1; - } - } - if ((major == 0) && (minor == 9)) { - return HTTP_0_9; - } - - // argument checking is done in the constructor - return new HttpVersion(major, minor); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/MalformedChunkCodingException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/MalformedChunkCodingException.java deleted file mode 100644 index 1cffd688..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/MalformedChunkCodingException.java +++ /dev/null @@ -1,57 +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 com.tracelytics.ext.apache.http; - -import java.io.IOException; - -/** - * Signals a malformed chunked stream. - * - * @since 4.0 - */ -public class MalformedChunkCodingException extends IOException { - - private static final long serialVersionUID = 2158560246948994524L; - - /** - * Creates a MalformedChunkCodingException without a detail message. - */ - public MalformedChunkCodingException() { - super(); - } - - /** - * Creates a MalformedChunkCodingException with the specified detail message. - * - * @param message The exception detail message - */ - public MalformedChunkCodingException(final String message) { - super(message); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/MessageConstraintException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/MessageConstraintException.java deleted file mode 100644 index 98555d4d..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/MessageConstraintException.java +++ /dev/null @@ -1,57 +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 com.tracelytics.ext.apache.http; - -import java.nio.charset.CharacterCodingException; - -/** - * Signals a message constraint violation. - * - * @since 4.3 - */ -public class MessageConstraintException extends CharacterCodingException { - - private static final long serialVersionUID = 6077207720446368695L; - - private final String message; - /** - * Creates a TruncatedChunkException with the specified detail message. - * - * @param message The exception detail message - */ - public MessageConstraintException(final String message) { - super(); - this.message = message; - } - - @Override - public String getMessage() { - return this.message; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/MethodNotSupportedException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/MethodNotSupportedException.java deleted file mode 100644 index dd081579..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/MethodNotSupportedException.java +++ /dev/null @@ -1,59 +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 com.tracelytics.ext.apache.http; - - -/** - * Signals that an HTTP method is not supported. - * - * @since 4.0 - */ -public class MethodNotSupportedException extends HttpException { - - private static final long serialVersionUID = 3365359036840171201L; - - /** - * Creates a new MethodNotSupportedException with the specified detail message. - * - * @param message The exception detail message - */ - public MethodNotSupportedException(final String message) { - super(message); - } - - /** - * Creates a new MethodNotSupportedException with the specified detail message and cause. - * - * @param message the exception detail message - * @param cause the {@code Throwable} that caused this exception, or {@code null} - * if the cause is unavailable, unknown, or not a {@code Throwable} - */ - public MethodNotSupportedException(final String message, final Throwable cause) { - super(message, cause); - } -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/NameValuePair.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/NameValuePair.java deleted file mode 100644 index e9319887..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/NameValuePair.java +++ /dev/null @@ -1,47 +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 com.tracelytics.ext.apache.http; - -/** - * A name / value pair parameter used as an element of HTTP messages. - *
- * parameter               = attribute "=" value
- * attribute               = token
- * value                   = token | quoted-string
- * 
- * - * - * @since 4.0 - */ -public interface NameValuePair { - - String getName(); - - String getValue(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/NoHttpResponseException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/NoHttpResponseException.java deleted file mode 100644 index 84ab6f94..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/NoHttpResponseException.java +++ /dev/null @@ -1,50 +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 com.tracelytics.ext.apache.http; - -import java.io.IOException; - -/** - * Signals that the target server failed to respond with a valid HTTP response. - * - * @since 4.0 - */ -public class NoHttpResponseException extends IOException { - - private static final long serialVersionUID = -7658940387386078766L; - - /** - * Creates a new NoHttpResponseException with the specified detail message. - * - * @param message exception message - */ - public NoHttpResponseException(final String message) { - super(message); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ParseException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/ParseException.java deleted file mode 100644 index 1662811b..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ParseException.java +++ /dev/null @@ -1,61 +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 com.tracelytics.ext.apache.http; - -/** - * Signals a parse error. - * Parse errors when receiving a message will typically trigger - * {@link ProtocolException}. Parse errors that do not occur during - * protocol execution may be handled differently. - * This is an unchecked exception, since there are cases where - * the data to be parsed has been generated and is therefore - * known to be parseable. - * - * @since 4.0 - */ -public class ParseException extends RuntimeException { - - private static final long serialVersionUID = -7288819855864183578L; - - /** - * Creates a {@link ParseException} without details. - */ - public ParseException() { - super(); - } - - /** - * Creates a {@link ParseException} with a detail message. - * - * @param message the exception detail message, or {@code null} - */ - public ParseException(final String message) { - super(message); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ProtocolException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/ProtocolException.java deleted file mode 100644 index 9f7d6841..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ProtocolException.java +++ /dev/null @@ -1,67 +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 com.tracelytics.ext.apache.http; - -/** - * Signals that an HTTP protocol violation has occurred. - * For example a malformed status line or headers, a missing message body, etc. - * - * - * @since 4.0 - */ -public class ProtocolException extends HttpException { - - private static final long serialVersionUID = -2143571074341228994L; - - /** - * Creates a new ProtocolException with a {@code null} detail message. - */ - public ProtocolException() { - super(); - } - - /** - * Creates a new ProtocolException with the specified detail message. - * - * @param message The exception detail message - */ - public ProtocolException(final String message) { - super(message); - } - - /** - * Creates a new ProtocolException with the specified detail message and cause. - * - * @param message the exception detail message - * @param cause the {@code Throwable} that caused this exception, or {@code null} - * if the cause is unavailable, unknown, or not a {@code Throwable} - */ - public ProtocolException(final String message, final Throwable cause) { - super(message, cause); - } -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ProtocolVersion.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/ProtocolVersion.java deleted file mode 100644 index 676a9ac1..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ProtocolVersion.java +++ /dev/null @@ -1,265 +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 com.tracelytics.ext.apache.http; - -import java.io.Serializable; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Represents a protocol version. The "major.minor" numbering - * scheme is used to indicate versions of the protocol. - *

- * This class defines a protocol version as a combination of - * protocol name, major version number, and minor version number. - * Note that {@link #equals} and {@link #hashCode} are defined as - * final here, they cannot be overridden in derived classes. - *

- * - * @since 4.0 - */ -@Immutable -public class ProtocolVersion implements Serializable, Cloneable { - - private static final long serialVersionUID = 8950662842175091068L; - - - /** Name of the protocol. */ - protected final String protocol; - - /** Major version number of the protocol */ - protected final int major; - - /** Minor version number of the protocol */ - protected final int minor; - - - /** - * Create a protocol version designator. - * - * @param protocol the name of the protocol, for example "HTTP" - * @param major the major version number of the protocol - * @param minor the minor version number of the protocol - */ - public ProtocolVersion(final String protocol, final int major, final int minor) { - this.protocol = Args.notNull(protocol, "Protocol name"); - this.major = Args.notNegative(major, "Protocol minor version"); - this.minor = Args.notNegative(minor, "Protocol minor version"); - } - - /** - * Returns the name of the protocol. - * - * @return the protocol name - */ - public final String getProtocol() { - return protocol; - } - - /** - * Returns the major version number of the protocol. - * - * @return the major version number. - */ - public final int getMajor() { - return major; - } - - /** - * Returns the minor version number of the HTTP protocol. - * - * @return the minor version number. - */ - public final int getMinor() { - return minor; - } - - - /** - * Obtains a specific version of this protocol. - * This can be used by derived classes to instantiate themselves instead - * of the base class, and to define constants for commonly used versions. - *

- * The default implementation in this class returns {@code this} - * if the version matches, and creates a new {@link ProtocolVersion} - * otherwise. - *

- * - * @param major the major version - * @param minor the minor version - * - * @return a protocol version with the same protocol name - * and the argument version - */ - public ProtocolVersion forVersion(final int major, final int minor) { - - if ((major == this.major) && (minor == this.minor)) { - return this; - } - - // argument checking is done in the constructor - return new ProtocolVersion(this.protocol, major, minor); - } - - - /** - * Obtains a hash code consistent with {@link #equals}. - * - * @return the hashcode of this protocol version - */ - @Override - public final int hashCode() { - return this.protocol.hashCode() ^ (this.major * 100000) ^ this.minor; - } - - - /** - * Checks equality of this protocol version with an object. - * The object is equal if it is a protocl version with the same - * protocol name, major version number, and minor version number. - * The specific class of the object is not relevant, - * instances of derived classes with identical attributes are - * equal to instances of the base class and vice versa. - * - * @param obj the object to compare with - * - * @return {@code true} if the argument is the same protocol version, - * {@code false} otherwise - */ - @Override - public final boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof ProtocolVersion)) { - return false; - } - final ProtocolVersion that = (ProtocolVersion) obj; - - return ((this.protocol.equals(that.protocol)) && - (this.major == that.major) && - (this.minor == that.minor)); - } - - - /** - * Checks whether this protocol can be compared to another one. - * Only protocol versions with the same protocol name can be - * {@link #compareToVersion compared}. - * - * @param that the protocol version to consider - * - * @return {@code true} if {@link #compareToVersion compareToVersion} - * can be called with the argument, {@code false} otherwise - */ - public boolean isComparable(final ProtocolVersion that) { - return (that != null) && this.protocol.equals(that.protocol); - } - - - /** - * Compares this protocol version with another one. - * Only protocol versions with the same protocol name can be compared. - * This method does not define a total ordering, as it would be - * required for {@link java.lang.Comparable}. - * - * @param that the protocol version to compare with - * - * @return a negative integer, zero, or a positive integer - * as this version is less than, equal to, or greater than - * the argument version. - * - * @throws IllegalArgumentException - * if the argument has a different protocol name than this object, - * or if the argument is {@code null} - */ - public int compareToVersion(final ProtocolVersion that) { - Args.notNull(that, "Protocol version"); - Args.check(this.protocol.equals(that.protocol), - "Versions for different protocols cannot be compared: %s %s", this, that); - int delta = getMajor() - that.getMajor(); - if (delta == 0) { - delta = getMinor() - that.getMinor(); - } - return delta; - } - - - /** - * Tests if this protocol version is greater or equal to the given one. - * - * @param version the version against which to check this version - * - * @return {@code true} if this protocol version is - * {@link #isComparable comparable} to the argument - * and {@link #compareToVersion compares} as greater or equal, - * {@code false} otherwise - */ - public final boolean greaterEquals(final ProtocolVersion version) { - return isComparable(version) && (compareToVersion(version) >= 0); - } - - - /** - * Tests if this protocol version is less or equal to the given one. - * - * @param version the version against which to check this version - * - * @return {@code true} if this protocol version is - * {@link #isComparable comparable} to the argument - * and {@link #compareToVersion compares} as less or equal, - * {@code false} otherwise - */ - public final boolean lessEquals(final ProtocolVersion version) { - return isComparable(version) && (compareToVersion(version) <= 0); - } - - - /** - * Converts this protocol version to a string. - * - * @return a protocol version string, like "HTTP/1.1" - */ - @Override - public String toString() { - final StringBuilder buffer = new StringBuilder(); - buffer.append(this.protocol); - buffer.append('/'); - buffer.append(Integer.toString(this.major)); - buffer.append('.'); - buffer.append(Integer.toString(this.minor)); - return buffer.toString(); - } - - @Override - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ReasonPhraseCatalog.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/ReasonPhraseCatalog.java deleted file mode 100644 index 72fc625a..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ReasonPhraseCatalog.java +++ /dev/null @@ -1,51 +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 com.tracelytics.ext.apache.http; - -import java.util.Locale; - -/** - * Interface for obtaining reason phrases for HTTP status codes. - * - * @since 4.0 - */ -public interface ReasonPhraseCatalog { - - /** - * Obtains the reason phrase for a status code. - * The optional context allows for catalogs that detect - * the language for the reason phrase. - * - * @param status the status code, in the range 100-599 - * @param loc the preferred locale for the reason phrase - * - * @return the reason phrase, or {@code null} if unknown - */ - String getReason(int status, Locale loc); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/RequestLine.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/RequestLine.java deleted file mode 100644 index 86598163..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/RequestLine.java +++ /dev/null @@ -1,49 +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 com.tracelytics.ext.apache.http; - -/** - * The Request-Line begins with a method token, followed by the - * Request-URI and the protocol version, and ending with CRLF. The - * elements are separated by SP characters. No CR or LF is allowed - * except in the final CRLF sequence. - *
- *      Request-Line   = Method SP Request-URI SP HTTP-Version CRLF
- * 
- * - * @since 4.0 - */ -public interface RequestLine { - - String getMethod(); - - ProtocolVersion getProtocolVersion(); - - String getUri(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/StatusLine.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/StatusLine.java deleted file mode 100644 index 6c73913b..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/StatusLine.java +++ /dev/null @@ -1,52 +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 com.tracelytics.ext.apache.http; - -/** - * The first line of a Response message is the Status-Line, consisting - * of the protocol version followed by a numeric status code and its - * associated textual phrase, with each element separated by SP - * characters. No CR or LF is allowed except in the final CRLF sequence. - *
- *     Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
- * 
- * - * @see HttpStatus - * @version $Id$ - * - * @since 4.0 - */ -public interface StatusLine { - - ProtocolVersion getProtocolVersion(); - - int getStatusCode(); - - String getReasonPhrase(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/TokenIterator.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/TokenIterator.java deleted file mode 100644 index be43f576..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/TokenIterator.java +++ /dev/null @@ -1,60 +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 com.tracelytics.ext.apache.http; - -import java.util.Iterator; - -/** - * An iterator for {@link String} tokens. - * This interface is designed as a complement to - * {@link HeaderElementIterator}, in cases where the items - * are plain strings rather than full header elements. - * - * @since 4.0 - */ -public interface TokenIterator extends Iterator { - - /** - * Indicates whether there is another token in this iteration. - * - * @return {@code true} if there is another token, - * {@code false} otherwise - */ - @Override - boolean hasNext(); - - /** - * Obtains the next token from this iteration. - * This method should only be called while {@link #hasNext hasNext} - * is true. - * - * @return the next token in this iteration - */ - String nextToken(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/TruncatedChunkException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/TruncatedChunkException.java deleted file mode 100644 index 54c7578c..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/TruncatedChunkException.java +++ /dev/null @@ -1,48 +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 com.tracelytics.ext.apache.http; - -/** - * Signals a truncated chunk in a chunked stream. - * - * @since 4.1 - */ -public class TruncatedChunkException extends MalformedChunkCodingException { - - private static final long serialVersionUID = -23506263930279460L; - - /** - * Creates a TruncatedChunkException with the specified detail message. - * - * @param message The exception detail message - */ - public TruncatedChunkException(final String message) { - super(message); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/UnsupportedHttpVersionException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/UnsupportedHttpVersionException.java deleted file mode 100644 index 2ee04076..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/UnsupportedHttpVersionException.java +++ /dev/null @@ -1,57 +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 com.tracelytics.ext.apache.http; - - -/** - * Signals an unsupported version of the HTTP protocol. - * - * @since 4.0 - */ -public class UnsupportedHttpVersionException extends ProtocolException { - - private static final long serialVersionUID = -1348448090193107031L; - - - /** - * Creates an exception without a detail message. - */ - public UnsupportedHttpVersionException() { - super(); - } - - /** - * Creates an exception with the specified detail message. - * - * @param message The exception detail message - */ - public UnsupportedHttpVersionException(final String message) { - super(message); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/annotation/Experimental.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/annotation/Experimental.java deleted file mode 100644 index 1e42fd7e..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/annotation/Experimental.java +++ /dev/null @@ -1,42 +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 com.tracelytics.ext.apache.http.annotation; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * The field or method to which this annotation is applied is marked as experimental. - */ -@Documented -@Target({ElementType.METHOD, ElementType.TYPE}) -@Retention(RetentionPolicy.CLASS) -public @interface Experimental { -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/annotation/GuardedBy.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/annotation/GuardedBy.java deleted file mode 100644 index ddc20679..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/annotation/GuardedBy.java +++ /dev/null @@ -1,80 +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 com.tracelytics.ext.apache.http.annotation; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * The field or method to which this annotation is applied can only be accessed - * when holding a particular lock, which may be a built-in (synchronization) lock, - * or may be an explicit java.util.concurrent.Lock. - * - *

- * The argument determines which lock guards the annotated field or method: - *

- *
    - *
  • - * {@code this} : The intrinsic lock of the object in whose class the field is defined. - *
  • - *
  • - * {@code class-name.this} : For inner classes, it may be necessary to disambiguate 'this'; - * the class-name.this designation allows you to specify which 'this' reference is intended - *
  • - *
  • - * {@code itself} : For reference fields only; the object to which the field refers. - *
  • - *
  • - * {@code field-name} : The lock object is referenced by the (instance or static) field - * specified by field-name. - *
  • - *
  • - * {@code class-name.field-name} : The lock object is reference by the static field specified - * by class-name.field-name. - *
  • - *
  • - * {@code method-name()} : The lock object is returned by calling the named nil-ary method. - *
  • - *
  • - * {@code class-name.class} : The Class object for the specified class should be used as the lock object. - *
  • - *
- *

- * Based on code developed by Brian Goetz and Tim Peierls and concepts - * published in 'Java Concurrency in Practice' by Brian Goetz, Tim Peierls, - * Joshua Bloch, Joseph Bowbeer, David Holmes and Doug Lea. - *

- */ -@Documented -@Target({ElementType.FIELD, ElementType.METHOD}) -@Retention(RetentionPolicy.CLASS) // The original version used RUNTIME -public @interface GuardedBy { - String value(); -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/annotation/Immutable.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/annotation/Immutable.java deleted file mode 100644 index 4f7a9e09..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/annotation/Immutable.java +++ /dev/null @@ -1,59 +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 com.tracelytics.ext.apache.http.annotation; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * The class to which this annotation is applied is immutable. This means that - * its state cannot be seen to change by callers, which implies that - *
    - *
  • all public fields are final,
  • - *
  • all public final reference fields refer to other immutable objects, and
  • - *
  • constructors and methods do not publish references to any internal state - * which is potentially mutable by the implementation.
  • - *
- * Immutable objects may still have internal mutable state for purposes of performance - * optimization; some state variables may be lazily computed, so long as they are computed - * from immutable state and that callers cannot tell the difference. - *

- * Immutable objects are inherently thread-safe; they may be passed between threads or - * published without synchronization. - *

- * Based on code developed by Brian Goetz and Tim Peierls and concepts - * published in 'Java Concurrency in Practice' by Brian Goetz, Tim Peierls, - * Joshua Bloch, Joseph Bowbeer, David Holmes and Doug Lea. - */ -@Documented -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.CLASS) // The original version used RUNTIME -public @interface Immutable { -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/annotation/NotThreadSafe.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/annotation/NotThreadSafe.java deleted file mode 100644 index 880b1e8c..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/annotation/NotThreadSafe.java +++ /dev/null @@ -1,50 +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 com.tracelytics.ext.apache.http.annotation; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * The class to which this annotation is applied is not thread-safe. - * This annotation primarily exists for clarifying the non-thread-safety of a class - * that might otherwise be assumed to be thread-safe, despite the fact that it is a bad - * idea to assume a class is thread-safe without good reason. - * @see ThreadSafe - *

- * Based on code developed by Brian Goetz and Tim Peierls and concepts - * published in 'Java Concurrency in Practice' by Brian Goetz, Tim Peierls, - * Joshua Bloch, Joseph Bowbeer, David Holmes and Doug Lea. - */ -@Documented -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.CLASS) // The original version used RUNTIME -public @interface NotThreadSafe { -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/annotation/Obsolete.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/annotation/Obsolete.java deleted file mode 100644 index 556fcd34..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/annotation/Obsolete.java +++ /dev/null @@ -1,43 +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 com.tracelytics.ext.apache.http.annotation; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * The field or method to which this annotation is applied is marked as implementing - * requirements of the HTTP protocol or a related protocol that are now obsolete. - */ -@Documented -@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE}) -@Retention(RetentionPolicy.CLASS) -public @interface Obsolete { -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/annotation/ThreadSafe.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/annotation/ThreadSafe.java deleted file mode 100644 index 466b8f24..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/annotation/ThreadSafe.java +++ /dev/null @@ -1,51 +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 com.tracelytics.ext.apache.http.annotation; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * The class to which this annotation is applied is thread-safe. This means that - * no sequences of accesses (reads and writes to public fields, calls to public methods) - * may put the object into an invalid state, regardless of the interleaving of those actions - * by the runtime, and without requiring any additional synchronization or coordination on the - * part of the caller. - * @see NotThreadSafe - *

- * Based on code developed by Brian Goetz and Tim Peierls and concepts - * published in 'Java Concurrency in Practice' by Brian Goetz, Tim Peierls, - * Joshua Bloch, Joseph Bowbeer, David Holmes and Doug Lea. - */ -@Documented -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.CLASS) // The original version used RUNTIME -public @interface ThreadSafe { -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/annotation/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/annotation/package-info.java deleted file mode 100644 index f82949a0..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/annotation/package-info.java +++ /dev/null @@ -1,35 +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 - * . - * - */ - -/** - * Thread-safety annotations based on JCIP-ANNOTATIONS - *

- * Copyright (c) 2005 Brian Goetz and Tim Peierls. - * See http://www.jcip.net - *

- */ -package com.tracelytics.ext.apache.http.annotation; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AUTH.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AUTH.java deleted file mode 100644 index 5bbe465a..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AUTH.java +++ /dev/null @@ -1,64 +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 com.tracelytics.ext.apache.http.auth; - -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * Constants and static helpers related to the HTTP authentication. - * - * - * @since 4.0 - */ -@Immutable -public final class AUTH { - - /** - * The www authenticate challange header. - */ - public static final String WWW_AUTH = "WWW-Authenticate"; - - /** - * The www authenticate response header. - */ - public static final String WWW_AUTH_RESP = "Authorization"; - - /** - * The proxy authenticate challange header. - */ - public static final String PROXY_AUTH = "Proxy-Authenticate"; - - /** - * The proxy authenticate response header. - */ - public static final String PROXY_AUTH_RESP = "Proxy-Authorization"; - - private AUTH() { - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthOption.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthOption.java deleted file mode 100644 index d3afa0ec..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthOption.java +++ /dev/null @@ -1,63 +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 com.tracelytics.ext.apache.http.auth; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * @since 4.2 - */ -@Immutable -public final class AuthOption { - - private final AuthScheme authScheme; - private final Credentials creds; - - public AuthOption(final AuthScheme authScheme, final Credentials creds) { - super(); - Args.notNull(authScheme, "Auth scheme"); - Args.notNull(creds, "User credentials"); - this.authScheme = authScheme; - this.creds = creds; - } - - public AuthScheme getAuthScheme() { - return this.authScheme; - } - - public Credentials getCredentials() { - return this.creds; - } - - @Override - public String toString() { - return this.authScheme.toString(); - } - -} - diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthProtocolState.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthProtocolState.java deleted file mode 100644 index dda55351..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthProtocolState.java +++ /dev/null @@ -1,33 +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 com.tracelytics.ext.apache.http.auth; - -public enum AuthProtocolState { - - UNCHALLENGED, CHALLENGED, HANDSHAKE, FAILURE, SUCCESS - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthScheme.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthScheme.java deleted file mode 100644 index 6232a579..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthScheme.java +++ /dev/null @@ -1,130 +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 com.tracelytics.ext.apache.http.auth; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpRequest; - -/** - * This interface represents an abstract challenge-response oriented - * authentication scheme. - *

- * An authentication scheme should be able to support the following - * functions: - *

    - *
  • Parse and process the challenge sent by the target server - * in response to request for a protected resource - *
  • Provide its textual designation - *
  • Provide its parameters, if available - *
  • Provide the realm this authentication scheme is applicable to, - * if available - *
  • Generate authorization string for the given set of credentials - * and the HTTP request in response to the authorization challenge. - *
- *

- * Authentication schemes may be stateful involving a series of - * challenge-response exchanges. - *

- * IMPORTANT: implementations of this interface MUST also implement {@link ContextAwareAuthScheme} - * interface in order to remain API compatible with newer versions of HttpClient. - * - * @since 4.0 - */ - -public interface AuthScheme { - - /** - * Processes the given challenge token. Some authentication schemes - * may involve multiple challenge-response exchanges. Such schemes must be able - * to maintain the state information when dealing with sequential challenges - * - * @param header the challenge header - */ - void processChallenge(final Header header) throws MalformedChallengeException; - - /** - * Returns textual designation of the given authentication scheme. - * - * @return the name of the given authentication scheme - */ - String getSchemeName(); - - /** - * Returns authentication parameter with the given name, if available. - * - * @param name The name of the parameter to be returned - * - * @return the parameter with the given name - */ - String getParameter(final String name); - - /** - * Returns authentication realm. If the concept of an authentication - * realm is not applicable to the given authentication scheme, returns - * {@code null}. - * - * @return the authentication realm - */ - String getRealm(); - - /** - * Tests if the authentication scheme is provides authorization on a per - * connection basis instead of usual per request basis - * - * @return {@code true} if the scheme is connection based, {@code false} - * if the scheme is request based. - */ - boolean isConnectionBased(); - - /** - * Authentication process may involve a series of challenge-response exchanges. - * This method tests if the authorization process has been completed, either - * successfully or unsuccessfully, that is, all the required authorization - * challenges have been processed in their entirety. - * - * @return {@code true} if the authentication process has been completed, - * {@code false} otherwise. - */ - boolean isComplete(); - - /** - * Produces an authorization string for the given set of {@link Credentials}. - * - * @param credentials The set of credentials to be used for athentication - * @param request The request being authenticated - * @throws AuthenticationException if authorization string cannot - * be generated due to an authentication failure - * - * @return the authorization string - * - * @deprecated (4.1) Use {@link ContextAwareAuthScheme#authenticate(Credentials, HttpRequest, com.tracelytics.ext.apache.http.protocol.HttpContext)} - */ - @Deprecated - Header authenticate(Credentials credentials, HttpRequest request) - throws AuthenticationException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthSchemeFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthSchemeFactory.java deleted file mode 100644 index 5735a764..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthSchemeFactory.java +++ /dev/null @@ -1,51 +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 com.tracelytics.ext.apache.http.auth; - -import com.tracelytics.ext.apache.http.params.HttpParams; - -/** - * Factory for {@link AuthScheme} implementations. - * - * @since 4.0 - * - * @deprecated (4.3) use {@link AuthSchemeProvider} - */ -@Deprecated -public interface AuthSchemeFactory { - - /** - * Creates an instance of {@link AuthScheme} using given HTTP parameters. - * - * @param params HTTP parameters. - * - * @return auth scheme. - */ - AuthScheme newInstance(HttpParams params); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthSchemeProvider.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthSchemeProvider.java deleted file mode 100644 index ff974f10..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthSchemeProvider.java +++ /dev/null @@ -1,46 +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 com.tracelytics.ext.apache.http.auth; - -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -/** - * Factory for {@link AuthScheme} implementations. - * - * @since 4.3 - */ -public interface AuthSchemeProvider { - - /** - * Creates an instance of {@link AuthScheme}. - * - * @return auth scheme. - */ - AuthScheme create(HttpContext context); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthSchemeRegistry.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthSchemeRegistry.java deleted file mode 100644 index 905d9fac..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthSchemeRegistry.java +++ /dev/null @@ -1,157 +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 com.tracelytics.ext.apache.http.auth; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.config.Lookup; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.protocol.ExecutionContext; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Authentication scheme registry that can be used to obtain the corresponding - * authentication scheme implementation for a given type of authorization challenge. - * - * @since 4.0 - * - * @deprecated (4.3) use {@link com.tracelytics.ext.apache.http.config.Registry} - */ -@ThreadSafe -@Deprecated -public final class AuthSchemeRegistry implements Lookup { - - private final ConcurrentHashMap registeredSchemes; - - public AuthSchemeRegistry() { - super(); - this.registeredSchemes = new ConcurrentHashMap(); - } - - /** - * Registers a {@link AuthSchemeFactory} with the given identifier. If a factory with the - * given name already exists it will be overridden. This name is the same one used to - * retrieve the {@link AuthScheme authentication scheme} from {@link #getAuthScheme}. - * - *

- * Please note that custom authentication preferences, if used, need to be updated accordingly - * for the new {@link AuthScheme authentication scheme} to take effect. - *

- * - * @param name the identifier for this scheme - * @param factory the {@link AuthSchemeFactory} class to register - * - * @see #getAuthScheme - */ - public void register( - final String name, - final AuthSchemeFactory factory) { - Args.notNull(name, "Name"); - Args.notNull(factory, "Authentication scheme factory"); - registeredSchemes.put(name.toLowerCase(Locale.ENGLISH), factory); - } - - /** - * Unregisters the class implementing an {@link AuthScheme authentication scheme} with - * the given name. - * - * @param name the identifier of the class to unregister - */ - public void unregister(final String name) { - Args.notNull(name, "Name"); - registeredSchemes.remove(name.toLowerCase(Locale.ENGLISH)); - } - - /** - * Gets the {@link AuthScheme authentication scheme} with the given name. - * - * @param name the {@link AuthScheme authentication scheme} identifier - * @param params the {@link HttpParams HTTP parameters} for the authentication - * scheme. - * - * @return {@link AuthScheme authentication scheme} - * - * @throws IllegalStateException if a scheme with the given name cannot be found - */ - public AuthScheme getAuthScheme(final String name, final HttpParams params) - throws IllegalStateException { - - Args.notNull(name, "Name"); - final AuthSchemeFactory factory = registeredSchemes.get(name.toLowerCase(Locale.ENGLISH)); - if (factory != null) { - return factory.newInstance(params); - } else { - throw new IllegalStateException("Unsupported authentication scheme: " + name); - } - } - - /** - * Obtains a list containing the names of all registered {@link AuthScheme authentication - * schemes} - * - * @return list of registered scheme names - */ - public List getSchemeNames() { - return new ArrayList(registeredSchemes.keySet()); - } - - /** - * Populates the internal collection of registered {@link AuthScheme authentication schemes} - * with the content of the map passed as a parameter. - * - * @param map authentication schemes - */ - public void setItems(final Map map) { - if (map == null) { - return; - } - registeredSchemes.clear(); - registeredSchemes.putAll(map); - } - - @Override - public AuthSchemeProvider lookup(final String name) { - return new AuthSchemeProvider() { - - @Override - public AuthScheme create(final HttpContext context) { - final HttpRequest request = (HttpRequest) context.getAttribute( - ExecutionContext.HTTP_REQUEST); - return getAuthScheme(name, request.getParams()); - } - - }; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthScope.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthScope.java deleted file mode 100644 index 1750c5f9..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthScope.java +++ /dev/null @@ -1,328 +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 com.tracelytics.ext.apache.http.auth; - -import java.util.Locale; - -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.LangUtils; - -/** - * {@code AuthScope} represents an authentication scope consisting of a host name, - * a port number, a realm name and an authentication scheme name. - *

- * This class can also optionally contain a host of origin, if created in response - * to authentication challenge from a specific host. - *

- * @since 4.0 - */ -@Immutable -public class AuthScope { - - /** - * The {@code null} value represents any host. In the future versions of - * HttpClient the use of this parameter will be discontinued. - */ - public static final String ANY_HOST = null; - - /** - * The {@code -1} value represents any port. - */ - public static final int ANY_PORT = -1; - - /** - * The {@code null} value represents any realm. - */ - public static final String ANY_REALM = null; - - /** - * The {@code null} value represents any authentication scheme. - */ - public static final String ANY_SCHEME = null; - - /** - * Default scope matching any host, port, realm and authentication scheme. - * In the future versions of HttpClient the use of this parameter will be - * discontinued. - */ - public static final AuthScope ANY = new AuthScope(ANY_HOST, ANY_PORT, ANY_REALM, ANY_SCHEME); - - /** The authentication scheme the credentials apply to. */ - private final String scheme; - - /** The realm the credentials apply to. */ - private final String realm; - - /** The host the credentials apply to. */ - private final String host; - - /** The port the credentials apply to. */ - private final int port; - - /** The original host, if known */ - private final HttpHost origin; - - /** - * Defines auth scope with the given {@code host}, {@code port}, {@code realm}, and - * {@code schemeName}. - * - * @param host authentication host. May be {@link #ANY_HOST} if applies - * to any host. - * @param port authentication port. May be {@link #ANY_PORT} if applies - * to any port of the host. - * @param realm authentication realm. May be {@link #ANY_REALM} if applies - * to any realm on the host. - * @param schemeName authentication scheme. May be {@link #ANY_SCHEME} if applies - * to any scheme supported by the host. - */ - public AuthScope( - final String host, - final int port, - final String realm, - final String schemeName) { - this.host = host == null ? ANY_HOST: host.toLowerCase(Locale.ROOT); - this.port = port < 0 ? ANY_PORT : port; - this.realm = realm == null ? ANY_REALM : realm; - this.scheme = schemeName == null ? ANY_SCHEME : schemeName.toUpperCase(Locale.ROOT); - this.origin = null; - } - - /** - * Defines auth scope for a specific host of origin. - * - * @param origin host of origin - * @param realm authentication realm. May be {@link #ANY_REALM} if applies - * to any realm on the host. - * @param schemeName authentication scheme. May be {@link #ANY_SCHEME} if applies - * to any scheme supported by the host. - * - * @since 4.2 - */ - public AuthScope( - final HttpHost origin, - final String realm, - final String schemeName) { - Args.notNull(origin, "Host"); - this.host = origin.getHostName().toLowerCase(Locale.ROOT); - this.port = origin.getPort() < 0 ? ANY_PORT : origin.getPort(); - this.realm = realm == null ? ANY_REALM : realm; - this.scheme = schemeName == null ? ANY_SCHEME : schemeName.toUpperCase(Locale.ROOT); - this.origin = origin; - } - - /** - * Defines auth scope for a specific host of origin. - * - * @param origin host of origin - * - * @since 4.2 - */ - public AuthScope(final HttpHost origin) { - this(origin, ANY_REALM, ANY_SCHEME); - } - - /** - * Defines auth scope with the given {@code host}, {@code port} and {@code realm}. - * - * @param host authentication host. May be {@link #ANY_HOST} if applies - * to any host. - * @param port authentication port. May be {@link #ANY_PORT} if applies - * to any port of the host. - * @param realm authentication realm. May be {@link #ANY_REALM} if applies - * to any realm on the host. - */ - public AuthScope(final String host, final int port, final String realm) { - this(host, port, realm, ANY_SCHEME); - } - - /** - * Defines auth scope with the given {@code host} and {@code port}. - * - * @param host authentication host. May be {@link #ANY_HOST} if applies - * to any host. - * @param port authentication port. May be {@link #ANY_PORT} if applies - * to any port of the host. - */ - public AuthScope(final String host, final int port) { - this(host, port, ANY_REALM, ANY_SCHEME); - } - - /** - * Creates a copy of the given credentials scope. - */ - public AuthScope(final AuthScope authscope) { - super(); - Args.notNull(authscope, "Scope"); - this.host = authscope.getHost(); - this.port = authscope.getPort(); - this.realm = authscope.getRealm(); - this.scheme = authscope.getScheme(); - this.origin = authscope.getOrigin(); - } - - /** - * @return host of origin. If unknown returns @null, - * - * @since 4.4 - */ - public HttpHost getOrigin() { - return this.origin; - } - - /** - * @return the host - */ - public String getHost() { - return this.host; - } - - /** - * @return the port - */ - public int getPort() { - return this.port; - } - - /** - * @return the realm name - */ - public String getRealm() { - return this.realm; - } - - /** - * @return the scheme type - */ - public String getScheme() { - return this.scheme; - } - - /** - * Tests if the authentication scopes match. - * - * @return the match factor. Negative value signifies no match. - * Non-negative signifies a match. The greater the returned value - * the closer the match. - */ - public int match(final AuthScope that) { - int factor = 0; - if (LangUtils.equals(this.scheme, that.scheme)) { - factor += 1; - } else { - if (this.scheme != ANY_SCHEME && that.scheme != ANY_SCHEME) { - return -1; - } - } - if (LangUtils.equals(this.realm, that.realm)) { - factor += 2; - } else { - if (this.realm != ANY_REALM && that.realm != ANY_REALM) { - return -1; - } - } - if (this.port == that.port) { - factor += 4; - } else { - if (this.port != ANY_PORT && that.port != ANY_PORT) { - return -1; - } - } - if (LangUtils.equals(this.host, that.host)) { - factor += 8; - } else { - if (this.host != ANY_HOST && that.host != ANY_HOST) { - return -1; - } - } - return factor; - } - - /** - * @see java.lang.Object#equals(Object) - */ - @Override - public boolean equals(final Object o) { - if (o == null) { - return false; - } - if (o == this) { - return true; - } - if (!(o instanceof AuthScope)) { - return super.equals(o); - } - final AuthScope that = (AuthScope) o; - return - LangUtils.equals(this.host, that.host) - && this.port == that.port - && LangUtils.equals(this.realm, that.realm) - && LangUtils.equals(this.scheme, that.scheme); - } - - /** - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - final StringBuilder buffer = new StringBuilder(); - if (this.scheme != null) { - buffer.append(this.scheme.toUpperCase(Locale.ROOT)); - buffer.append(' '); - } - if (this.realm != null) { - buffer.append('\''); - buffer.append(this.realm); - buffer.append('\''); - } else { - buffer.append(""); - } - if (this.host != null) { - buffer.append('@'); - buffer.append(this.host); - if (this.port >= 0) { - buffer.append(':'); - buffer.append(this.port); - } - } - return buffer.toString(); - } - - /** - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - int hash = LangUtils.HASH_SEED; - hash = LangUtils.hashCode(hash, this.host); - hash = LangUtils.hashCode(hash, this.port); - hash = LangUtils.hashCode(hash, this.realm); - hash = LangUtils.hashCode(hash, this.scheme); - return hash; - } -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthState.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthState.java deleted file mode 100644 index a42fed1b..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthState.java +++ /dev/null @@ -1,235 +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 com.tracelytics.ext.apache.http.auth; - -import java.util.Queue; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * This class provides detailed information about the state of the authentication process. - * - * @since 4.0 - */ -@NotThreadSafe -public class AuthState { - - /** Actual state of authentication protocol */ - private AuthProtocolState state; - - /** Actual authentication scheme */ - private AuthScheme authScheme; - - /** Actual authentication scope */ - private AuthScope authScope; - - /** Credentials selected for authentication */ - private Credentials credentials; - - /** Available auth options */ - private Queue authOptions; - - public AuthState() { - super(); - this.state = AuthProtocolState.UNCHALLENGED; - } - - /** - * Resets the auth state. - * - * @since 4.2 - */ - public void reset() { - this.state = AuthProtocolState.UNCHALLENGED; - this.authOptions = null; - this.authScheme = null; - this.authScope = null; - this.credentials = null; - } - - /** - * @since 4.2 - */ - public AuthProtocolState getState() { - return this.state; - } - - /** - * @since 4.2 - */ - public void setState(final AuthProtocolState state) { - this.state = state != null ? state : AuthProtocolState.UNCHALLENGED; - } - - /** - * Returns actual {@link AuthScheme}. May be null. - */ - public AuthScheme getAuthScheme() { - return this.authScheme; - } - - /** - * Returns actual {@link Credentials}. May be null. - */ - public Credentials getCredentials() { - return this.credentials; - } - - /** - * Updates the auth state with {@link AuthScheme} and {@link Credentials}. - * - * @param authScheme auth scheme. May not be null. - * @param credentials user crednetials. May not be null. - * - * @since 4.2 - */ - public void update(final AuthScheme authScheme, final Credentials credentials) { - Args.notNull(authScheme, "Auth scheme"); - Args.notNull(credentials, "Credentials"); - this.authScheme = authScheme; - this.credentials = credentials; - this.authOptions = null; - } - - /** - * Returns available {@link AuthOption}s. May be null. - * - * @since 4.2 - */ - public Queue getAuthOptions() { - return this.authOptions; - } - - /** - * Returns {@code true} if {@link AuthOption}s are available, {@code false} - * otherwise. - * - * @since 4.2 - */ - public boolean hasAuthOptions() { - return this.authOptions != null && !this.authOptions.isEmpty(); - } - - /** - * Updates the auth state with a queue of {@link AuthOption}s. - * - * @param authOptions a queue of auth options. May not be null or empty. - * - * @since 4.2 - */ - public void update(final Queue authOptions) { - Args.notEmpty(authOptions, "Queue of auth options"); - this.authOptions = authOptions; - this.authScheme = null; - this.credentials = null; - } - - /** - * Invalidates the authentication state by resetting its parameters. - * - * @deprecated (4.2) use {@link #reset()} - */ - @Deprecated - public void invalidate() { - reset(); - } - - /** - * @deprecated (4.2) do not use - */ - @Deprecated - public boolean isValid() { - return this.authScheme != null; - } - - /** - * Assigns the given {@link AuthScheme authentication scheme}. - * - * @param authScheme the {@link AuthScheme authentication scheme} - * - * @deprecated (4.2) use {@link #update(AuthScheme, Credentials)} - */ - @Deprecated - public void setAuthScheme(final AuthScheme authScheme) { - if (authScheme == null) { - reset(); - return; - } - this.authScheme = authScheme; - } - - /** - * Sets user {@link Credentials} to be used for authentication - * - * @param credentials User credentials - * - * @deprecated (4.2) use {@link #update(AuthScheme, Credentials)} - */ - @Deprecated - public void setCredentials(final Credentials credentials) { - this.credentials = credentials; - } - - /** - * Returns actual {@link AuthScope} if available - * - * @return actual authentication scope if available, {@code null} otherwise - * - * @deprecated (4.2) do not use. - */ - @Deprecated - public AuthScope getAuthScope() { - return this.authScope; - } - - /** - * Sets actual {@link AuthScope}. - * - * @param authScope Authentication scope - * - * @deprecated (4.2) do not use. - */ - @Deprecated - public void setAuthScope(final AuthScope authScope) { - this.authScope = authScope; - } - - @Override - public String toString() { - final StringBuilder buffer = new StringBuilder(); - buffer.append("state:").append(this.state).append(";"); - if (this.authScheme != null) { - buffer.append("auth scheme:").append(this.authScheme.getSchemeName()).append(";"); - } - if (this.credentials != null) { - buffer.append("credentials present"); - } - return buffer.toString(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthenticationException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthenticationException.java deleted file mode 100644 index 4943f2e0..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/AuthenticationException.java +++ /dev/null @@ -1,70 +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 com.tracelytics.ext.apache.http.auth; - -import com.tracelytics.ext.apache.http.ProtocolException; -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * Signals a failure in authentication process - * - * - * @since 4.0 - */ -@Immutable -public class AuthenticationException extends ProtocolException { - - private static final long serialVersionUID = -6794031905674764776L; - - /** - * Creates a new AuthenticationException with a {@code null} detail message. - */ - public AuthenticationException() { - super(); - } - - /** - * Creates a new AuthenticationException with the specified message. - * - * @param message the exception detail message - */ - public AuthenticationException(final String message) { - super(message); - } - - /** - * Creates a new AuthenticationException with the specified detail message and cause. - * - * @param message the exception detail message - * @param cause the {@code Throwable} that caused this exception, or {@code null} - * if the cause is unavailable, unknown, or not a {@code Throwable} - */ - public AuthenticationException(final String message, final Throwable cause) { - super(message, cause); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/BasicUserPrincipal.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/BasicUserPrincipal.java deleted file mode 100644 index 618a8b2c..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/BasicUserPrincipal.java +++ /dev/null @@ -1,90 +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 com.tracelytics.ext.apache.http.auth; - -import java.io.Serializable; -import java.security.Principal; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.LangUtils; - -/** - * Basic user principal used for HTTP authentication - * - * @since 4.0 - */ -@Immutable -public final class BasicUserPrincipal implements Principal, Serializable { - - private static final long serialVersionUID = -2266305184969850467L; - - private final String username; - - public BasicUserPrincipal(final String username) { - super(); - Args.notNull(username, "User name"); - this.username = username; - } - - @Override - public String getName() { - return this.username; - } - - @Override - public int hashCode() { - int hash = LangUtils.HASH_SEED; - hash = LangUtils.hashCode(hash, this.username); - return hash; - } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - if (o instanceof BasicUserPrincipal) { - final BasicUserPrincipal that = (BasicUserPrincipal) o; - if (LangUtils.equals(this.username, that.username)) { - return true; - } - } - return false; - } - - @Override - public String toString() { - final StringBuilder buffer = new StringBuilder(); - buffer.append("[principal: "); - buffer.append(this.username); - buffer.append("]"); - return buffer.toString(); - } - -} - diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/ChallengeState.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/ChallengeState.java deleted file mode 100644 index 66170ba9..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/ChallengeState.java +++ /dev/null @@ -1,38 +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 com.tracelytics.ext.apache.http.auth; - -/** - * Challenge mode (TARGET or PROXY) - * - * @since 4.2 - */ -public enum ChallengeState { - - TARGET, PROXY - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/ContextAwareAuthScheme.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/ContextAwareAuthScheme.java deleted file mode 100644 index 83d41684..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/ContextAwareAuthScheme.java +++ /dev/null @@ -1,62 +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 com.tracelytics.ext.apache.http.auth; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -/** - * This interface represents an extended authentication scheme - * that requires access to {@link HttpContext} in order to - * generate an authorization string. - * - * TODO: Fix AuthScheme interface in the next major version - * - * @since 4.1 - */ - -public interface ContextAwareAuthScheme extends AuthScheme { - - /** - * Produces an authorization string for the given set of - * {@link Credentials}. - * - * @param credentials The set of credentials to be used for athentication - * @param request The request being authenticated - * @param context HTTP context - * @throws AuthenticationException if authorization string cannot - * be generated due to an authentication failure - * - * @return the authorization string - */ - Header authenticate( - Credentials credentials, - HttpRequest request, - HttpContext context) throws AuthenticationException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/Credentials.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/Credentials.java deleted file mode 100644 index b8954b88..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/Credentials.java +++ /dev/null @@ -1,44 +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 com.tracelytics.ext.apache.http.auth; - -import java.security.Principal; - -/** - * This interface represents a set of credentials consisting of a security - * principal and a secret (password) that can be used to establish user - * identity - * - * @since 4.0 - */ -public interface Credentials { - - Principal getUserPrincipal(); - - String getPassword(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/InvalidCredentialsException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/InvalidCredentialsException.java deleted file mode 100644 index 37aa8acb..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/InvalidCredentialsException.java +++ /dev/null @@ -1,69 +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 com.tracelytics.ext.apache.http.auth; - -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * Authentication credentials required to respond to a authentication - * challenge are invalid - * - * - * @since 4.0 - */ -@Immutable -public class InvalidCredentialsException extends AuthenticationException { - - private static final long serialVersionUID = -4834003835215460648L; - - /** - * Creates a new InvalidCredentialsException with a {@code null} detail message. - */ - public InvalidCredentialsException() { - super(); - } - - /** - * Creates a new InvalidCredentialsException with the specified message. - * - * @param message the exception detail message - */ - public InvalidCredentialsException(final String message) { - super(message); - } - - /** - * Creates a new InvalidCredentialsException with the specified detail message and cause. - * - * @param message the exception detail message - * @param cause the {@code Throwable} that caused this exception, or {@code null} - * if the cause is unavailable, unknown, or not a {@code Throwable} - */ - public InvalidCredentialsException(final String message, final Throwable cause) { - super(message, cause); - } -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/KerberosCredentials.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/KerberosCredentials.java deleted file mode 100644 index 229c3fab..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/KerberosCredentials.java +++ /dev/null @@ -1,69 +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 com.tracelytics.ext.apache.http.auth; - -import java.io.Serializable; -import java.security.Principal; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import org.ietf.jgss.GSSCredential; - -/** - * {@link Credentials} implementation based on GSSCredential for Kerberos Authentication. - * - * @since 4.4 - */ -@Immutable -public class KerberosCredentials implements Credentials, Serializable { - - private static final long serialVersionUID = 487421613855550713L; - - /** GSSCredential */ - private final GSSCredential gssCredential; - - /** - * Constructor with GSSCredential argument - * - * @param gssCredential - */ - public KerberosCredentials(final GSSCredential gssCredential) { - this.gssCredential = gssCredential; - } - - public GSSCredential getGSSCredential() { - return gssCredential; - } - - public Principal getUserPrincipal() { - return null; - } - - public String getPassword() { - return null; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/MalformedChallengeException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/MalformedChallengeException.java deleted file mode 100644 index bd7b9f12..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/MalformedChallengeException.java +++ /dev/null @@ -1,70 +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 com.tracelytics.ext.apache.http.auth; - -import com.tracelytics.ext.apache.http.ProtocolException; -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * Signals that authentication challenge is in some way invalid or - * illegal in the given context - * - * - * @since 4.0 - */ -@Immutable -public class MalformedChallengeException extends ProtocolException { - - private static final long serialVersionUID = 814586927989932284L; - - /** - * Creates a new MalformedChallengeException with a {@code null} detail message. - */ - public MalformedChallengeException() { - super(); - } - - /** - * Creates a new MalformedChallengeException with the specified message. - * - * @param message the exception detail message - */ - public MalformedChallengeException(final String message) { - super(message); - } - - /** - * Creates a new MalformedChallengeException with the specified detail message and cause. - * - * @param message the exception detail message - * @param cause the {@code Throwable} that caused this exception, or {@code null} - * if the cause is unavailable, unknown, or not a {@code Throwable} - */ - public MalformedChallengeException(final String message, final Throwable cause) { - super(message, cause); - } -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/NTCredentials.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/NTCredentials.java deleted file mode 100644 index f0ec00ab..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/NTCredentials.java +++ /dev/null @@ -1,179 +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 com.tracelytics.ext.apache.http.auth; - -import java.io.Serializable; -import java.security.Principal; -import java.util.Locale; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.LangUtils; - -/** - * {@link Credentials} implementation for Microsoft Windows platforms that includes - * Windows specific attributes such as name of the domain the user belongs to. - * - * @since 4.0 - */ -@Immutable -public class NTCredentials implements Credentials, Serializable { - - private static final long serialVersionUID = -7385699315228907265L; - - /** The user principal */ - private final NTUserPrincipal principal; - - /** Password */ - private final String password; - - /** The host the authentication request is originating from. */ - private final String workstation; - - /** - * The constructor with the fully qualified username and password combined - * string argument. - * - * @param usernamePassword the domain/username:password formed string - */ - public NTCredentials(final String usernamePassword) { - super(); - Args.notNull(usernamePassword, "Username:password string"); - final String username; - final int atColon = usernamePassword.indexOf(':'); - if (atColon >= 0) { - username = usernamePassword.substring(0, atColon); - this.password = usernamePassword.substring(atColon + 1); - } else { - username = usernamePassword; - this.password = null; - } - final int atSlash = username.indexOf('/'); - if (atSlash >= 0) { - this.principal = new NTUserPrincipal( - username.substring(0, atSlash).toUpperCase(Locale.ROOT), - username.substring(atSlash + 1)); - } else { - this.principal = new NTUserPrincipal( - null, - username.substring(atSlash + 1)); - } - this.workstation = null; - } - - /** - * Constructor. - * @param userName The user name. This should not include the domain to authenticate with. - * For example: "user" is correct whereas "DOMAIN\\user" is not. - * @param password The password. - * @param workstation The workstation the authentication request is originating from. - * Essentially, the computer name for this machine. - * @param domain The domain to authenticate within. - */ - public NTCredentials( - final String userName, - final String password, - final String workstation, - final String domain) { - super(); - Args.notNull(userName, "User name"); - this.principal = new NTUserPrincipal(domain, userName); - this.password = password; - if (workstation != null) { - this.workstation = workstation.toUpperCase(Locale.ROOT); - } else { - this.workstation = null; - } - } - - @Override - public Principal getUserPrincipal() { - return this.principal; - } - - public String getUserName() { - return this.principal.getUsername(); - } - - @Override - public String getPassword() { - return this.password; - } - - /** - * Retrieves the name to authenticate with. - * - * @return String the domain these credentials are intended to authenticate with. - */ - public String getDomain() { - return this.principal.getDomain(); - } - - /** - * Retrieves the workstation name of the computer originating the request. - * - * @return String the workstation the user is logged into. - */ - public String getWorkstation() { - return this.workstation; - } - - @Override - public int hashCode() { - int hash = LangUtils.HASH_SEED; - hash = LangUtils.hashCode(hash, this.principal); - hash = LangUtils.hashCode(hash, this.workstation); - return hash; - } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - if (o instanceof NTCredentials) { - final NTCredentials that = (NTCredentials) o; - if (LangUtils.equals(this.principal, that.principal) - && LangUtils.equals(this.workstation, that.workstation)) { - return true; - } - } - return false; - } - - @Override - public String toString() { - final StringBuilder buffer = new StringBuilder(); - buffer.append("[principal: "); - buffer.append(this.principal); - buffer.append("][workstation: "); - buffer.append(this.workstation); - buffer.append("]"); - return buffer.toString(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/NTUserPrincipal.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/NTUserPrincipal.java deleted file mode 100644 index be1f0414..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/NTUserPrincipal.java +++ /dev/null @@ -1,114 +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 com.tracelytics.ext.apache.http.auth; - -import java.io.Serializable; -import java.security.Principal; -import java.util.Locale; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.LangUtils; - -/** - * Microsoft Windows specific user principal implementation. - * - * @since 4.0 - */ -@Immutable -public class NTUserPrincipal implements Principal, Serializable { - - private static final long serialVersionUID = -6870169797924406894L; - - private final String username; - private final String domain; - private final String ntname; - - public NTUserPrincipal( - final String domain, - final String username) { - super(); - Args.notNull(username, "User name"); - this.username = username; - if (domain != null) { - this.domain = domain.toUpperCase(Locale.ROOT); - } else { - this.domain = null; - } - if (this.domain != null && !this.domain.isEmpty()) { - final StringBuilder buffer = new StringBuilder(); - buffer.append(this.domain); - buffer.append('\\'); - buffer.append(this.username); - this.ntname = buffer.toString(); - } else { - this.ntname = this.username; - } - } - - @Override - public String getName() { - return this.ntname; - } - - public String getDomain() { - return this.domain; - } - - public String getUsername() { - return this.username; - } - - @Override - public int hashCode() { - int hash = LangUtils.HASH_SEED; - hash = LangUtils.hashCode(hash, this.username); - hash = LangUtils.hashCode(hash, this.domain); - return hash; - } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - if (o instanceof NTUserPrincipal) { - final NTUserPrincipal that = (NTUserPrincipal) o; - if (LangUtils.equals(this.username, that.username) - && LangUtils.equals(this.domain, that.domain)) { - return true; - } - } - return false; - } - - @Override - public String toString() { - return this.ntname; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/UsernamePasswordCredentials.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/UsernamePasswordCredentials.java deleted file mode 100644 index b9977e2c..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/UsernamePasswordCredentials.java +++ /dev/null @@ -1,122 +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 com.tracelytics.ext.apache.http.auth; - -import java.io.Serializable; -import java.security.Principal; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.LangUtils; - -/** - * Simple {@link Credentials} implementation based on a user name / password - * pair. - * - * @since 4.0 - */ -@Immutable -public class UsernamePasswordCredentials implements Credentials, Serializable { - - private static final long serialVersionUID = 243343858802739403L; - - private final BasicUserPrincipal principal; - private final String password; - - /** - * The constructor with the username and password combined string argument. - * - * @param usernamePassword the username:password formed string - * @see #toString - */ - public UsernamePasswordCredentials(final String usernamePassword) { - super(); - Args.notNull(usernamePassword, "Username:password string"); - final int atColon = usernamePassword.indexOf(':'); - if (atColon >= 0) { - this.principal = new BasicUserPrincipal(usernamePassword.substring(0, atColon)); - this.password = usernamePassword.substring(atColon + 1); - } else { - this.principal = new BasicUserPrincipal(usernamePassword); - this.password = null; - } - } - - - /** - * The constructor with the username and password arguments. - * - * @param userName the user name - * @param password the password - */ - public UsernamePasswordCredentials(final String userName, final String password) { - super(); - Args.notNull(userName, "Username"); - this.principal = new BasicUserPrincipal(userName); - this.password = password; - } - - @Override - public Principal getUserPrincipal() { - return this.principal; - } - - public String getUserName() { - return this.principal.getName(); - } - - @Override - public String getPassword() { - return password; - } - - @Override - public int hashCode() { - return this.principal.hashCode(); - } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - if (o instanceof UsernamePasswordCredentials) { - final UsernamePasswordCredentials that = (UsernamePasswordCredentials) o; - if (LangUtils.equals(this.principal, that.principal)) { - return true; - } - } - return false; - } - - @Override - public String toString() { - return this.principal.toString(); - } - -} - diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/package-info.java deleted file mode 100644 index 31fcbf0b..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/package-info.java +++ /dev/null @@ -1,31 +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 - * . - * - */ - -/** - * Client HTTP authentication APIs. - */ -package com.tracelytics.ext.apache.http.auth; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/params/AuthPNames.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/params/AuthPNames.java deleted file mode 100644 index 8a5a9312..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/params/AuthPNames.java +++ /dev/null @@ -1,74 +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 com.tracelytics.ext.apache.http.auth.params; - -/** - * Parameter names for HTTP authentication classes. - * - * @since 4.0 - * - * @deprecated (4.3) use {@link com.tracelytics.ext.apache.http.client.config.RequestConfig} - * and constructor parameters of - * {@link com.tracelytics.ext.apache.http.auth.AuthSchemeProvider}s. -*/ -@Deprecated -public interface AuthPNames { - - /** - * Defines the charset to be used when encoding - * {@link com.tracelytics.ext.apache.http.auth.Credentials}. - *

- * This parameter expects a value of type {@link String}. - */ - public static final String CREDENTIAL_CHARSET = "http.auth.credential-charset"; - - /** - * Defines the order of preference for supported - * {@link com.tracelytics.ext.apache.http.auth.AuthScheme}s when authenticating with - * the target host. - *

- * This parameter expects a value of type {@link java.util.Collection}. The - * collection is expected to contain {@link String} instances representing - * a name of an authentication scheme as returned by - * {@link com.tracelytics.ext.apache.http.auth.AuthScheme#getSchemeName()}. - */ - public static final String TARGET_AUTH_PREF = "http.auth.target-scheme-pref"; - - /** - * Defines the order of preference for supported - * {@link com.tracelytics.ext.apache.http.auth.AuthScheme}s when authenticating with the - * proxy host. - *

- * This parameter expects a value of type {@link java.util.Collection}. The - * collection is expected to contain {@link String} instances representing - * a name of an authentication scheme as returned by - * {@link com.tracelytics.ext.apache.http.auth.AuthScheme#getSchemeName()}. - */ - public static final String PROXY_AUTH_PREF = "http.auth.proxy-scheme-pref"; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/params/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/params/package-info.java deleted file mode 100644 index 3332b81d..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/auth/params/package-info.java +++ /dev/null @@ -1,32 +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 - * . - * - */ - -/** - * Deprecated. - * @deprecated (4.3). - */ -package com.tracelytics.ext.apache.http.auth.params; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/AuthCache.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/AuthCache.java deleted file mode 100644 index 9915ea2d..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/AuthCache.java +++ /dev/null @@ -1,50 +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 com.tracelytics.ext.apache.http.client; - -import com.tracelytics.ext.apache.http.HttpHost; - -import com.tracelytics.ext.apache.http.auth.AuthScheme; - -/** - * Abstract {@link AuthScheme} cache. Initialized {@link AuthScheme} objects - * from this cache can be used to preemptively authenticate against known - * hosts. - * - * @since 4.1 - */ -public interface AuthCache { - - void put(HttpHost host, AuthScheme authScheme); - - AuthScheme get(HttpHost host); - - void remove(HttpHost host); - - void clear(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/AuthenticationStrategy.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/AuthenticationStrategy.java deleted file mode 100644 index f6ae7309..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/AuthenticationStrategy.java +++ /dev/null @@ -1,131 +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 com.tracelytics.ext.apache.http.client; - -import java.util.Map; -import java.util.Queue; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -import com.tracelytics.ext.apache.http.auth.AuthOption; -import com.tracelytics.ext.apache.http.auth.AuthScheme; -import com.tracelytics.ext.apache.http.auth.MalformedChallengeException; - -/** -/** - * A handler for determining if an HTTP response represents an authentication challenge that was - * sent back to the client as a result of authentication failure. - *

- * Implementations of this interface must be thread-safe. Access to shared data must be - * synchronized as methods of this interface may be executed from multiple threads. - * - * @since 4.2 - */ -public interface AuthenticationStrategy { - - /** - * Determines if the given HTTP response response represents - * an authentication challenge that was sent back as a result - * of authentication failure. - * - * @param authhost authentication host. - * @param response HTTP response. - * @param context HTTP context. - * @return {@code true} if user authentication is required, - * {@code false} otherwise. - */ - boolean isAuthenticationRequested( - HttpHost authhost, - HttpResponse response, - HttpContext context); - - /** - * Extracts from the given HTTP response a collection of authentication - * challenges, each of which represents an authentication scheme supported - * by the authentication host. - * - * @param authhost authentication host. - * @param response HTTP response. - * @param context HTTP context. - * @return a collection of challenges keyed by names of corresponding - * authentication schemes. - * @throws MalformedChallengeException if one of the authentication - * challenges is not valid or malformed. - */ - Map getChallenges( - HttpHost authhost, - HttpResponse response, - HttpContext context) throws MalformedChallengeException; - - /** - * Selects one authentication challenge out of all available and - * creates and generates {@link AuthOption} instance capable of - * processing that challenge. - * - * @param challenges collection of challenges. - * @param authhost authentication host. - * @param response HTTP response. - * @param context HTTP context. - * @return authentication auth schemes that can be used for authentication. Can be empty. - * @throws MalformedChallengeException if one of the authentication - * challenges is not valid or malformed. - */ - Queue select( - Map challenges, - HttpHost authhost, - HttpResponse response, - HttpContext context) throws MalformedChallengeException; - - /** - * Callback invoked in case of successful authentication. - * - * @param authhost authentication host. - * @param authScheme authentication scheme used. - * @param context HTTP context. - */ - void authSucceeded( - HttpHost authhost, - AuthScheme authScheme, - HttpContext context); - - /** - * Callback invoked in case of unsuccessful authentication. - * - * @param authhost authentication host. - * @param authScheme authentication scheme used. - * @param context HTTP context. - */ - void authFailed( - HttpHost authhost, - AuthScheme authScheme, - HttpContext context); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/BackoffManager.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/BackoffManager.java deleted file mode 100644 index c5fe13d1..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/BackoffManager.java +++ /dev/null @@ -1,54 +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 com.tracelytics.ext.apache.http.client; - -import com.tracelytics.ext.apache.http.conn.routing.HttpRoute; - -/** - * Represents a controller that dynamically adjusts the size - * of an available connection pool based on feedback from - * using the connections. - * - * @since 4.2 - * - */ -public interface BackoffManager { - - /** - * Called when we have decided that the result of - * using a connection should be interpreted as a - * backoff signal. - */ - public void backOff(HttpRoute route); - - /** - * Called when we have determined that the result of - * using a connection has succeeded and that we may - * probe for more connections. - */ - public void probe(HttpRoute route); -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/CircularRedirectException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/CircularRedirectException.java deleted file mode 100644 index 81baa435..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/CircularRedirectException.java +++ /dev/null @@ -1,68 +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 com.tracelytics.ext.apache.http.client; - -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * Signals a circular redirect - * - * - * @since 4.0 - */ -@Immutable -public class CircularRedirectException extends RedirectException { - - private static final long serialVersionUID = 6830063487001091803L; - - /** - * Creates a new CircularRedirectException with a {@code null} detail message. - */ - public CircularRedirectException() { - super(); - } - - /** - * Creates a new CircularRedirectException with the specified detail message. - * - * @param message The exception detail message - */ - public CircularRedirectException(final String message) { - super(message); - } - - /** - * Creates a new CircularRedirectException with the specified detail message and cause. - * - * @param message the exception detail message - * @param cause the {@code Throwable} that caused this exception, or {@code null} - * if the cause is unavailable, unknown, or not a {@code Throwable} - */ - public CircularRedirectException(final String message, final Throwable cause) { - super(message, cause); - } -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/ClientProtocolException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/ClientProtocolException.java deleted file mode 100644 index 19a38f67..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/ClientProtocolException.java +++ /dev/null @@ -1,61 +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 com.tracelytics.ext.apache.http.client; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * Signals an error in the HTTP protocol. - * - * @since 4.0 - */ -@Immutable -public class ClientProtocolException extends IOException { - - private static final long serialVersionUID = -5596590843227115865L; - - public ClientProtocolException() { - super(); - } - - public ClientProtocolException(final String s) { - super(s); - } - - public ClientProtocolException(final Throwable cause) { - initCause(cause); - } - - public ClientProtocolException(final String message, final Throwable cause) { - super(message); - initCause(cause); - } - - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/ConnectionBackoffStrategy.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/ConnectionBackoffStrategy.java deleted file mode 100644 index 26a710df..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/ConnectionBackoffStrategy.java +++ /dev/null @@ -1,64 +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 com.tracelytics.ext.apache.http.client; - -import com.tracelytics.ext.apache.http.HttpResponse; - -/** - * When managing a dynamic number of connections for a given route, this - * strategy assesses whether a given request execution outcome should - * result in a backoff signal or not, based on either examining the - * {@code Throwable} that resulted or by examining the resulting - * response (e.g. for its status code). - * - * @since 4.2 - * - */ -public interface ConnectionBackoffStrategy { - - /** - * Determines whether seeing the given {@code Throwable} as - * a result of request execution should result in a backoff - * signal. - * @param t the {@code Throwable} that happened - * @return {@code true} if a backoff signal should be - * given - */ - boolean shouldBackoff(Throwable t); - - /** - * Determines whether receiving the given {@link HttpResponse} as - * a result of request execution should result in a backoff - * signal. Implementations MUST restrict themselves to examining - * the response header and MUST NOT consume any of the response - * body, if any. - * @param resp the {@code HttpResponse} that was received - * @return {@code true} if a backoff signal should be - * given - */ - boolean shouldBackoff(HttpResponse resp); -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/CookieStore.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/CookieStore.java deleted file mode 100644 index 4f35d01d..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/CookieStore.java +++ /dev/null @@ -1,71 +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 com.tracelytics.ext.apache.http.client; - -import java.util.Date; -import java.util.List; - -import com.tracelytics.ext.apache.http.cookie.Cookie; - -/** - * This interface represents an abstract store for {@link Cookie} - * objects. - * - * @since 4.0 - */ -public interface CookieStore { - - /** - * Adds an {@link Cookie}, replacing any existing equivalent cookies. - * If the given cookie has already expired it will not be added, but existing - * values will still be removed. - * - * @param cookie the {@link Cookie cookie} to be added - */ - void addCookie(Cookie cookie); - - /** - * Returns all cookies contained in this store. - * - * @return all cookies - */ - List getCookies(); - - /** - * Removes all of {@link Cookie}s in this store that have expired by - * the specified {@link java.util.Date}. - * - * @return true if any cookies were purged. - */ - boolean clearExpired(Date date); - - /** - * Clears all cookies. - */ - void clear(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/CredentialsProvider.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/CredentialsProvider.java deleted file mode 100644 index 4e811398..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/CredentialsProvider.java +++ /dev/null @@ -1,71 +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 com.tracelytics.ext.apache.http.client; - -import com.tracelytics.ext.apache.http.auth.AuthScope; -import com.tracelytics.ext.apache.http.auth.Credentials; - -/** - * Abstract credentials provider that maintains a collection of user - * credentials. - *

- * Implementations of this interface must be thread-safe. Access to shared - * data must be synchronized as methods of this interface may be executed - * from multiple threads. - * - * @since 4.0 - */ -public interface CredentialsProvider { - - /** - * Sets the {@link Credentials credentials} for the given authentication - * scope. Any previous credentials for the given scope will be overwritten. - * - * @param authscope the {@link AuthScope authentication scope} - * @param credentials the authentication {@link Credentials credentials} - * for the given scope. - * - * @see #getCredentials(AuthScope) - */ - void setCredentials(AuthScope authscope, Credentials credentials); - - /** - * Get the {@link Credentials credentials} for the given authentication scope. - * - * @param authscope the {@link AuthScope authentication scope} - * @return the credentials - * - * @see #setCredentials(AuthScope, Credentials) - */ - Credentials getCredentials(AuthScope authscope); - - /** - * Clears all credentials. - */ - void clear(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/HttpClient.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/HttpClient.java deleted file mode 100644 index 22bad8b2..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/HttpClient.java +++ /dev/null @@ -1,263 +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 com.tracelytics.ext.apache.http.client; - -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -import com.tracelytics.ext.apache.http.client.methods.HttpUriRequest; -import com.tracelytics.ext.apache.http.conn.ClientConnectionManager; - -import java.io.IOException; - -/** - * This interface represents only the most basic contract for HTTP request - * execution. It imposes no restrictions or particular details on the request - * execution process and leaves the specifics of state management, - * authentication and redirect handling up to individual implementations. - * - * @since 4.0 - */ -@SuppressWarnings("deprecation") -public interface HttpClient { - - - /** - * Obtains the parameters for this client. - * These parameters will become defaults for all requests being - * executed with this client, and for the parameters of - * dependent objects in this client. - * - * @return the default parameters - * - * @deprecated (4.3) use - * {@link com.tracelytics.ext.apache.http.client.config.RequestConfig}. - */ - @Deprecated - HttpParams getParams(); - - /** - * Obtains the connection manager used by this client. - * - * @return the connection manager - * - * @deprecated (4.3) use - * {@link com.tracelytics.ext.apache.http.impl.client.HttpClientBuilder}. - */ - @Deprecated - ClientConnectionManager getConnectionManager(); - - /** - * Executes HTTP request using the default context. - * - * @param request the request to execute - * - * @return the response to the request. This is always a final response, - * never an intermediate response with an 1xx status code. - * Whether redirects or authentication challenges will be returned - * or handled automatically depends on the implementation and - * configuration of this client. - * @throws IOException in case of a problem or the connection was aborted - * @throws ClientProtocolException in case of an http protocol error - */ - HttpResponse execute(HttpUriRequest request) - throws IOException, ClientProtocolException; - - /** - * Executes HTTP request using the given context. - * - * @param request the request to execute - * @param context the context to use for the execution, or - * {@code null} to use the default context - * - * @return the response to the request. This is always a final response, - * never an intermediate response with an 1xx status code. - * Whether redirects or authentication challenges will be returned - * or handled automatically depends on the implementation and - * configuration of this client. - * @throws IOException in case of a problem or the connection was aborted - * @throws ClientProtocolException in case of an http protocol error - */ - HttpResponse execute(HttpUriRequest request, HttpContext context) - throws IOException, ClientProtocolException; - - /** - * Executes HTTP request using the default context. - * - * @param target the target host for the request. - * Implementations may accept {@code null} - * if they can still determine a route, for example - * to a default target or by inspecting the request. - * @param request the request to execute - * - * @return the response to the request. This is always a final response, - * never an intermediate response with an 1xx status code. - * Whether redirects or authentication challenges will be returned - * or handled automatically depends on the implementation and - * configuration of this client. - * @throws IOException in case of a problem or the connection was aborted - * @throws ClientProtocolException in case of an http protocol error - */ - HttpResponse execute(HttpHost target, HttpRequest request) - throws IOException, ClientProtocolException; - - /** - * Executes HTTP request using the given context. - * - * @param target the target host for the request. - * Implementations may accept {@code null} - * if they can still determine a route, for example - * to a default target or by inspecting the request. - * @param request the request to execute - * @param context the context to use for the execution, or - * {@code null} to use the default context - * - * @return the response to the request. This is always a final response, - * never an intermediate response with an 1xx status code. - * Whether redirects or authentication challenges will be returned - * or handled automatically depends on the implementation and - * configuration of this client. - * @throws IOException in case of a problem or the connection was aborted - * @throws ClientProtocolException in case of an http protocol error - */ - HttpResponse execute(HttpHost target, HttpRequest request, - HttpContext context) - throws IOException, ClientProtocolException; - - /** - * Executes HTTP request using the default context and processes the - * response using the given response handler. - *

- * Implementing classes are required to ensure that the content entity - * associated with the response is fully consumed and the underlying - * connection is released back to the connection manager automatically - * in all cases relieving individual {@link ResponseHandler}s from - * having to manage resource deallocation internally. - *

- * - * @param request the request to execute - * @param responseHandler the response handler - * - * @return the response object as generated by the response handler. - * @throws IOException in case of a problem or the connection was aborted - * @throws ClientProtocolException in case of an http protocol error - */ - T execute( - HttpUriRequest request, - ResponseHandler responseHandler) - throws IOException, ClientProtocolException; - - /** - * Executes HTTP request using the given context and processes the - * response using the given response handler. - *

- * Implementing classes are required to ensure that the content entity - * associated with the response is fully consumed and the underlying - * connection is released back to the connection manager automatically - * in all cases relieving individual {@link ResponseHandler}s from - * having to manage resource deallocation internally. - *

- * - * @param request the request to execute - * @param responseHandler the response handler - * @param context the context to use for the execution, or - * {@code null} to use the default context - * - * @return the response object as generated by the response handler. - * @throws IOException in case of a problem or the connection was aborted - * @throws ClientProtocolException in case of an http protocol error - */ - T execute( - HttpUriRequest request, - ResponseHandler responseHandler, - HttpContext context) - throws IOException, ClientProtocolException; - - /** - * Executes HTTP request to the target using the default context and - * processes the response using the given response handler. - *

- * Implementing classes are required to ensure that the content entity - * associated with the response is fully consumed and the underlying - * connection is released back to the connection manager automatically - * in all cases relieving individual {@link ResponseHandler}s from - * having to manage resource deallocation internally. - *

- * - * @param target the target host for the request. - * Implementations may accept {@code null} - * if they can still determine a route, for example - * to a default target or by inspecting the request. - * @param request the request to execute - * @param responseHandler the response handler - * - * @return the response object as generated by the response handler. - * @throws IOException in case of a problem or the connection was aborted - * @throws ClientProtocolException in case of an http protocol error - */ - T execute( - HttpHost target, - HttpRequest request, - ResponseHandler responseHandler) - throws IOException, ClientProtocolException; - - /** - * Executes HTTP request to the target using the given context and - * processes the response using the given response handler. - *

- * Implementing classes are required to ensure that the content entity - * associated with the response is fully consumed and the underlying - * connection is released back to the connection manager automatically - * in all cases relieving individual {@link ResponseHandler}s from - * having to manage resource deallocation internally. - *

- * - * @param target the target host for the request. - * Implementations may accept {@code null} - * if they can still determine a route, for example - * to a default target or by inspecting the request. - * @param request the request to execute - * @param responseHandler the response handler - * @param context the context to use for the execution, or - * {@code null} to use the default context - * - * @return the response object as generated by the response handler. - * @throws IOException in case of a problem or the connection was aborted - * @throws ClientProtocolException in case of an http protocol error - */ - T execute( - HttpHost target, - HttpRequest request, - ResponseHandler responseHandler, - HttpContext context) - throws IOException, ClientProtocolException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/HttpRequestRetryHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/HttpRequestRetryHandler.java deleted file mode 100644 index cf69fc81..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/HttpRequestRetryHandler.java +++ /dev/null @@ -1,60 +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 com.tracelytics.ext.apache.http.client; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -/** - * A handler for determining if an HttpRequest should be retried after a - * recoverable exception during execution. - *

- * Implementations of this interface must be thread-safe. Access to shared - * data must be synchronized as methods of this interface may be executed - * from multiple threads. - * - * @since 4.0 - */ -public interface HttpRequestRetryHandler { - - /** - * Determines if a method should be retried after an IOException - * occurs during execution. - * - * @param exception the exception that occurred - * @param executionCount the number of times this method has been - * unsuccessfully executed - * @param context the context for the request execution - * - * @return {@code true} if the method should be retried, {@code false} - * otherwise - */ - boolean retryRequest(IOException exception, int executionCount, HttpContext context); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/HttpResponseException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/HttpResponseException.java deleted file mode 100644 index a5300298..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/HttpResponseException.java +++ /dev/null @@ -1,52 +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 com.tracelytics.ext.apache.http.client; - -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * Signals a non 2xx HTTP response. - * - * @since 4.0 - */ -@Immutable -public class HttpResponseException extends ClientProtocolException { - - private static final long serialVersionUID = -7186627969477257933L; - - private final int statusCode; - - public HttpResponseException(final int statusCode, final String s) { - super(s); - this.statusCode = statusCode; - } - - public int getStatusCode() { - return this.statusCode; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/NonRepeatableRequestException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/NonRepeatableRequestException.java deleted file mode 100644 index 9fd548c9..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/NonRepeatableRequestException.java +++ /dev/null @@ -1,72 +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 com.tracelytics.ext.apache.http.client; - -import com.tracelytics.ext.apache.http.ProtocolException; -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * Signals failure to retry the request due to non-repeatable request - * entity. - * - * - * @since 4.0 - */ -@Immutable -public class NonRepeatableRequestException extends ProtocolException { - - private static final long serialVersionUID = 82685265288806048L; - - /** - * Creates a new NonRepeatableEntityException with a {@code null} detail message. - */ - public NonRepeatableRequestException() { - super(); - } - - /** - * Creates a new NonRepeatableEntityException with the specified detail message. - * - * @param message The exception detail message - */ - public NonRepeatableRequestException(final String message) { - super(message); - } - - /** - * Creates a new NonRepeatableEntityException with the specified detail message. - * - * @param message The exception detail message - * @param cause the cause - */ - public NonRepeatableRequestException(final String message, final Throwable cause) { - super(message, cause); - } - - - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/RedirectException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/RedirectException.java deleted file mode 100644 index 59384ae8..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/RedirectException.java +++ /dev/null @@ -1,69 +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 com.tracelytics.ext.apache.http.client; - -import com.tracelytics.ext.apache.http.ProtocolException; -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * Signals violation of HTTP specification caused by an invalid redirect - * - * - * @since 4.0 - */ -@Immutable -public class RedirectException extends ProtocolException { - - private static final long serialVersionUID = 4418824536372559326L; - - /** - * Creates a new RedirectException with a {@code null} detail message. - */ - public RedirectException() { - super(); - } - - /** - * Creates a new RedirectException with the specified detail message. - * - * @param message The exception detail message - */ - public RedirectException(final String message) { - super(message); - } - - /** - * Creates a new RedirectException with the specified detail message and cause. - * - * @param message the exception detail message - * @param cause the {@code Throwable} that caused this exception, or {@code null} - * if the cause is unavailable, unknown, or not a {@code Throwable} - */ - public RedirectException(final String message, final Throwable cause) { - super(message, cause); - } -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/RedirectStrategy.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/RedirectStrategy.java deleted file mode 100644 index 09d8d751..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/RedirectStrategy.java +++ /dev/null @@ -1,82 +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 com.tracelytics.ext.apache.http.client; - -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.ProtocolException; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -import com.tracelytics.ext.apache.http.client.methods.HttpUriRequest; - -/** - * A strategy for determining if an HTTP request should be redirected to - * a new location in response to an HTTP response received from the target - * server. - *

- * Implementations of this interface must be thread-safe. Access to shared - * data must be synchronized as methods of this interface may be executed - * from multiple threads. - * - * @since 4.1 - */ -public interface RedirectStrategy { - - /** - * Determines if a request should be redirected to a new location - * given the response from the target server. - * - * @param request the executed request - * @param response the response received from the target server - * @param context the context for the request execution - * - * @return {@code true} if the request should be redirected, {@code false} - * otherwise - */ - boolean isRedirected( - HttpRequest request, - HttpResponse response, - HttpContext context) throws ProtocolException; - - /** - * Determines the redirect location given the response from the target - * server and the current request execution context and generates a new - * request to be sent to the location. - * - * @param request the executed request - * @param response the response received from the target server - * @param context the context for the request execution - * - * @return redirected request - */ - HttpUriRequest getRedirect( - HttpRequest request, - HttpResponse response, - HttpContext context) throws ProtocolException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/ResponseHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/ResponseHandler.java deleted file mode 100644 index f5d90805..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/ResponseHandler.java +++ /dev/null @@ -1,54 +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 com.tracelytics.ext.apache.http.client; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.HttpResponse; - -/** - * Handler that encapsulates the process of generating a response object - * from a {@link HttpResponse}. - * - * - * @since 4.0 - */ -public interface ResponseHandler { - - /** - * 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 ClientProtocolException in case of an http protocol error - * @throws IOException in case of a problem or the connection was aborted - */ - T handleResponse(HttpResponse response) throws ClientProtocolException, IOException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/ServiceUnavailableRetryStrategy.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/ServiceUnavailableRetryStrategy.java deleted file mode 100644 index 63d44d68..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/ServiceUnavailableRetryStrategy.java +++ /dev/null @@ -1,60 +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 com.tracelytics.ext.apache.http.client; - -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -/** - * Strategy interface that allows API users to plug in their own logic to - * control whether or not a retry should automatically be done, how many times - * it should be retried and so on. - * - * @since 4.2 - */ -public interface ServiceUnavailableRetryStrategy { - - /** - * Determines if a method should be retried given the response from the target server. - * - * @param response the response from the target server - * @param executionCount the number of times this method has been - * unsuccessfully executed - * @param context the context for the request execution - - * @return {@code true} if the method should be retried, {@code false} - * otherwise - */ - boolean retryRequest(HttpResponse response, int executionCount, HttpContext context); - - /** - * @return The interval between the subsequent auto-retries. - */ - long getRetryInterval(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/UserTokenHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/UserTokenHandler.java deleted file mode 100644 index a74dede9..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/UserTokenHandler.java +++ /dev/null @@ -1,59 +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 com.tracelytics.ext.apache.http.client; - -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -/** - * A handler for determining if the given execution context is user specific - * or not. The token object returned by this handler is expected to uniquely - * identify the current user if the context is user specific or to be - * {@code null} if the context does not contain any resources or details - * specific to the current user. - *

- * The user token will be used to ensure that user specific resources will not - * be shared with or reused by other users. - *

- * - * @since 4.0 - */ -public interface UserTokenHandler { - - /** - * The token object returned by this method is expected to uniquely - * identify the current user if the context is user specific or to be - * {@code null} if it is not. - * - * @param context the execution context - * - * @return user token that uniquely identifies the user or - * {@code null} if the context is not user specific. - */ - Object getUserToken(HttpContext context); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/config/AuthSchemes.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/config/AuthSchemes.java deleted file mode 100644 index 15e5b35c..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/config/AuthSchemes.java +++ /dev/null @@ -1,74 +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 com.tracelytics.ext.apache.http.client.config; - -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * Standard authentication schemes supported by HttpClient. - * - * @since 4.3 - */ -@Immutable -public final class AuthSchemes { - - /** - * Basic authentication scheme as defined in RFC 2617 (considered inherently - * insecure, but most widely supported). - */ - public static final String BASIC = "Basic"; - - /** - * Digest authentication scheme as defined in RFC 2617. - */ - public static final String DIGEST = "Digest"; - - /** - * The NTLM authentication scheme is a proprietary Microsoft Windows - * authentication protocol as defined in [MS-NLMP]. - */ - public static final String NTLM = "NTLM"; - - /** - * SPNEGO authentication scheme as defined in RFC 4559 and RFC 4178 - * (considered to be the most secure among currently supported - * authentication schemes if Kerberos is selected). - */ - public static final String SPNEGO = "Negotiate"; - - /** - * Kerberos authentication scheme as defined in RFC 4120 - * (considered to be the most secure among currently supported - * authentication schemes). - */ - public static final String KERBEROS = "Kerberos"; - - private AuthSchemes() { - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/config/CookieSpecs.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/config/CookieSpecs.java deleted file mode 100644 index dd73b666..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/config/CookieSpecs.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 com.tracelytics.ext.apache.http.client.config; - -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * Standard cookie specifications supported by HttpClient. - * - * @since 4.3 - */ -@Immutable -public final class CookieSpecs { - - /** - * The policy that provides high degree of compatibility - * with common cookie management of popular HTTP agents. - * - * @deprecated (4.4) use {link #DEFAULT}. - */ - @Deprecated - public static final String BROWSER_COMPATIBILITY = "compatibility"; - - /** - * The Netscape cookie draft compliant policy. - */ - public static final String NETSCAPE = "netscape"; - - /** - * The RFC 6265 compliant policy (interoprability profile). - */ - public static final String STANDARD = "standard"; - - /** - * The RFC 6265 compliant policy (strict profile). - * - * @since 4.4 - */ - public static final String STANDARD_STRICT = "standard-strict"; - - /** - * The default 'best match' policy. - * - * @deprecated (4.4) use {link #DEFAULT}. - */ - @Deprecated - public static final String BEST_MATCH = "best-match"; - - /** - * The default policy. This policy provides a higher degree of compatibility - * with common cookie management of popular HTTP agents for non-standard - * (Netscape style) cookies. - */ - public static final String DEFAULT = "default"; - - /** - * The policy that ignores cookies. - */ - public static final String IGNORE_COOKIES = "ignoreCookies"; - - private CookieSpecs() { - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/config/RequestConfig.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/config/RequestConfig.java deleted file mode 100644 index ccdd8a23..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/config/RequestConfig.java +++ /dev/null @@ -1,505 +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 com.tracelytics.ext.apache.http.client.config; - -import java.net.InetAddress; -import java.util.Collection; - -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * Immutable class encapsulating request configuration items. - * The default setting for stale connection checking changed - * to false, and the feature was deprecated starting with version 4.4. - */ -@Immutable -public class RequestConfig implements Cloneable { - - public static final RequestConfig DEFAULT = new Builder().build(); - - private final boolean expectContinueEnabled; - private final HttpHost proxy; - private final InetAddress localAddress; - private final boolean staleConnectionCheckEnabled; - private final String cookieSpec; - private final boolean redirectsEnabled; - private final boolean relativeRedirectsAllowed; - private final boolean circularRedirectsAllowed; - private final int maxRedirects; - private final boolean authenticationEnabled; - private final Collection targetPreferredAuthSchemes; - private final Collection proxyPreferredAuthSchemes; - private final int connectionRequestTimeout; - private final int connectTimeout; - private final int socketTimeout; - private final boolean decompressionEnabled; - - RequestConfig( - 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, - final Collection targetPreferredAuthSchemes, - final Collection proxyPreferredAuthSchemes, - final int connectionRequestTimeout, - final int connectTimeout, - final int socketTimeout, - final boolean decompressionEnabled) { - super(); - this.expectContinueEnabled = expectContinueEnabled; - this.proxy = proxy; - this.localAddress = localAddress; - this.staleConnectionCheckEnabled = staleConnectionCheckEnabled; - this.cookieSpec = cookieSpec; - this.redirectsEnabled = redirectsEnabled; - this.relativeRedirectsAllowed = relativeRedirectsAllowed; - this.circularRedirectsAllowed = circularRedirectsAllowed; - this.maxRedirects = maxRedirects; - this.authenticationEnabled = authenticationEnabled; - this.targetPreferredAuthSchemes = targetPreferredAuthSchemes; - this.proxyPreferredAuthSchemes = proxyPreferredAuthSchemes; - this.connectionRequestTimeout = connectionRequestTimeout; - this.connectTimeout = connectTimeout; - this.socketTimeout = socketTimeout; - this.decompressionEnabled = decompressionEnabled; - } - - /** - * Determines whether the 'Expect: 100-Continue' handshake is enabled - * for entity enclosing methods. The purpose of the 'Expect: 100-Continue' - * handshake is to allow a client that is sending a request message with - * a request body to determine if the origin server is willing to - * accept the request (based on the request headers) before the client - * sends the request body. - *

- * The use of the 'Expect: 100-continue' handshake can result in - * a noticeable performance improvement for entity enclosing requests - * (such as POST and PUT) that require the target server's - * authentication. - *

- *

- * 'Expect: 100-continue' handshake should be used with caution, as it - * may cause problems with HTTP servers and proxies that do not support - * HTTP/1.1 protocol. - *

- *

- * Default: {@code false} - *

- */ - public boolean isExpectContinueEnabled() { - return expectContinueEnabled; - } - - /** - * Returns HTTP proxy to be used for request execution. - *

- * Default: {@code null} - *

- */ - public HttpHost getProxy() { - return proxy; - } - - /** - * Returns local address to be used for request execution. - *

- * On machines with multiple network interfaces, this parameter - * can be used to select the network interface from which the - * connection originates. - *

- *

- * Default: {@code null} - *

- */ - public InetAddress getLocalAddress() { - return localAddress; - } - - /** - * Determines whether stale connection check is to be used. The stale - * connection check can cause up to 30 millisecond overhead per request and - * should be used only when appropriate. For performance critical - * operations this check should be disabled. - *

- * Default: {@code false} since 4.4 - *

- * - * @deprecated (4.4) Use {@link - * com.tracelytics.ext.apache.http.impl.conn.PoolingHttpClientConnectionManager#getValidateAfterInactivity()} - */ - @Deprecated - public boolean isStaleConnectionCheckEnabled() { - return staleConnectionCheckEnabled; - } - - /** - * Determines the name of the cookie specification to be used for HTTP state - * management. - *

- * Default: {@code null} - *

- */ - public String getCookieSpec() { - return cookieSpec; - } - - /** - * Determines whether redirects should be handled automatically. - *

- * Default: {@code true} - *

- */ - public boolean isRedirectsEnabled() { - return redirectsEnabled; - } - - /** - * Determines whether relative redirects should be rejected. HTTP specification - * requires the location value be an absolute URI. - *

- * Default: {@code true} - *

- */ - public boolean isRelativeRedirectsAllowed() { - return relativeRedirectsAllowed; - } - - /** - * Determines whether circular redirects (redirects to the same location) should - * be allowed. The HTTP spec is not sufficiently clear whether circular redirects - * are permitted, therefore optionally they can be enabled - *

- * Default: {@code false} - *

- */ - public boolean isCircularRedirectsAllowed() { - return circularRedirectsAllowed; - } - - /** - * Returns the maximum number of redirects to be followed. The limit on number - * of redirects is intended to prevent infinite loops. - *

- * Default: {@code 50} - *

- */ - public int getMaxRedirects() { - return maxRedirects; - } - - /** - * Determines whether authentication should be handled automatically. - *

- * Default: {@code true} - *

- */ - public boolean isAuthenticationEnabled() { - return authenticationEnabled; - } - - /** - * Determines the order of preference for supported authentication schemes - * when authenticating with the target host. - *

- * Default: {@code null} - *

- */ - public Collection getTargetPreferredAuthSchemes() { - return targetPreferredAuthSchemes; - } - - /** - * Determines the order of preference for supported authentication schemes - * when authenticating with the proxy host. - *

- * Default: {@code null} - *

- */ - public Collection getProxyPreferredAuthSchemes() { - return proxyPreferredAuthSchemes; - } - - /** - * Returns the timeout in milliseconds used when requesting a connection - * from the connection manager. A timeout value of zero is interpreted - * as an infinite timeout. - *

- * A timeout value of zero is interpreted as an infinite timeout. - * A negative value is interpreted as undefined (system default). - *

- *

- * Default: {@code -1} - *

- */ - public int getConnectionRequestTimeout() { - return connectionRequestTimeout; - } - - /** - * Determines the timeout in milliseconds until a connection is established. - * A timeout value of zero is interpreted as an infinite timeout. - *

- * A timeout value of zero is interpreted as an infinite timeout. - * A negative value is interpreted as undefined (system default). - *

- *

- * Default: {@code -1} - *

- */ - public int getConnectTimeout() { - return connectTimeout; - } - - /** - * Defines the socket timeout ({@code SO_TIMEOUT}) in milliseconds, - * which is the timeout for waiting for data or, put differently, - * a maximum period inactivity between two consecutive data packets). - *

- * A timeout value of zero is interpreted as an infinite timeout. - * A negative value is interpreted as undefined (system default). - *

- *

- * Default: {@code -1} - *

- */ - public int getSocketTimeout() { - return socketTimeout; - } - - /** - * Determines whether compressed entities should be decompressed automatically. - *

- * Default: {@code true} - *

- * - * @since 4.4 - */ - public boolean isDecompressionEnabled() { - return decompressionEnabled; - } - - @Override - protected RequestConfig clone() throws CloneNotSupportedException { - return (RequestConfig) super.clone(); - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("["); - builder.append("expectContinueEnabled=").append(expectContinueEnabled); - builder.append(", proxy=").append(proxy); - builder.append(", localAddress=").append(localAddress); - builder.append(", cookieSpec=").append(cookieSpec); - builder.append(", redirectsEnabled=").append(redirectsEnabled); - builder.append(", relativeRedirectsAllowed=").append(relativeRedirectsAllowed); - builder.append(", maxRedirects=").append(maxRedirects); - builder.append(", circularRedirectsAllowed=").append(circularRedirectsAllowed); - builder.append(", authenticationEnabled=").append(authenticationEnabled); - builder.append(", targetPreferredAuthSchemes=").append(targetPreferredAuthSchemes); - builder.append(", proxyPreferredAuthSchemes=").append(proxyPreferredAuthSchemes); - builder.append(", connectionRequestTimeout=").append(connectionRequestTimeout); - builder.append(", connectTimeout=").append(connectTimeout); - builder.append(", socketTimeout=").append(socketTimeout); - builder.append(", decompressionEnabled=").append(decompressionEnabled); - builder.append("]"); - return builder.toString(); - } - - public static RequestConfig.Builder custom() { - return new Builder(); - } - - @SuppressWarnings("deprecation") - public static RequestConfig.Builder copy(final RequestConfig config) { - return new Builder() - .setExpectContinueEnabled(config.isExpectContinueEnabled()) - .setProxy(config.getProxy()) - .setLocalAddress(config.getLocalAddress()) - .setStaleConnectionCheckEnabled(config.isStaleConnectionCheckEnabled()) - .setCookieSpec(config.getCookieSpec()) - .setRedirectsEnabled(config.isRedirectsEnabled()) - .setRelativeRedirectsAllowed(config.isRelativeRedirectsAllowed()) - .setCircularRedirectsAllowed(config.isCircularRedirectsAllowed()) - .setMaxRedirects(config.getMaxRedirects()) - .setAuthenticationEnabled(config.isAuthenticationEnabled()) - .setTargetPreferredAuthSchemes(config.getTargetPreferredAuthSchemes()) - .setProxyPreferredAuthSchemes(config.getProxyPreferredAuthSchemes()) - .setConnectionRequestTimeout(config.getConnectionRequestTimeout()) - .setConnectTimeout(config.getConnectTimeout()) - .setSocketTimeout(config.getSocketTimeout()) - .setDecompressionEnabled(config.isDecompressionEnabled()); - } - - public static class Builder { - - 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; - private Collection targetPreferredAuthSchemes; - private Collection proxyPreferredAuthSchemes; - private int connectionRequestTimeout; - private int connectTimeout; - private int socketTimeout; - private boolean decompressionEnabled; - - Builder() { - super(); - this.staleConnectionCheckEnabled = false; - this.redirectsEnabled = true; - this.maxRedirects = 50; - this.relativeRedirectsAllowed = true; - this.authenticationEnabled = true; - this.connectionRequestTimeout = -1; - this.connectTimeout = -1; - this.socketTimeout = -1; - this.decompressionEnabled = true; - } - - public Builder setExpectContinueEnabled(final boolean expectContinueEnabled) { - this.expectContinueEnabled = expectContinueEnabled; - return this; - } - - public Builder setProxy(final HttpHost proxy) { - this.proxy = proxy; - return this; - } - - public Builder setLocalAddress(final InetAddress localAddress) { - this.localAddress = localAddress; - return this; - } - - /** - * @deprecated (4.4) Use {@link - * com.tracelytics.ext.apache.http.impl.conn.PoolingHttpClientConnectionManager#setValidateAfterInactivity(int)} - */ - @Deprecated - public Builder setStaleConnectionCheckEnabled(final boolean staleConnectionCheckEnabled) { - this.staleConnectionCheckEnabled = staleConnectionCheckEnabled; - return this; - } - - public Builder setCookieSpec(final String cookieSpec) { - this.cookieSpec = cookieSpec; - return this; - } - - public Builder setRedirectsEnabled(final boolean redirectsEnabled) { - this.redirectsEnabled = redirectsEnabled; - return this; - } - - public Builder setRelativeRedirectsAllowed(final boolean relativeRedirectsAllowed) { - this.relativeRedirectsAllowed = relativeRedirectsAllowed; - return this; - } - - public Builder setCircularRedirectsAllowed(final boolean circularRedirectsAllowed) { - this.circularRedirectsAllowed = circularRedirectsAllowed; - return this; - } - - public Builder setMaxRedirects(final int maxRedirects) { - this.maxRedirects = maxRedirects; - return this; - } - - public Builder setAuthenticationEnabled(final boolean authenticationEnabled) { - this.authenticationEnabled = authenticationEnabled; - return this; - } - - public Builder setTargetPreferredAuthSchemes(final Collection targetPreferredAuthSchemes) { - this.targetPreferredAuthSchemes = targetPreferredAuthSchemes; - return this; - } - - public Builder setProxyPreferredAuthSchemes(final Collection proxyPreferredAuthSchemes) { - this.proxyPreferredAuthSchemes = proxyPreferredAuthSchemes; - return this; - } - - public Builder setConnectionRequestTimeout(final int connectionRequestTimeout) { - this.connectionRequestTimeout = connectionRequestTimeout; - return this; - } - - public Builder setConnectTimeout(final int connectTimeout) { - this.connectTimeout = connectTimeout; - return this; - } - - public Builder setSocketTimeout(final int socketTimeout) { - this.socketTimeout = socketTimeout; - return this; - } - - public Builder setDecompressionEnabled(final boolean decompressionEnabled) { - this.decompressionEnabled = decompressionEnabled; - return this; - } - - public RequestConfig build() { - return new RequestConfig( - expectContinueEnabled, - proxy, - localAddress, - staleConnectionCheckEnabled, - cookieSpec, - redirectsEnabled, - relativeRedirectsAllowed, - circularRedirectsAllowed, - maxRedirects, - authenticationEnabled, - targetPreferredAuthSchemes, - proxyPreferredAuthSchemes, - connectionRequestTimeout, - connectTimeout, - socketTimeout, - decompressionEnabled); - } - - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/config/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/config/package-info.java deleted file mode 100644 index 912e79f5..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/config/package-info.java +++ /dev/null @@ -1,31 +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 - * . - * - */ - -/** - * Client configuration APIs. - */ -package com.tracelytics.ext.apache.http.client.config; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/DecompressingEntity.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/DecompressingEntity.java deleted file mode 100644 index f7e9a83b..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/DecompressingEntity.java +++ /dev/null @@ -1,114 +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 com.tracelytics.ext.apache.http.client.entity; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.entity.HttpEntityWrapper; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Common base class for decompressing {@link HttpEntity} implementations. - * - * @since 4.4 - */ -public class DecompressingEntity extends HttpEntityWrapper { - - /** - * Default buffer size. - */ - private static final int BUFFER_SIZE = 1024 * 2; - - private final InputStreamFactory inputStreamFactory; - /** - * {@link #getContent()} method must return the same {@link InputStream} - * instance when DecompressingEntity is wrapping a streaming entity. - */ - private InputStream content; - - /** - * Creates a new {@link DecompressingEntity}. - * - * @param wrapped the non-null {@link HttpEntity} to be wrapped - * @param inputStreamFactory factory to create decompressing stream. - */ - public DecompressingEntity( - final HttpEntity wrapped, - final InputStreamFactory inputStreamFactory) { - super(wrapped); - this.inputStreamFactory = inputStreamFactory; - } - - private InputStream getDecompressingStream() throws IOException { - final InputStream in = wrappedEntity.getContent(); - return new LazyDecompressingInputStream(in, inputStreamFactory); - } - - @Override - public InputStream getContent() throws IOException { - if (wrappedEntity.isStreaming()) { - if (content == null) { - content = getDecompressingStream(); - } - return content; - } else { - return getDecompressingStream(); - } - } - - @Override - public void writeTo(final OutputStream outstream) throws IOException { - Args.notNull(outstream, "Output stream"); - final InputStream instream = getContent(); - try { - final byte[] buffer = new byte[BUFFER_SIZE]; - int l; - while ((l = instream.read(buffer)) != -1) { - outstream.write(buffer, 0, l); - } - } finally { - instream.close(); - } - } - - @Override - public Header getContentEncoding() { - /* Content encoding is now 'identity' */ - return null; - } - - @Override - public long getContentLength() { - /* length of decompressed content is not known */ - return -1; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/DeflateDecompressingEntity.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/DeflateDecompressingEntity.java deleted file mode 100644 index e47bd822..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/DeflateDecompressingEntity.java +++ /dev/null @@ -1,70 +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 com.tracelytics.ext.apache.http.client.entity; - -import java.io.IOException; -import java.io.InputStream; - -import com.tracelytics.ext.apache.http.HttpEntity; - -/** - * {@link com.tracelytics.ext.apache.http.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 - * {@code deflate} stream as defined in RFC1951 should be used - * (or maybe they did that since that's how IE behaves?). It's confusing - * that {@code deflate} in HTTP 1.1 means {@code zlib} streams - * rather than {@code deflate} streams. We handle both types in here, - * since that's what is seen on the internet. Moral - prefer - * {@code gzip}! - * - * @see GzipDecompressingEntity - * - * @since 4.1 - */ -public class DeflateDecompressingEntity extends DecompressingEntity { - - /** - * Creates a new {@link DeflateDecompressingEntity} which will wrap the specified - * {@link HttpEntity}. - * - * @param entity - * a non-null {@link HttpEntity} to be wrapped - */ - public DeflateDecompressingEntity(final HttpEntity entity) { - super(entity, new InputStreamFactory() { - - @Override - public InputStream create(final InputStream instream) throws IOException { - return new DeflateInputStream(instream); - } - - }); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/DeflateInputStream.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/DeflateInputStream.java deleted file mode 100644 index 39913bce..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/DeflateInputStream.java +++ /dev/null @@ -1,229 +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 com.tracelytics.ext.apache.http.client.entity; - -import java.io.IOException; -import java.io.InputStream; -import java.io.PushbackInputStream; -import java.util.zip.DataFormatException; -import java.util.zip.Inflater; -import java.util.zip.InflaterInputStream; - -/** Deflate input stream. This class includes logic needed for various Rfc's in order -* to reasonably implement the "deflate" compression style. -*/ -public class DeflateInputStream extends InputStream -{ - private InputStream sourceStream; - - public DeflateInputStream(final InputStream wrapped) - throws IOException - { - /* - * A zlib stream will have a header. - * - * CMF | FLG [| DICTID ] | ...compressed data | ADLER32 | - * - * * CMF is one byte. - * - * * FLG is one byte. - * - * * DICTID is four bytes, and only present if FLG.FDICT is set. - * - * Sniff the content. Does it look like a zlib stream, with a CMF, etc? c.f. RFC1950, - * section 2.2. http://tools.ietf.org/html/rfc1950#page-4 - * - * We need to see if it looks like a proper zlib stream, or whether it is just a deflate - * stream. RFC2616 calls zlib streams deflate. Confusing, isn't it? That's why some servers - * implement deflate Content-Encoding using deflate streams, rather than zlib streams. - * - * We could start looking at the bytes, but to be honest, someone else has already read - * the RFCs and implemented that for us. So we'll just use the JDK libraries and exception - * handling to do this. If that proves slow, then we could potentially change this to check - * the first byte - does it look like a CMF? What about the second byte - does it look like - * a FLG, etc. - */ - - /* We read a small buffer to sniff the content. */ - final byte[] peeked = new byte[6]; - - final PushbackInputStream pushback = new PushbackInputStream(wrapped, peeked.length); - - final int headerLength = pushback.read(peeked); - - if (headerLength == -1) { - throw new IOException("Unable to read the response"); - } - - /* We try to read the first uncompressed byte. */ - final byte[] dummy = new byte[1]; - - final Inflater inf = new Inflater(); - - try { - int n; - while ((n = inf.inflate(dummy)) == 0) { - if (inf.finished()) { - - /* Not expecting this, so fail loudly. */ - throw new IOException("Unable to read the response"); - } - - if (inf.needsDictionary()) { - - /* Need dictionary - then it must be zlib stream with DICTID part? */ - break; - } - - if (inf.needsInput()) { - inf.setInput(peeked); - } - } - - if (n == -1) { - throw new IOException("Unable to read the response"); - } - - /* - * We read something without a problem, so it's a valid zlib stream. Just need to reset - * and return an unused InputStream now. - */ - pushback.unread(peeked, 0, headerLength); - sourceStream = new DeflateStream(pushback, new Inflater()); - } catch (final DataFormatException e) { - - /* Presume that it's an RFC1951 deflate stream rather than RFC1950 zlib stream and try - * again. */ - pushback.unread(peeked, 0, headerLength); - sourceStream = new DeflateStream(pushback, new Inflater(true)); - } finally { - inf.end(); - } - - } - - /** Read a byte. - */ - @Override - public int read() - throws IOException - { - return sourceStream.read(); - } - - /** Read lots of bytes. - */ - @Override - public int read(final byte[] b) - throws IOException - { - return sourceStream.read(b); - } - - /** Read lots of specific bytes. - */ - @Override - public int read(final byte[] b, final int off, final int len) - throws IOException - { - return sourceStream.read(b,off,len); - } - - /** Skip - */ - @Override - public long skip(final long n) - throws IOException - { - return sourceStream.skip(n); - } - - /** Get available. - */ - @Override - public int available() - throws IOException - { - return sourceStream.available(); - } - - /** Mark. - */ - @Override - public void mark(final int readLimit) - { - sourceStream.mark(readLimit); - } - - /** Reset. - */ - @Override - public void reset() - throws IOException - { - sourceStream.reset(); - } - - /** Check if mark is supported. - */ - @Override - public boolean markSupported() - { - return sourceStream.markSupported(); - } - - /** Close. - */ - @Override - public void close() - throws IOException - { - sourceStream.close(); - } - - static class DeflateStream extends InflaterInputStream { - - private boolean closed = false; - - public DeflateStream(final InputStream in, final Inflater inflater) { - super(in, inflater); - } - - @Override - public void close() throws IOException { - if (closed) { - return; - } - closed = true; - inf.end(); - super.close(); - } - - } - -} - diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/EntityBuilder.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/EntityBuilder.java deleted file mode 100644 index 738df53c..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/EntityBuilder.java +++ /dev/null @@ -1,343 +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 com.tracelytics.ext.apache.http.client.entity; - -import java.io.File; -import java.io.InputStream; -import java.io.Serializable; -import java.util.Arrays; -import java.util.List; - -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.NameValuePair; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.entity.AbstractHttpEntity; -import com.tracelytics.ext.apache.http.entity.BasicHttpEntity; -import com.tracelytics.ext.apache.http.entity.ByteArrayEntity; -import com.tracelytics.ext.apache.http.entity.ContentType; -import com.tracelytics.ext.apache.http.entity.FileEntity; -import com.tracelytics.ext.apache.http.entity.InputStreamEntity; -import com.tracelytics.ext.apache.http.entity.SerializableEntity; -import com.tracelytics.ext.apache.http.entity.StringEntity; - -/** - * Builder for {@link HttpEntity} instances. - *

- * Several setter methods of this builder are mutually exclusive. In case of multiple invocations - * of the following methods only the last one will have effect: - *

- *
    - *
  • {@link #setText(String)}
  • - *
  • {@link #setBinary(byte[])}
  • - *
  • {@link #setStream(java.io.InputStream)}
  • - *
  • {@link #setSerializable(java.io.Serializable)}
  • - *
  • {@link #setParameters(java.util.List)}
  • - *
  • {@link #setParameters(com.tracelytics.ext.apache.http.NameValuePair...)}
  • - *
  • {@link #setFile(java.io.File)}
  • - *
- * - * @since 4.3 - */ -@NotThreadSafe -public class EntityBuilder { - - private String text; - private byte[] binary; - private InputStream stream; - private List parameters; - private Serializable serializable; - private File file; - private ContentType contentType; - private String contentEncoding; - private boolean chunked; - private boolean gzipCompress; - - EntityBuilder() { - super(); - } - - public static EntityBuilder create() { - return new EntityBuilder(); - } - - private void clearContent() { - this.text = null; - this.binary = null; - this.stream = null; - this.parameters = null; - this.serializable = null; - this.file = null; - } - - /** - * Returns entity content as a string if set using {@link #setText(String)} method. - */ - public String getText() { - return text; - } - - /** - * Sets entity content as a string. This method is mutually exclusive with - * {@link #setBinary(byte[])}, - * {@link #setStream(java.io.InputStream)} , - * {@link #setSerializable(java.io.Serializable)} , - * {@link #setParameters(java.util.List)}, - * {@link #setParameters(com.tracelytics.ext.apache.http.NameValuePair...)} - * {@link #setFile(java.io.File)} methods. - */ - public EntityBuilder setText(final String text) { - clearContent(); - this.text = text; - return this; - } - - /** - * Returns entity content as a byte array if set using - * {@link #setBinary(byte[])} method. - */ - public byte[] getBinary() { - return binary; - } - - /** - * Sets entity content as a byte array. This method is mutually exclusive with - * {@link #setText(String)}, - * {@link #setStream(java.io.InputStream)} , - * {@link #setSerializable(java.io.Serializable)} , - * {@link #setParameters(java.util.List)}, - * {@link #setParameters(com.tracelytics.ext.apache.http.NameValuePair...)} - * {@link #setFile(java.io.File)} methods. - */ - public EntityBuilder setBinary(final byte[] binary) { - clearContent(); - this.binary = binary; - return this; - } - - /** - * Returns entity content as a {@link InputStream} if set using - * {@link #setStream(java.io.InputStream)} method. - */ - public InputStream getStream() { - return stream; - } - - /** - * Sets entity content as a {@link InputStream}. This method is mutually exclusive with - * {@link #setText(String)}, - * {@link #setBinary(byte[])}, - * {@link #setSerializable(java.io.Serializable)} , - * {@link #setParameters(java.util.List)}, - * {@link #setParameters(com.tracelytics.ext.apache.http.NameValuePair...)} - * {@link #setFile(java.io.File)} methods. - */ - public EntityBuilder setStream(final InputStream stream) { - clearContent(); - this.stream = stream; - return this; - } - - /** - * Returns entity content as a parameter list if set using - * {@link #setParameters(java.util.List)} or - * {@link #setParameters(com.tracelytics.ext.apache.http.NameValuePair...)} methods. - */ - public List getParameters() { - return parameters; - } - - /** - * Sets entity content as a parameter list. This method is mutually exclusive with - * {@link #setText(String)}, - * {@link #setBinary(byte[])}, - * {@link #setStream(java.io.InputStream)} , - * {@link #setSerializable(java.io.Serializable)} , - * {@link #setFile(java.io.File)} methods. - */ - public EntityBuilder setParameters(final List parameters) { - clearContent(); - this.parameters = parameters; - return this; - } - - /** - * Sets entity content as a parameter list. This method is mutually exclusive with - * {@link #setText(String)}, - * {@link #setBinary(byte[])}, - * {@link #setStream(java.io.InputStream)} , - * {@link #setSerializable(java.io.Serializable)} , - * {@link #setFile(java.io.File)} methods. - */ - public EntityBuilder setParameters(final NameValuePair... parameters) { - return setParameters(Arrays.asList(parameters)); - } - - /** - * Returns entity content as a {@link Serializable} if set using - * {@link #setSerializable(java.io.Serializable)} method. - */ - public Serializable getSerializable() { - return serializable; - } - - /** - * Sets entity content as a {@link Serializable}. This method is mutually exclusive with - * {@link #setText(String)}, - * {@link #setBinary(byte[])}, - * {@link #setStream(java.io.InputStream)} , - * {@link #setParameters(java.util.List)}, - * {@link #setParameters(com.tracelytics.ext.apache.http.NameValuePair...)} - * {@link #setFile(java.io.File)} methods. - */ - public EntityBuilder setSerializable(final Serializable serializable) { - clearContent(); - this.serializable = serializable; - return this; - } - - /** - * Returns entity content as a {@link File} if set using - * {@link #setFile(java.io.File)} method. - */ - public File getFile() { - return file; - } - - /** - * Sets entity content as a {@link File}. This method is mutually exclusive with - * {@link #setText(String)}, - * {@link #setBinary(byte[])}, - * {@link #setStream(java.io.InputStream)} , - * {@link #setParameters(java.util.List)}, - * {@link #setParameters(com.tracelytics.ext.apache.http.NameValuePair...)} - * {@link #setSerializable(java.io.Serializable)} methods. - */ - public EntityBuilder setFile(final File file) { - clearContent(); - this.file = file; - return this; - } - - /** - * Returns {@link ContentType} of the entity, if set. - */ - public ContentType getContentType() { - return contentType; - } - - /** - * Sets {@link ContentType} of the entity. - */ - public EntityBuilder setContentType(final ContentType contentType) { - this.contentType = contentType; - return this; - } - - /** - * Returns content encoding of the entity, if set. - */ - public String getContentEncoding() { - return contentEncoding; - } - - /** - * Sets content encoding of the entity. - */ - public EntityBuilder setContentEncoding(final String contentEncoding) { - this.contentEncoding = contentEncoding; - return this; - } - - /** - * Returns {@code true} if entity is to be chunk coded, {@code false} otherwise. - */ - public boolean isChunked() { - return chunked; - } - - /** - * Makes entity chunk coded. - */ - public EntityBuilder chunked() { - this.chunked = true; - return this; - } - - /** - * Returns {@code true} if entity is to be GZIP compressed, {@code false} otherwise. - */ - public boolean isGzipCompress() { - return gzipCompress; - } - - /** - * Makes entity GZIP compressed. - */ - public EntityBuilder gzipCompress() { - this.gzipCompress = true; - return this; - } - - private ContentType getContentOrDefault(final ContentType def) { - return this.contentType != null ? this.contentType : def; - } - - /** - * Creates new instance of {@link HttpEntity} based on the current state. - */ - public HttpEntity build() { - final AbstractHttpEntity e; - if (this.text != null) { - e = new StringEntity(this.text, getContentOrDefault(ContentType.DEFAULT_TEXT)); - } else if (this.binary != null) { - e = new ByteArrayEntity(this.binary, getContentOrDefault(ContentType.DEFAULT_BINARY)); - } else if (this.stream != null) { - e = new InputStreamEntity(this.stream, -1, getContentOrDefault(ContentType.DEFAULT_BINARY)); - } else if (this.parameters != null) { - e = new UrlEncodedFormEntity(this.parameters, - this.contentType != null ? this.contentType.getCharset() : null); - } else if (this.serializable != null) { - e = new SerializableEntity(this.serializable); - e.setContentType(ContentType.DEFAULT_BINARY.toString()); - } else if (this.file != null) { - e = new FileEntity(this.file, getContentOrDefault(ContentType.DEFAULT_BINARY)); - } else { - e = new BasicHttpEntity(); - } - if (e.getContentType() != null && this.contentType != null) { - e.setContentType(this.contentType.toString()); - } - e.setContentEncoding(this.contentEncoding); - e.setChunked(this.chunked); - if (this.gzipCompress) { - return new GzipCompressingEntity(e); - } - return e; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/GzipCompressingEntity.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/GzipCompressingEntity.java deleted file mode 100644 index 0e1ff0fc..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/GzipCompressingEntity.java +++ /dev/null @@ -1,113 +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 com.tracelytics.ext.apache.http.client.entity; - -/* - * ==================================================================== - * 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 - * . - * - */ - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.zip.GZIPOutputStream; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.entity.HttpEntityWrapper; -import com.tracelytics.ext.apache.http.message.BasicHeader; -import com.tracelytics.ext.apache.http.protocol.HTTP; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Wrapping entity that compresses content when {@link #writeTo writing}. - * - * - * @since 4.0 - */ -public class GzipCompressingEntity extends HttpEntityWrapper { - - private static final String GZIP_CODEC = "gzip"; - - public GzipCompressingEntity(final HttpEntity entity) { - super(entity); - } - - @Override - public Header getContentEncoding() { - return new BasicHeader(HTTP.CONTENT_ENCODING, GZIP_CODEC); - } - - @Override - public long getContentLength() { - return -1; - } - - @Override - public boolean isChunked() { - // force content chunking - return true; - } - - @Override - public InputStream getContent() throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public void writeTo(final OutputStream outstream) throws IOException { - Args.notNull(outstream, "Output stream"); - final GZIPOutputStream gzip = new GZIPOutputStream(outstream); - wrappedEntity.writeTo(gzip); - // Only close output stream if the wrapped entity has been - // successfully written out - gzip.close(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/GzipDecompressingEntity.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/GzipDecompressingEntity.java deleted file mode 100644 index 95a75e5e..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/GzipDecompressingEntity.java +++ /dev/null @@ -1,61 +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 com.tracelytics.ext.apache.http.client.entity; - -import java.io.IOException; -import java.io.InputStream; -import java.util.zip.GZIPInputStream; - -import com.tracelytics.ext.apache.http.HttpEntity; - -/** - * {@link com.tracelytics.ext.apache.http.entity.HttpEntityWrapper} for handling gzip - * Content Coded responses. - * - * @since 4.1 - */ -public class GzipDecompressingEntity extends DecompressingEntity { - - /** - * Creates a new {@link GzipDecompressingEntity} which will wrap the specified - * {@link HttpEntity}. - * - * @param entity - * the non-null {@link HttpEntity} to be wrapped - */ - public GzipDecompressingEntity(final HttpEntity entity) { - super(entity, new InputStreamFactory() { - - @Override - public InputStream create(final InputStream instream) throws IOException { - return new GZIPInputStream(instream); - } - - }); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/InputStreamFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/InputStreamFactory.java deleted file mode 100644 index 92d9db8f..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/InputStreamFactory.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 com.tracelytics.ext.apache.http.client.entity; - -import java.io.IOException; -import java.io.InputStream; - -/** - * Factory for decorated {@link java.io.InputStream}s. - * - * @since 4.4 - */ -public interface InputStreamFactory { - - InputStream create(InputStream instream) throws IOException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/LazyDecompressingInputStream.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/LazyDecompressingInputStream.java deleted file mode 100644 index 640febd1..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/LazyDecompressingInputStream.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 com.tracelytics.ext.apache.http.client.entity; - -import java.io.IOException; -import java.io.InputStream; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; - -/** - * Lazy init InputStream wrapper. - */ -@NotThreadSafe -class LazyDecompressingInputStream extends InputStream { - - private final InputStream wrappedStream; - private final InputStreamFactory inputStreamFactory; - - private InputStream wrapperStream; - - public LazyDecompressingInputStream( - final InputStream wrappedStream, - final InputStreamFactory inputStreamFactory) { - this.wrappedStream = wrappedStream; - this.inputStreamFactory = inputStreamFactory; - } - - private void initWrapper() throws IOException { - if (wrapperStream == null) { - wrapperStream = inputStreamFactory.create(wrappedStream); - } - } - - @Override - public int read() throws IOException { - initWrapper(); - return wrapperStream.read(); - } - - @Override - public int read(final byte[] b) throws IOException { - initWrapper(); - return wrapperStream.read(b); - } - - @Override - public int read(final byte[] b, final int off, final int len) throws IOException { - initWrapper(); - return wrapperStream.read(b, off, len); - } - - @Override - public long skip(final long n) throws IOException { - initWrapper(); - return wrapperStream.skip(n); - } - - @Override - public boolean markSupported() { - return false; - } - - @Override - public int available() throws IOException { - initWrapper(); - return wrapperStream.available(); - } - - @Override - public void close() throws IOException { - try { - if (wrapperStream != null) { - wrapperStream.close(); - } - } finally { - wrappedStream.close(); - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/UrlEncodedFormEntity.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/UrlEncodedFormEntity.java deleted file mode 100644 index 3be3bdb0..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/UrlEncodedFormEntity.java +++ /dev/null @@ -1,108 +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 com.tracelytics.ext.apache.http.client.entity; - -import java.io.UnsupportedEncodingException; -import java.nio.charset.Charset; -import java.util.List; - -import com.tracelytics.ext.apache.http.NameValuePair; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.entity.ContentType; -import com.tracelytics.ext.apache.http.entity.StringEntity; -import com.tracelytics.ext.apache.http.protocol.HTTP; - -import com.tracelytics.ext.apache.http.client.utils.URLEncodedUtils; - -/** - * An entity composed of a list of url-encoded pairs. - * This is typically useful while sending an HTTP POST request. - * - * @since 4.0 - */ -@NotThreadSafe // AbstractHttpEntity is not thread-safe -public class UrlEncodedFormEntity extends StringEntity { - - /** - * Constructs a new {@link UrlEncodedFormEntity} with the list - * of parameters in the specified encoding. - * - * @param parameters list of name/value pairs - * @param charset encoding the name/value pairs be encoded with - * @throws UnsupportedEncodingException if the encoding isn't supported - */ - public UrlEncodedFormEntity ( - final List parameters, - final String charset) throws UnsupportedEncodingException { - super(URLEncodedUtils.format(parameters, - charset != null ? charset : HTTP.DEF_CONTENT_CHARSET.name()), - ContentType.create(URLEncodedUtils.CONTENT_TYPE, charset)); - } - - /** - * Constructs a new {@link UrlEncodedFormEntity} with the list - * of parameters in the specified encoding. - * - * @param parameters iterable collection of name/value pairs - * @param charset encoding the name/value pairs be encoded with - * - * @since 4.2 - */ - public UrlEncodedFormEntity ( - final Iterable parameters, - final Charset charset) { - super(URLEncodedUtils.format(parameters, - charset != null ? charset : HTTP.DEF_CONTENT_CHARSET), - ContentType.create(URLEncodedUtils.CONTENT_TYPE, charset)); - } - - /** - * Constructs a new {@link UrlEncodedFormEntity} with the list - * of parameters with the default encoding of {@link HTTP#DEFAULT_CONTENT_CHARSET} - * - * @param parameters list of name/value pairs - * @throws UnsupportedEncodingException if the default encoding isn't supported - */ - public UrlEncodedFormEntity ( - final List parameters) throws UnsupportedEncodingException { - this(parameters, (Charset) null); - } - - /** - * Constructs a new {@link UrlEncodedFormEntity} with the list - * of parameters with the default encoding of {@link HTTP#DEFAULT_CONTENT_CHARSET} - * - * @param parameters iterable collection of name/value pairs - * - * @since 4.2 - */ - public UrlEncodedFormEntity ( - final Iterable parameters) { - this(parameters, null); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/package-info.java deleted file mode 100644 index 1bfffcb1..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/entity/package-info.java +++ /dev/null @@ -1,31 +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 - * . - * - */ - -/** - * Client specific HTTP entity implementations. - */ -package com.tracelytics.ext.apache.http.client.entity; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/AbortableHttpRequest.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/AbortableHttpRequest.java deleted file mode 100644 index 1f6aed07..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/AbortableHttpRequest.java +++ /dev/null @@ -1,82 +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 com.tracelytics.ext.apache.http.client.methods; - -import com.tracelytics.ext.apache.http.conn.ClientConnectionRequest; -import com.tracelytics.ext.apache.http.conn.ConnectionReleaseTrigger; - -import java.io.IOException; - - -/** - * Interface representing an HTTP request that can be aborted by shutting - * down the underlying HTTP connection. - * - * @since 4.0 - * - * @deprecated (4.3) use {@link HttpExecutionAware} - */ -@Deprecated -public interface AbortableHttpRequest { - - /** - * Sets the {@link com.tracelytics.ext.apache.http.conn.ClientConnectionRequest} - * callback that can be used to abort a long-lived request for a connection. - * If the request is already aborted, throws an {@link IOException}. - * - * @see com.tracelytics.ext.apache.http.conn.ClientConnectionManager - */ - void setConnectionRequest(ClientConnectionRequest connRequest) throws IOException; - - /** - * Sets the {@link ConnectionReleaseTrigger} callback that can - * be used to abort an active connection. - * Typically, this will be the - * {@link com.tracelytics.ext.apache.http.conn.ManagedClientConnection} itself. - * If the request is already aborted, throws an {@link IOException}. - */ - void setReleaseTrigger(ConnectionReleaseTrigger releaseTrigger) throws IOException; - - /** - * Aborts this http request. Any active execution of this method should - * return immediately. If the request has not started, it will abort after - * the next execution. Aborting this request will cause all subsequent - * executions with this request to fail. - * - * @see com.tracelytics.ext.apache.http.client.HttpClient#execute(HttpUriRequest) - * @see com.tracelytics.ext.apache.http.client.HttpClient#execute(com.tracelytics.ext.apache.http.HttpHost, - * com.tracelytics.ext.apache.http.HttpRequest) - * @see com.tracelytics.ext.apache.http.client.HttpClient#execute(HttpUriRequest, - * com.tracelytics.ext.apache.http.protocol.HttpContext) - * @see com.tracelytics.ext.apache.http.client.HttpClient#execute(com.tracelytics.ext.apache.http.HttpHost, - * com.tracelytics.ext.apache.http.HttpRequest, com.tracelytics.ext.apache.http.protocol.HttpContext) - */ - void abort(); - -} - diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/AbstractExecutionAwareRequest.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/AbstractExecutionAwareRequest.java deleted file mode 100644 index 3a458c19..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/AbstractExecutionAwareRequest.java +++ /dev/null @@ -1,139 +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 com.tracelytics.ext.apache.http.client.methods; - -import java.io.IOException; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; - -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.concurrent.Cancellable; -import com.tracelytics.ext.apache.http.message.AbstractHttpMessage; - -import com.tracelytics.ext.apache.http.client.utils.CloneUtils; -import com.tracelytics.ext.apache.http.conn.ClientConnectionRequest; -import com.tracelytics.ext.apache.http.conn.ConnectionReleaseTrigger; - -@SuppressWarnings("deprecation") -public abstract class AbstractExecutionAwareRequest extends AbstractHttpMessage implements - HttpExecutionAware, AbortableHttpRequest, Cloneable, HttpRequest { - - private final AtomicBoolean aborted; - private final AtomicReference cancellableRef; - - protected AbstractExecutionAwareRequest() { - super(); - this.aborted = new AtomicBoolean(false); - this.cancellableRef = new AtomicReference(null); - } - - @Override - @Deprecated - public void setConnectionRequest(final ClientConnectionRequest connRequest) { - setCancellable(new Cancellable() { - - @Override - public boolean cancel() { - connRequest.abortRequest(); - return true; - } - - }); - } - - @Override - @Deprecated - public void setReleaseTrigger(final ConnectionReleaseTrigger releaseTrigger) { - setCancellable(new Cancellable() { - - @Override - public boolean cancel() { - try { - releaseTrigger.abortConnection(); - return true; - } catch (final IOException ex) { - return false; - } - } - - }); - } - - @Override - public void abort() { - 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(); - } - - /** - * @since 4.2 - */ - @Override - public void setCancellable(final Cancellable cancellable) { - if (!this.aborted.get()) { - this.cancellableRef.set(cancellable); - } - } - - @Override - public Object clone() throws CloneNotSupportedException { - final AbstractExecutionAwareRequest clone = (AbstractExecutionAwareRequest) super.clone(); - clone.headergroup = CloneUtils.cloneObject(this.headergroup); - clone.params = CloneUtils.cloneObject(this.params); - return clone; - } - - /** - * @since 4.2 - */ - public void completed() { - this.cancellableRef.set(null); - } - - /** - * Resets internal state of the request making it reusable. - * - * @since 4.2 - */ - public void reset() { - final Cancellable cancellable = this.cancellableRef.getAndSet(null); - if (cancellable != null) { - cancellable.cancel(); - } - this.aborted.set(false); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/CloseableHttpResponse.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/CloseableHttpResponse.java deleted file mode 100644 index e91145f6..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/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 com.tracelytics.ext.apache.http.client.methods; - -import java.io.Closeable; - -import com.tracelytics.ext.apache.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/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/Configurable.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/Configurable.java deleted file mode 100644 index 61970171..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/Configurable.java +++ /dev/null @@ -1,44 +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 com.tracelytics.ext.apache.http.client.methods; - -import com.tracelytics.ext.apache.http.client.config.RequestConfig; - -/** - * Configuration interface for HTTP requests. - * - * @since 4.3 - */ -public interface Configurable { - - /** - * Returns actual request configuration. - */ - RequestConfig getConfig(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpDelete.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpDelete.java deleted file mode 100644 index 20466042..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpDelete.java +++ /dev/null @@ -1,77 +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 com.tracelytics.ext.apache.http.client.methods; - -import java.net.URI; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; - -/** - * HTTP DELETE method - *

- * The HTTP DELETE method is defined in section 9.7 of - * RFC2616: - *

- * The DELETE method requests that the origin server delete the resource - * identified by the Request-URI. [...] The client cannot - * be guaranteed that the operation has been carried out, even if the - * status code returned from the origin server indicates that the action - * has been completed successfully. - *
- * - * @since 4.0 - */ -@NotThreadSafe // HttpRequestBase is @NotThreadSafe -public class HttpDelete extends HttpRequestBase { - - public final static String METHOD_NAME = "DELETE"; - - - public HttpDelete() { - super(); - } - - public HttpDelete(final URI uri) { - super(); - setURI(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; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpEntityEnclosingRequestBase.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpEntityEnclosingRequestBase.java deleted file mode 100644 index 1d544563..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpEntityEnclosingRequestBase.java +++ /dev/null @@ -1,80 +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 com.tracelytics.ext.apache.http.client.methods; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpEntityEnclosingRequest; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.protocol.HTTP; - -import com.tracelytics.ext.apache.http.client.utils.CloneUtils; - -/** - * Basic implementation of an entity enclosing HTTP request - * that can be modified - * - * @since 4.0 - */ -@NotThreadSafe // HttpRequestBase is @NotThreadSafe -public abstract class HttpEntityEnclosingRequestBase - extends HttpRequestBase implements HttpEntityEnclosingRequest { - - private HttpEntity entity; - - public HttpEntityEnclosingRequestBase() { - super(); - } - - @Override - public HttpEntity getEntity() { - return this.entity; - } - - @Override - public void setEntity(final HttpEntity entity) { - this.entity = entity; - } - - @Override - public boolean expectContinue() { - final Header expect = getFirstHeader(HTTP.EXPECT_DIRECTIVE); - return expect != null && HTTP.EXPECT_CONTINUE.equalsIgnoreCase(expect.getValue()); - } - - @Override - public Object clone() throws CloneNotSupportedException { - final HttpEntityEnclosingRequestBase clone = - (HttpEntityEnclosingRequestBase) super.clone(); - if (this.entity != null) { - clone.entity = CloneUtils.cloneObject(this.entity); - } - return clone; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpExecutionAware.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpExecutionAware.java deleted file mode 100644 index 89d92d96..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpExecutionAware.java +++ /dev/null @@ -1,48 +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 com.tracelytics.ext.apache.http.client.methods; - -import com.tracelytics.ext.apache.http.concurrent.Cancellable; - -/** - * Interface to be implemented by any object that wishes to be notified of - * blocking I/O operations that could be cancelled. - * - * @since 4.3 - */ -public interface HttpExecutionAware { - - boolean isAborted(); - - /** - * Sets {@link Cancellable} for the ongoing operation. - */ - void setCancellable(Cancellable cancellable); - -} - diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpGet.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpGet.java deleted file mode 100644 index 261bdd31..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpGet.java +++ /dev/null @@ -1,77 +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 com.tracelytics.ext.apache.http.client.methods; - -import java.net.URI; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; - -/** - * HTTP GET method. - *

- * The HTTP GET method is defined in section 9.3 of - * RFC2616: - *

- *
- * The GET method means retrieve whatever information (in the form of an - * entity) is identified by the Request-URI. If the Request-URI refers - * to a data-producing process, it is the produced data which shall be - * returned as the entity in the response and not the source text of the - * process, unless that text happens to be the output of the process. - *
- * - * @since 4.0 - */ -@NotThreadSafe -public class HttpGet extends HttpRequestBase { - - public final static String METHOD_NAME = "GET"; - - public HttpGet() { - super(); - } - - public HttpGet(final URI uri) { - super(); - setURI(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; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpHead.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpHead.java deleted file mode 100644 index ef0f6f62..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpHead.java +++ /dev/null @@ -1,80 +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 com.tracelytics.ext.apache.http.client.methods; - -import java.net.URI; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; - -/** - * HTTP HEAD method. - *

- * The HTTP HEAD method is defined in section 9.4 of - * RFC2616: - *

- *
- * The HEAD method is identical to GET except that the server MUST NOT - * return a message-body in the response. The metainformation contained - * in the HTTP headers in response to a HEAD request SHOULD be identical - * to the information sent in response to a GET request. This method can - * be used for obtaining metainformation about the entity implied by the - * request without transferring the entity-body itself. This method is - * often used for testing hypertext links for validity, accessibility, - * and recent modification. - *
- * - * @since 4.0 - */ -@NotThreadSafe -public class HttpHead extends HttpRequestBase { - - public final static String METHOD_NAME = "HEAD"; - - public HttpHead() { - super(); - } - - public HttpHead(final URI uri) { - super(); - setURI(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; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpOptions.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpOptions.java deleted file mode 100644 index d21911b3..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpOptions.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 com.tracelytics.ext.apache.http.client.methods; - -import java.net.URI; -import java.util.HashSet; -import java.util.Set; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HeaderElement; -import com.tracelytics.ext.apache.http.HeaderIterator; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * HTTP OPTIONS method. - *

- * The HTTP OPTIONS method is defined in section 9.2 of - * RFC2616: - *

- *
- * The OPTIONS method represents a request for information about the - * communication options available on the request/response chain - * identified by the Request-URI. This method allows the client to - * determine the options and/or requirements associated with a resource, - * or the capabilities of a server, without implying a resource action - * or initiating a resource retrieval. - *
- * - * @since 4.0 - */ -@NotThreadSafe -public class HttpOptions extends HttpRequestBase { - - public final static String METHOD_NAME = "OPTIONS"; - - public HttpOptions() { - super(); - } - - public HttpOptions(final URI uri) { - super(); - setURI(uri); - } - - /** - * @throws IllegalArgumentException if the uri is invalid. - */ - public HttpOptions(final String uri) { - super(); - setURI(URI.create(uri)); - } - - @Override - public String getMethod() { - return METHOD_NAME; - } - - public Set getAllowedMethods(final HttpResponse response) { - Args.notNull(response, "HTTP response"); - - final HeaderIterator it = response.headerIterator("Allow"); - final Set methods = new HashSet(); - while (it.hasNext()) { - final Header header = it.nextHeader(); - final HeaderElement[] elements = header.getElements(); - for (final HeaderElement element : elements) { - methods.add(element.getName()); - } - } - return methods; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpPatch.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpPatch.java deleted file mode 100644 index 80c51a7c..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpPatch.java +++ /dev/null @@ -1,77 +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 com.tracelytics.ext.apache.http.client.methods; - -import java.net.URI; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; - -/** - * HTTP PATCH method. - *

- * The HTTP PATCH method is defined in RF5789: - *

- *
The PATCH - * method requests that a set of changes described in the request entity be - * applied to the resource identified by the Request- URI. Differs from the PUT - * method in the way the server processes the enclosed entity to modify the - * resource identified by the Request-URI. In a PUT request, the enclosed entity - * origin server, and the client is requesting that the stored version be - * replaced. With PATCH, however, the enclosed entity contains a set of - * instructions describing how a resource currently residing on the origin - * server should be modified to produce a new version. - *
- * - * @since 4.2 - */ -@NotThreadSafe -public class HttpPatch extends HttpEntityEnclosingRequestBase { - - public final static String METHOD_NAME = "PATCH"; - - public HttpPatch() { - super(); - } - - public HttpPatch(final URI uri) { - super(); - setURI(uri); - } - - public HttpPatch(final String uri) { - super(); - setURI(URI.create(uri)); - } - - @Override - public String getMethod() { - return METHOD_NAME; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpPost.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpPost.java deleted file mode 100644 index be0b7781..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpPost.java +++ /dev/null @@ -1,84 +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 com.tracelytics.ext.apache.http.client.methods; - -import java.net.URI; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; - -/** - * HTTP POST method. - *

- * The HTTP POST method is defined in section 9.5 of - * RFC2616: - *

- *
- * The POST method is used to request that the origin server accept the entity - * enclosed in the request as a new subordinate of the resource identified by - * the Request-URI in the Request-Line. POST is designed to allow a uniform - * method to cover the following functions: - *
    - *
  • Annotation of existing resources
  • - *
  • Posting a message to a bulletin board, newsgroup, mailing list, or - * similar group of articles
  • - *
  • Providing a block of data, such as the result of submitting a form, - * to a data-handling process
  • - *
  • Extending a database through an append operation
  • - *
- *
- * - * @since 4.0 - */ -@NotThreadSafe -public class HttpPost extends HttpEntityEnclosingRequestBase { - - public final static String METHOD_NAME = "POST"; - - public HttpPost() { - super(); - } - - public HttpPost(final URI uri) { - super(); - setURI(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; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpPut.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpPut.java deleted file mode 100644 index 3cc9ee86..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpPut.java +++ /dev/null @@ -1,76 +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 com.tracelytics.ext.apache.http.client.methods; - -import java.net.URI; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; - -/** - * HTTP PUT method. - *

- * The HTTP PUT method is defined in section 9.6 of - * RFC2616: - *

- *
- * The PUT method requests that the enclosed entity be stored under the - * supplied Request-URI. If the Request-URI refers to an already - * existing resource, the enclosed entity SHOULD be considered as a - * modified version of the one residing on the origin server. - *
- * - * @since 4.0 - */ -@NotThreadSafe -public class HttpPut extends HttpEntityEnclosingRequestBase { - - public final static String METHOD_NAME = "PUT"; - - public HttpPut() { - super(); - } - - public HttpPut(final URI uri) { - super(); - setURI(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; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpRequestBase.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpRequestBase.java deleted file mode 100644 index 8761b206..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpRequestBase.java +++ /dev/null @@ -1,130 +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 com.tracelytics.ext.apache.http.client.methods; - -import java.net.URI; - -import com.tracelytics.ext.apache.http.ProtocolVersion; -import com.tracelytics.ext.apache.http.RequestLine; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.message.BasicRequestLine; -import com.tracelytics.ext.apache.http.params.HttpProtocolParams; - -import com.tracelytics.ext.apache.http.client.config.RequestConfig; - -/** - * Base implementation of {@link HttpUriRequest}. - * - * @since 4.0 - */ -@SuppressWarnings("deprecation") -@NotThreadSafe -public abstract class HttpRequestBase extends AbstractExecutionAwareRequest - implements HttpUriRequest, Configurable { - - 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 : HttpProtocolParams.getVersion(getParams()); - } - - /** - * 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 = getProtocolVersion(); - 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/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpRequestWrapper.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpRequestWrapper.java deleted file mode 100644 index 4153eb63..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpRequestWrapper.java +++ /dev/null @@ -1,208 +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 com.tracelytics.ext.apache.http.client.methods; - -import java.net.URI; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpEntityEnclosingRequest; -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.ProtocolVersion; -import com.tracelytics.ext.apache.http.RequestLine; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.message.AbstractHttpMessage; -import com.tracelytics.ext.apache.http.message.BasicRequestLine; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.protocol.HTTP; -import com.tracelytics.ext.apache.http.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 - */ -@SuppressWarnings("deprecation") -@NotThreadSafe -public class HttpRequestWrapper extends AbstractHttpMessage implements HttpUriRequest { - - private final HttpRequest original; - private final HttpHost target; - private final String method; - private ProtocolVersion version; - private URI uri; - - 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()); - } - - @Override - public ProtocolVersion getProtocolVersion() { - return this.version != null ? this.version : this.original.getProtocolVersion(); - } - - public void setProtocolVersion(final ProtocolVersion version) { - this.version = version; - } - - @Override - public URI getURI() { - return this.uri; - } - - public void setURI(final URI uri) { - this.uri = uri; - } - - @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() { - String requestUri = null; - if (this.uri != null) { - requestUri = this.uri.toASCIIString(); - } else { - requestUri = this.original.getRequestLine().getUri(); - } - if (requestUri == null || requestUri.isEmpty()) { - requestUri = "/"; - } - return new BasicRequestLine(this.method, requestUri, getProtocolVersion()); - } - - public HttpRequest getOriginal() { - return this.original; - } - - /** - * @since 4.4 - */ - public HttpHost getTarget() { - return target; - } - - @Override - public String toString() { - return getRequestLine() + " " + this.headergroup; - } - - static class HttpEntityEnclosingRequestWrapper extends HttpRequestWrapper - implements HttpEntityEnclosingRequest { - - private HttpEntity entity; - - HttpEntityEnclosingRequestWrapper(final HttpEntityEnclosingRequest request, final HttpHost target) { - super(request, target); - this.entity = request.getEntity(); - } - - @Override - public HttpEntity getEntity() { - return this.entity; - } - - @Override - public void setEntity(final HttpEntity entity) { - this.entity = entity; - } - - @Override - public boolean expectContinue() { - final Header expect = getFirstHeader(HTTP.EXPECT_DIRECTIVE); - return expect != null && HTTP.EXPECT_CONTINUE.equalsIgnoreCase(expect.getValue()); - } - - } - - /** - * 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) { - return wrap(request, null); - } - - - /** - * Creates a mutable wrapper of the original request. - * - * @param request original request - * @param target original target, if explicitly specified - * @return mutable request wrappering the original one - * @since 4.4 - */ - public static HttpRequestWrapper wrap(final HttpRequest request, final HttpHost target) { - Args.notNull(request, "HTTP request"); - if (request instanceof HttpEntityEnclosingRequest) { - return new HttpEntityEnclosingRequestWrapper((HttpEntityEnclosingRequest) request, target); - } else { - return new HttpRequestWrapper(request, target); - } - } - - /** - * @deprecated (4.3) use - * {@link com.tracelytics.ext.apache.http.client.config.RequestConfig}. - */ - @Override - @Deprecated - public HttpParams getParams() { - if (this.params == null) { - this.params = original.getParams().copy(); - } - return this.params; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpTrace.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpTrace.java deleted file mode 100644 index ac34be02..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpTrace.java +++ /dev/null @@ -1,79 +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 com.tracelytics.ext.apache.http.client.methods; - -import java.net.URI; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; - -/** - * HTTP TRACE method. - *

- * The HTTP TRACE method is defined in section 9.6 of - * RFC2616: - *

- *
- * The TRACE method is used to invoke a remote, application-layer loop- - * back of the request message. The final recipient of the request - * SHOULD reflect the message received back to the client as the - * entity-body of a 200 (OK) response. The final recipient is either the - * origin server or the first proxy or gateway to receive a Max-Forwards - * value of zero (0) in the request (see section 14.31). A TRACE request - * MUST NOT include an entity. - *
- * - * @since 4.0 - */ -@NotThreadSafe -public class HttpTrace extends HttpRequestBase { - - public final static String METHOD_NAME = "TRACE"; - - public HttpTrace() { - super(); - } - - public HttpTrace(final URI uri) { - super(); - setURI(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; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpUriRequest.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpUriRequest.java deleted file mode 100644 index 54b9bc13..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/HttpUriRequest.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 com.tracelytics.ext.apache.http.client.methods; - -import java.net.URI; - -import com.tracelytics.ext.apache.http.HttpRequest; - -/** - * Extended version of the {@link HttpRequest} 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(); - - /** - * Aborts execution of the request. - * - * @throws UnsupportedOperationException if the abort operation - * is not supported / cannot be implemented. - */ - void abort() throws UnsupportedOperationException; - - /** - * Tests if the request execution has been aborted. - * - * @return {@code true} if the request execution has been aborted, - * {@code false} otherwise. - */ - boolean isAborted(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/RequestBuilder.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/RequestBuilder.java deleted file mode 100644 index 8c205641..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/RequestBuilder.java +++ /dev/null @@ -1,544 +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 com.tracelytics.ext.apache.http.client.methods; - -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; - -import com.tracelytics.ext.apache.http.Consts; -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HeaderIterator; -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpEntityEnclosingRequest; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.NameValuePair; -import com.tracelytics.ext.apache.http.ProtocolVersion; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.entity.ContentType; -import com.tracelytics.ext.apache.http.message.BasicHeader; -import com.tracelytics.ext.apache.http.message.BasicNameValuePair; -import com.tracelytics.ext.apache.http.message.HeaderGroup; -import com.tracelytics.ext.apache.http.protocol.HTTP; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.client.config.RequestConfig; -import com.tracelytics.ext.apache.http.client.entity.UrlEncodedFormEntity; -import com.tracelytics.ext.apache.http.client.utils.URIBuilder; -import com.tracelytics.ext.apache.http.client.utils.URLEncodedUtils; - -/** - * Builder for {@link HttpUriRequest} instances. - *

- * Please note that this class treats parameters differently depending on composition - * of the request: if the request has a content entity explicitly set with - * {@link #setEntity(com.tracelytics.ext.apache.http.HttpEntity)} or it is not an entity enclosing method - * (such as POST or PUT), parameters will be added to the query component of the request URI. - * Otherwise, parameters will be added as a URL encoded {@link UrlEncodedFormEntity entity}. - *

- * - * @since 4.3 - */ -@NotThreadSafe -public class RequestBuilder { - - private String method; - private Charset charset; - private ProtocolVersion version; - private URI uri; - private HeaderGroup headergroup; - private HttpEntity entity; - private List parameters; - private RequestConfig config; - - RequestBuilder(final String method) { - super(); - this.charset = Consts.UTF_8; - this.method = method; - } - - RequestBuilder(final String method, final URI uri) { - super(); - this.method = method; - this.uri = uri; - } - - RequestBuilder(final String method, final String uri) { - super(); - this.method = method; - this.uri = uri != null ? URI.create(uri) : null; - } - - RequestBuilder() { - this(null); - } - - public static RequestBuilder create(final String method) { - Args.notBlank(method, "HTTP method"); - return new RequestBuilder(method); - } - - public static RequestBuilder get() { - return new RequestBuilder(HttpGet.METHOD_NAME); - } - - /** - * @since 4.4 - */ - public static RequestBuilder get(final URI uri) { - return new RequestBuilder(HttpGet.METHOD_NAME, uri); - } - - /** - * @since 4.4 - */ - public static RequestBuilder get(final String uri) { - return new RequestBuilder(HttpGet.METHOD_NAME, uri); - } - - public static RequestBuilder head() { - return new RequestBuilder(HttpHead.METHOD_NAME); - } - - /** - * @since 4.4 - */ - public static RequestBuilder head(final URI uri) { - return new RequestBuilder(HttpHead.METHOD_NAME, uri); - } - - /** - * @since 4.4 - */ - public static RequestBuilder head(final String uri) { - return new RequestBuilder(HttpHead.METHOD_NAME, uri); - } - - /** - * @since 4.4 - */ - public static RequestBuilder patch() { - return new RequestBuilder(HttpPatch.METHOD_NAME); - } - - /** - * @since 4.4 - */ - public static RequestBuilder patch(final URI uri) { - return new RequestBuilder(HttpPatch.METHOD_NAME, uri); - } - - /** - * @since 4.4 - */ - public static RequestBuilder patch(final String uri) { - return new RequestBuilder(HttpPatch.METHOD_NAME, uri); - } - - public static RequestBuilder post() { - return new RequestBuilder(HttpPost.METHOD_NAME); - } - - /** - * @since 4.4 - */ - public static RequestBuilder post(final URI uri) { - return new RequestBuilder(HttpPost.METHOD_NAME, uri); - } - - /** - * @since 4.4 - */ - public static RequestBuilder post(final String uri) { - return new RequestBuilder(HttpPost.METHOD_NAME, uri); - } - - public static RequestBuilder put() { - return new RequestBuilder(HttpPut.METHOD_NAME); - } - - /** - * @since 4.4 - */ - public static RequestBuilder put(final URI uri) { - return new RequestBuilder(HttpPut.METHOD_NAME, uri); - } - - /** - * @since 4.4 - */ - public static RequestBuilder put(final String uri) { - return new RequestBuilder(HttpPut.METHOD_NAME, uri); - } - - public static RequestBuilder delete() { - return new RequestBuilder(HttpDelete.METHOD_NAME); - } - - /** - * @since 4.4 - */ - public static RequestBuilder delete(final URI uri) { - return new RequestBuilder(HttpDelete.METHOD_NAME, uri); - } - - /** - * @since 4.4 - */ - public static RequestBuilder delete(final String uri) { - return new RequestBuilder(HttpDelete.METHOD_NAME, uri); - } - - public static RequestBuilder trace() { - return new RequestBuilder(HttpTrace.METHOD_NAME); - } - - /** - * @since 4.4 - */ - public static RequestBuilder trace(final URI uri) { - return new RequestBuilder(HttpTrace.METHOD_NAME, uri); - } - - /** - * @since 4.4 - */ - public static RequestBuilder trace(final String uri) { - return new RequestBuilder(HttpTrace.METHOD_NAME, uri); - } - - public static RequestBuilder options() { - return new RequestBuilder(HttpOptions.METHOD_NAME); - } - - /** - * @since 4.4 - */ - public static RequestBuilder options(final URI uri) { - return new RequestBuilder(HttpOptions.METHOD_NAME, uri); - } - - /** - * @since 4.4 - */ - public static RequestBuilder options(final String uri) { - return new RequestBuilder(HttpOptions.METHOD_NAME, uri); - } - - public static RequestBuilder copy(final HttpRequest request) { - Args.notNull(request, "HTTP request"); - return new RequestBuilder().doCopy(request); - } - - private RequestBuilder doCopy(final HttpRequest request) { - if (request == null) { - return this; - } - method = request.getRequestLine().getMethod(); - version = request.getRequestLine().getProtocolVersion(); - - if (headergroup == null) { - headergroup = new HeaderGroup(); - } - headergroup.clear(); - headergroup.setHeaders(request.getAllHeaders()); - - parameters = null; - entity = null; - - if (request instanceof HttpEntityEnclosingRequest) { - final HttpEntity originalEntity = ((HttpEntityEnclosingRequest) request).getEntity(); - final ContentType contentType = ContentType.get(originalEntity); - if (contentType != null && - contentType.getMimeType().equals(ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) { - try { - final List formParams = URLEncodedUtils.parse(originalEntity); - if (!formParams.isEmpty()) { - parameters = formParams; - } - } catch (IOException ignore) { - } - } else { - entity = originalEntity; - } - } - - final URI originalUri; - if (request instanceof HttpUriRequest) { - originalUri = ((HttpUriRequest) request).getURI(); - } else { - originalUri = URI.create(request.getRequestLine().getUri()); - } - - final URIBuilder uriBuilder = new URIBuilder(originalUri); - if (parameters == null) { - final List queryParams = uriBuilder.getQueryParams(); - if (!queryParams.isEmpty()) { - parameters = queryParams; - uriBuilder.clearParameters(); - } else { - parameters = null; - } - } - try { - uri = uriBuilder.build(); - } catch (URISyntaxException ex) { - // Should never happen - uri = originalUri; - } - - if (request instanceof Configurable) { - config = ((Configurable) request).getConfig(); - } else { - config = null; - } - return this; - } - - /** - * @since 4.4 - */ - public RequestBuilder setCharset(final Charset charset) { - this.charset = charset; - return this; - } - - /** - * @since 4.4 - */ - public Charset getCharset() { - return charset; - } - - public String getMethod() { - return method; - } - - public ProtocolVersion getVersion() { - return version; - } - - public RequestBuilder setVersion(final ProtocolVersion version) { - this.version = version; - return this; - } - - public URI getUri() { - return uri; - } - - public RequestBuilder setUri(final URI uri) { - this.uri = uri; - return this; - } - - public RequestBuilder setUri(final String uri) { - this.uri = uri != null ? URI.create(uri) : null; - return this; - } - - public Header getFirstHeader(final String name) { - return headergroup != null ? headergroup.getFirstHeader(name) : null; - } - - public Header getLastHeader(final String name) { - return headergroup != null ? headergroup.getLastHeader(name) : null; - } - - public Header[] getHeaders(final String name) { - return headergroup != null ? headergroup.getHeaders(name) : null; - } - - public RequestBuilder addHeader(final Header header) { - if (headergroup == null) { - headergroup = new HeaderGroup(); - } - headergroup.addHeader(header); - return this; - } - - public RequestBuilder addHeader(final String name, final String value) { - if (headergroup == null) { - headergroup = new HeaderGroup(); - } - this.headergroup.addHeader(new BasicHeader(name, value)); - return this; - } - - public RequestBuilder removeHeader(final Header header) { - if (headergroup == null) { - headergroup = new HeaderGroup(); - } - headergroup.removeHeader(header); - return this; - } - - public RequestBuilder removeHeaders(final String name) { - if (name == null || headergroup == null) { - return this; - } - for (final HeaderIterator i = headergroup.iterator(); i.hasNext(); ) { - final Header header = i.nextHeader(); - if (name.equalsIgnoreCase(header.getName())) { - i.remove(); - } - } - return this; - } - - public RequestBuilder setHeader(final Header header) { - if (headergroup == null) { - headergroup = new HeaderGroup(); - } - this.headergroup.updateHeader(header); - return this; - } - - public RequestBuilder setHeader(final String name, final String value) { - if (headergroup == null) { - headergroup = new HeaderGroup(); - } - this.headergroup.updateHeader(new BasicHeader(name, value)); - return this; - } - - public HttpEntity getEntity() { - return entity; - } - - public RequestBuilder setEntity(final HttpEntity entity) { - this.entity = entity; - return this; - } - - public List getParameters() { - return parameters != null ? new ArrayList(parameters) : - new ArrayList(); - } - - public RequestBuilder addParameter(final NameValuePair nvp) { - Args.notNull(nvp, "Name value pair"); - if (parameters == null) { - parameters = new LinkedList(); - } - parameters.add(nvp); - return this; - } - - public RequestBuilder addParameter(final String name, final String value) { - return addParameter(new BasicNameValuePair(name, value)); - } - - public RequestBuilder addParameters(final NameValuePair... nvps) { - for (final NameValuePair nvp: nvps) { - addParameter(nvp); - } - return this; - } - - public RequestConfig getConfig() { - return config; - } - - public RequestBuilder setConfig(final RequestConfig config) { - this.config = config; - return this; - } - - public HttpUriRequest build() { - final HttpRequestBase result; - URI uriNotNull = this.uri != null ? this.uri : URI.create("/"); - HttpEntity entityCopy = this.entity; - if (parameters != null && !parameters.isEmpty()) { - if (entityCopy == null && (HttpPost.METHOD_NAME.equalsIgnoreCase(method) - || HttpPut.METHOD_NAME.equalsIgnoreCase(method))) { - entityCopy = new UrlEncodedFormEntity(parameters, HTTP.DEF_CONTENT_CHARSET); - } else { - try { - uriNotNull = new URIBuilder(uriNotNull) - .setCharset(this.charset) - .addParameters(parameters) - .build(); - } catch (final URISyntaxException ex) { - // should never happen - } - } - } - if (entityCopy == null) { - result = new InternalRequest(method); - } else { - final InternalEntityEclosingRequest request = new InternalEntityEclosingRequest(method); - request.setEntity(entityCopy); - result = request; - } - result.setProtocolVersion(this.version); - result.setURI(uriNotNull); - if (this.headergroup != null) { - result.setHeaders(this.headergroup.getAllHeaders()); - } - result.setConfig(this.config); - return result; - } - - static class InternalRequest extends HttpRequestBase { - - private final String method; - - InternalRequest(final String method) { - super(); - this.method = method; - } - - @Override - public String getMethod() { - return this.method; - } - - } - - static class InternalEntityEclosingRequest extends HttpEntityEnclosingRequestBase { - - private final String method; - - InternalEntityEclosingRequest(final String method) { - super(); - this.method = method; - } - - @Override - public String getMethod() { - return this.method; - } - - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/package-info.java deleted file mode 100644 index 7f47fed0..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/methods/package-info.java +++ /dev/null @@ -1,31 +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 - * . - * - */ - -/** - * Standard HTTP method implementations. - */ -package com.tracelytics.ext.apache.http.client.methods; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/package-info.java deleted file mode 100644 index cd6f8ad7..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/package-info.java +++ /dev/null @@ -1,31 +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 - * . - * - */ - -/** - * Client HTTP communication APIs. - */ -package com.tracelytics.ext.apache.http.client; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/params/AllClientPNames.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/params/AllClientPNames.java deleted file mode 100644 index 19577819..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/params/AllClientPNames.java +++ /dev/null @@ -1,65 +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 com.tracelytics.ext.apache.http.client.params; - -import com.tracelytics.ext.apache.http.params.CoreConnectionPNames; -import com.tracelytics.ext.apache.http.params.CoreProtocolPNames; - -import com.tracelytics.ext.apache.http.auth.params.AuthPNames; -import com.tracelytics.ext.apache.http.conn.params.ConnConnectionPNames; -import com.tracelytics.ext.apache.http.conn.params.ConnManagerPNames; -import com.tracelytics.ext.apache.http.conn.params.ConnRoutePNames; -import com.tracelytics.ext.apache.http.cookie.params.CookieSpecPNames; - -/** - * Collected parameter names for the HttpClient module. - * This interface combines the parameter definitions of the HttpClient - * module and all dependency modules or informational units. - * It does not define additional parameter names, but references - * other interfaces defining parameter names. - *

- * This interface is meant as a navigation aid for developers. - * When referring to parameter names, you should use the interfaces - * in which the respective constants are actually defined. - *

- * - * @since 4.0 - * - * @deprecated (4.3) use - * {@link com.tracelytics.ext.apache.http.client.config.RequestConfig}, - * {@link com.tracelytics.ext.apache.http.config.ConnectionConfig}, - * {@link com.tracelytics.ext.apache.http.config.SocketConfig} - */ -@Deprecated -public interface AllClientPNames extends - CoreConnectionPNames, CoreProtocolPNames, - ClientPNames, AuthPNames, CookieSpecPNames, - ConnConnectionPNames, ConnManagerPNames, ConnRoutePNames { - - // no additional definitions -} - diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/params/ClientPNames.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/params/ClientPNames.java deleted file mode 100644 index 9bb76554..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/params/ClientPNames.java +++ /dev/null @@ -1,133 +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 com.tracelytics.ext.apache.http.client.params; - -/** - * Parameter names for HTTP client parameters. - * - * @since 4.0 - * - * @deprecated (4.3) use {@link com.tracelytics.ext.apache.http.client.config.RequestConfig}. - */ -@Deprecated -public interface ClientPNames { - - public static final String CONNECTION_MANAGER_FACTORY_CLASS_NAME = "http.connection-manager.factory-class-name"; - - /** - * Defines whether redirects should be handled automatically - *

- * This parameter expects a value of type {@link Boolean}. - *

- */ - public static final String HANDLE_REDIRECTS = "http.protocol.handle-redirects"; - - /** - * Defines whether relative redirects should be rejected. HTTP specification - * requires the location value be an absolute URI. - *

- * This parameter expects a value of type {@link Boolean}. - *

- */ - public static final String REJECT_RELATIVE_REDIRECT = "http.protocol.reject-relative-redirect"; - - /** - * Defines the maximum number of redirects to be followed. - * The limit on number of redirects is intended to prevent infinite loops. - *

- * This parameter expects a value of type {@link Integer}. - *

- */ - public static final String MAX_REDIRECTS = "http.protocol.max-redirects"; - - /** - * Defines whether circular redirects (redirects to the same location) should be allowed. - * The HTTP spec is not sufficiently clear whether circular redirects are permitted, - * therefore optionally they can be enabled - *

- * This parameter expects a value of type {@link Boolean}. - *

- */ - public static final String ALLOW_CIRCULAR_REDIRECTS = "http.protocol.allow-circular-redirects"; - - /** - * Defines whether authentication should be handled automatically. - *

- * This parameter expects a value of type {@link Boolean}. - *

- */ - public static final String HANDLE_AUTHENTICATION = "http.protocol.handle-authentication"; - - /** - * Defines the name of the cookie specification to be used for HTTP state management. - *

- * This parameter expects a value of type {@link String}. - *

- */ - public static final String COOKIE_POLICY = "http.protocol.cookie-policy"; - - /** - * Defines the virtual host to be used in the {@code Host} - * request header instead of the physical host. - *

- * This parameter expects a value of type {@link com.tracelytics.ext.apache.http.HttpHost}. - *

- * If a port is not provided, it will be derived from the request URL. - */ - public static final String VIRTUAL_HOST = "http.virtual-host"; - - /** - * Defines the request headers to be sent per default with each request. - *

- * This parameter expects a value of type {@link java.util.Collection}. The - * collection is expected to contain {@link com.tracelytics.ext.apache.http.Header}s. - *

- */ - public static final String DEFAULT_HEADERS = "http.default-headers"; - - /** - * Defines the default host. The default value will be used if the target host is - * not explicitly specified in the request URI. - *

- * This parameter expects a value of type {@link com.tracelytics.ext.apache.http.HttpHost}. - *

- */ - public static final String DEFAULT_HOST = "http.default-host"; - - /** - * Defines the timeout in milliseconds used when retrieving an instance of - * {@link com.tracelytics.ext.apache.http.conn.ManagedClientConnection} from the - * {@link com.tracelytics.ext.apache.http.conn.ClientConnectionManager}. - *

- * This parameter expects a value of type {@link Long}. - *

- * @since 4.2 - */ - public static final String CONN_MANAGER_TIMEOUT = "http.conn-manager.timeout"; - -} - diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/params/HttpClientParamConfig.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/params/HttpClientParamConfig.java deleted file mode 100644 index 611ab257..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/params/HttpClientParamConfig.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 com.tracelytics.ext.apache.http.client.params; - -import java.net.InetAddress; -import java.util.Collection; - -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.params.CoreConnectionPNames; -import com.tracelytics.ext.apache.http.params.CoreProtocolPNames; -import com.tracelytics.ext.apache.http.params.HttpParams; - -import com.tracelytics.ext.apache.http.auth.params.AuthPNames; -import com.tracelytics.ext.apache.http.client.config.RequestConfig; -import com.tracelytics.ext.apache.http.conn.params.ConnRoutePNames; - -/** - * @deprecated (4.3) provided for compatibility with {@link HttpParams}. Do not use. - * - * @since 4.3 - */ -@Deprecated -public final class HttpClientParamConfig { - - private HttpClientParamConfig() { - } - - @SuppressWarnings("unchecked") - public static RequestConfig getRequestConfig(final HttpParams params) { - return RequestConfig.custom() - .setSocketTimeout(params.getIntParameter( - CoreConnectionPNames.SO_TIMEOUT, 0)) - .setStaleConnectionCheckEnabled(params.getBooleanParameter( - CoreConnectionPNames.STALE_CONNECTION_CHECK, true)) - .setConnectTimeout(params.getIntParameter( - CoreConnectionPNames.CONNECTION_TIMEOUT, 0)) - .setExpectContinueEnabled(params.getBooleanParameter( - CoreProtocolPNames.USE_EXPECT_CONTINUE, false)) - .setProxy((HttpHost) params.getParameter( - ConnRoutePNames.DEFAULT_PROXY)) - .setLocalAddress((InetAddress) params.getParameter( - ConnRoutePNames.LOCAL_ADDRESS)) - .setProxyPreferredAuthSchemes((Collection) params.getParameter( - AuthPNames.PROXY_AUTH_PREF)) - .setTargetPreferredAuthSchemes((Collection) params.getParameter( - AuthPNames.TARGET_AUTH_PREF)) - .setAuthenticationEnabled(params.getBooleanParameter( - ClientPNames.HANDLE_AUTHENTICATION, true)) - .setCircularRedirectsAllowed(params.getBooleanParameter( - ClientPNames.ALLOW_CIRCULAR_REDIRECTS, false)) - .setConnectionRequestTimeout((int) params.getLongParameter( - ClientPNames.CONN_MANAGER_TIMEOUT, 0)) - .setCookieSpec((String) params.getParameter( - ClientPNames.COOKIE_POLICY)) - .setMaxRedirects(params.getIntParameter( - ClientPNames.MAX_REDIRECTS, 50)) - .setRedirectsEnabled(params.getBooleanParameter( - ClientPNames.HANDLE_REDIRECTS, true)) - .setRelativeRedirectsAllowed(!params.getBooleanParameter( - ClientPNames.REJECT_RELATIVE_REDIRECT, false)) - .build(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/params/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/params/package-info.java deleted file mode 100644 index feb9701b..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/params/package-info.java +++ /dev/null @@ -1,32 +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 - * . - * - */ - -/** - * Deprecated. - * @deprecated (4.3). - */ -package com.tracelytics.ext.apache.http.client.params; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/HttpClientContext.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/HttpClientContext.java deleted file mode 100644 index 72a75cdc..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/HttpClientContext.java +++ /dev/null @@ -1,250 +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 com.tracelytics.ext.apache.http.client.protocol; - -import java.net.URI; -import java.util.List; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.config.Lookup; -import com.tracelytics.ext.apache.http.protocol.BasicHttpContext; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.protocol.HttpCoreContext; - -import com.tracelytics.ext.apache.http.auth.AuthSchemeProvider; -import com.tracelytics.ext.apache.http.auth.AuthState; -import com.tracelytics.ext.apache.http.client.AuthCache; -import com.tracelytics.ext.apache.http.client.CookieStore; -import com.tracelytics.ext.apache.http.client.CredentialsProvider; -import com.tracelytics.ext.apache.http.client.config.RequestConfig; -import com.tracelytics.ext.apache.http.conn.routing.HttpRoute; -import com.tracelytics.ext.apache.http.conn.routing.RouteInfo; -import com.tracelytics.ext.apache.http.cookie.CookieOrigin; -import com.tracelytics.ext.apache.http.cookie.CookieSpec; -import com.tracelytics.ext.apache.http.cookie.CookieSpecProvider; - -/** - * Adaptor class that provides convenience type safe setters and getters - * for common {@link HttpContext} attributes used in the course - * of HTTP request execution. - * - * @since 4.3 - */ -@NotThreadSafe -public class HttpClientContext extends HttpCoreContext { - - /** - * Attribute name of a {@link com.tracelytics.ext.apache.http.conn.routing.RouteInfo} - * object that represents the actual connection route. - */ - public static final String HTTP_ROUTE = "http.route"; - - /** - * Attribute name of a {@link List} object that represents a collection of all - * redirect locations received in the process of request execution. - */ - public static final String REDIRECT_LOCATIONS = "http.protocol.redirect-locations"; - - /** - * Attribute name of a {@link com.tracelytics.ext.apache.http.config.Lookup} object that represents - * the actual {@link CookieSpecProvider} registry. - */ - public static final String COOKIESPEC_REGISTRY = "http.cookiespec-registry"; - - /** - * Attribute name of a {@link com.tracelytics.ext.apache.http.cookie.CookieSpec} - * object that represents the actual cookie specification. - */ - public static final String COOKIE_SPEC = "http.cookie-spec"; - - /** - * Attribute name of a {@link com.tracelytics.ext.apache.http.cookie.CookieOrigin} - * object that represents the actual details of the origin server. - */ - public static final String COOKIE_ORIGIN = "http.cookie-origin"; - - /** - * Attribute name of a {@link com.tracelytics.ext.apache.http.client.CookieStore} - * object that represents the actual cookie store. - */ - public static final String COOKIE_STORE = "http.cookie-store"; - - /** - * Attribute name of a {@link com.tracelytics.ext.apache.http.client.CredentialsProvider} - * object that represents the actual credentials provider. - */ - public static final String CREDS_PROVIDER = "http.auth.credentials-provider"; - - /** - * Attribute name of a {@link com.tracelytics.ext.apache.http.client.AuthCache} object - * that represents the auth scheme cache. - */ - public static final String AUTH_CACHE = "http.auth.auth-cache"; - - /** - * Attribute name of a {@link com.tracelytics.ext.apache.http.auth.AuthState} - * object that represents the actual target authentication state. - */ - public static final String TARGET_AUTH_STATE = "http.auth.target-scope"; - - /** - * Attribute name of a {@link com.tracelytics.ext.apache.http.auth.AuthState} - * object that represents the actual proxy authentication state. - */ - public static final String PROXY_AUTH_STATE = "http.auth.proxy-scope"; - - /** - * Attribute name of a {@link java.lang.Object} object that represents - * the actual user identity such as user {@link java.security.Principal}. - */ - public static final String USER_TOKEN = "http.user-token"; - - /** - * Attribute name of a {@link com.tracelytics.ext.apache.http.config.Lookup} object that represents - * the actual {@link AuthSchemeProvider} registry. - */ - public static final String AUTHSCHEME_REGISTRY = "http.authscheme-registry"; - - /** - * Attribute name of a {@link com.tracelytics.ext.apache.http.client.config.RequestConfig} object that - * represents the actual request configuration. - */ - public static final String REQUEST_CONFIG = "http.request-config"; - - public static HttpClientContext adapt(final HttpContext context) { - if (context instanceof HttpClientContext) { - return (HttpClientContext) context; - } else { - return new HttpClientContext(context); - } - } - - public static HttpClientContext create() { - return new HttpClientContext(new BasicHttpContext()); - } - - public HttpClientContext(final HttpContext context) { - super(context); - } - - public HttpClientContext() { - super(); - } - - public RouteInfo getHttpRoute() { - return getAttribute(HTTP_ROUTE, HttpRoute.class); - } - - @SuppressWarnings("unchecked") - public List getRedirectLocations() { - return getAttribute(REDIRECT_LOCATIONS, List.class); - } - - public CookieStore getCookieStore() { - return getAttribute(COOKIE_STORE, CookieStore.class); - } - - public void setCookieStore(final CookieStore cookieStore) { - setAttribute(COOKIE_STORE, cookieStore); - } - - public CookieSpec getCookieSpec() { - return getAttribute(COOKIE_SPEC, CookieSpec.class); - } - - public CookieOrigin getCookieOrigin() { - return getAttribute(COOKIE_ORIGIN, CookieOrigin.class); - } - - @SuppressWarnings("unchecked") - private Lookup getLookup(final String name, final Class clazz) { - return getAttribute(name, Lookup.class); - } - - public Lookup getCookieSpecRegistry() { - return getLookup(COOKIESPEC_REGISTRY, CookieSpecProvider.class); - } - - public void setCookieSpecRegistry(final Lookup lookup) { - setAttribute(COOKIESPEC_REGISTRY, lookup); - } - - public Lookup getAuthSchemeRegistry() { - return getLookup(AUTHSCHEME_REGISTRY, AuthSchemeProvider.class); - } - - public void setAuthSchemeRegistry(final Lookup lookup) { - setAttribute(AUTHSCHEME_REGISTRY, lookup); - } - - public CredentialsProvider getCredentialsProvider() { - return getAttribute(CREDS_PROVIDER, CredentialsProvider.class); - } - - public void setCredentialsProvider(final CredentialsProvider credentialsProvider) { - setAttribute(CREDS_PROVIDER, credentialsProvider); - } - - public AuthCache getAuthCache() { - return getAttribute(AUTH_CACHE, AuthCache.class); - } - - public void setAuthCache(final AuthCache authCache) { - setAttribute(AUTH_CACHE, authCache); - } - - public AuthState getTargetAuthState() { - return getAttribute(TARGET_AUTH_STATE, AuthState.class); - } - - public AuthState getProxyAuthState() { - return getAttribute(PROXY_AUTH_STATE, AuthState.class); - } - - public T getUserToken(final Class clazz) { - return getAttribute(USER_TOKEN, clazz); - } - - public Object getUserToken() { - return getAttribute(USER_TOKEN); - } - - public void setUserToken(final Object obj) { - setAttribute(USER_TOKEN, obj); - } - - public RequestConfig getRequestConfig() { - final RequestConfig config = getAttribute(REQUEST_CONFIG, RequestConfig.class); - return config != null ? config : RequestConfig.DEFAULT; - } - - public void setRequestConfig(final RequestConfig config) { - setAttribute(REQUEST_CONFIG, config); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/RequestAcceptEncoding.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/RequestAcceptEncoding.java deleted file mode 100644 index f8ce388b..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/RequestAcceptEncoding.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 com.tracelytics.ext.apache.http.client.protocol; - -import java.io.IOException; -import java.util.List; - -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpRequestInterceptor; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -/** - * Class responsible for handling Content Encoding requests in HTTP. - *

- * Instances of this class are stateless, therefore they're thread-safe and immutable. - * - * @see "http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.5" - * - * @since 4.1 - */ -@Immutable -public class RequestAcceptEncoding implements HttpRequestInterceptor { - - private final String acceptEncoding; - - /** - * @since 4.4 - */ - public RequestAcceptEncoding(final List encodings) { - if (encodings != null && !encodings.isEmpty()) { - final StringBuilder buf = new StringBuilder(); - for (int i = 0; i < encodings.size(); i++) { - if (i > 0) { - buf.append(","); - } - buf.append(encodings.get(i)); - } - this.acceptEncoding = buf.toString(); - } else { - this.acceptEncoding = "gzip,deflate"; - } - } - - public RequestAcceptEncoding() { - this(null); - } - - @Override - public void process( - final HttpRequest request, - final HttpContext context) throws HttpException, IOException { - - /* Signal support for Accept-Encoding transfer encodings. */ - if (!request.containsHeader("Accept-Encoding")) { - request.addHeader("Accept-Encoding", acceptEncoding); - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/RequestAddCookies.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/RequestAddCookies.java deleted file mode 100644 index a008bac7..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/RequestAddCookies.java +++ /dev/null @@ -1,207 +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 com.tracelytics.ext.apache.http.client.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; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpRequestInterceptor; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.client.CookieStore; -import com.tracelytics.ext.apache.http.client.config.CookieSpecs; -import com.tracelytics.ext.apache.http.client.config.RequestConfig; -import com.tracelytics.ext.apache.http.client.methods.HttpUriRequest; -import com.tracelytics.ext.apache.http.config.Lookup; -import com.tracelytics.ext.apache.http.conn.routing.RouteInfo; -import com.tracelytics.ext.apache.http.cookie.Cookie; -import com.tracelytics.ext.apache.http.cookie.CookieOrigin; -import com.tracelytics.ext.apache.http.cookie.CookieSpec; -import com.tracelytics.ext.apache.http.cookie.CookieSpecProvider; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.TextUtils; - -/** - * Request interceptor that matches cookies available in the current - * {@link CookieStore} to the request being executed and generates - * corresponding {@code Cookie} request headers. - * - * @since 4.0 - */ -@Immutable -public class RequestAddCookies implements HttpRequestInterceptor { - - private final Logger log = Logger.getLogger(getClass().getName()); - - public RequestAddCookies() { - super(); - } - - @Override - public void process(final HttpRequest request, final HttpContext context) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - Args.notNull(context, "HTTP context"); - - final String method = request.getRequestLine().getMethod(); - if (method.equalsIgnoreCase("CONNECT")) { - return; - } - - final HttpClientContext clientContext = HttpClientContext.adapt(context); - - // Obtain cookie store - final CookieStore cookieStore = clientContext.getCookieStore(); - if (cookieStore == null) { - this.log.log(Level.FINE, "Cookie store not specified in HTTP context"); - return; - } - - // Obtain the registry of cookie specs - final Lookup registry = clientContext.getCookieSpecRegistry(); - if (registry == null) { - this.log.log(Level.FINE, "CookieSpec registry not specified in HTTP context"); - return; - } - - // Obtain the target host, possibly virtual (required) - final HttpHost targetHost = clientContext.getTargetHost(); - if (targetHost == null) { - this.log.log(Level.FINE, "Target host not set in the context"); - return; - } - - // Obtain the route (required) - final RouteInfo route = clientContext.getHttpRoute(); - if (route == null) { - this.log.log(Level.FINE, "Connection route not set in the context"); - return; - } - - final RequestConfig config = clientContext.getRequestConfig(); - String policy = config.getCookieSpec(); - if (policy == null) { - policy = CookieSpecs.DEFAULT; - } - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "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 String path = requestURI != null ? requestURI.getPath() : null; - final String hostName = targetHost.getHostName(); - int port = targetHost.getPort(); - if (port < 0) { - port = route.getTargetHost().getPort(); - } - - final CookieOrigin cookieOrigin = new CookieOrigin( - hostName, - port >= 0 ? port : 0, - !TextUtils.isEmpty(path) ? path : "/", - route.isSecure()); - - // Get an instance of the selected cookie policy - final CookieSpecProvider provider = registry.lookup(policy); - if (provider == null) { - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Unsupported cookie policy: " + policy); - } - - return; - } - final CookieSpec cookieSpec = provider.create(clientContext); - // Get all cookies available in the HTTP state - final List cookies = cookieStore.getCookies(); - // Find cookies matching the given origin - final List matchedCookies = new ArrayList(); - final Date now = new Date(); - boolean expired = false; - for (final Cookie cookie : cookies) { - if (!cookie.isExpired(now)) { - if (cookieSpec.match(cookie, cookieOrigin)) { - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Cookie " + cookie + " match " + cookieOrigin); - } - matchedCookies.add(cookie); - } - } else { - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Cookie " + cookie + " expired"); - } - expired = true; - } - } - // Per RFC 6265, 5.3 - // The user agent must evict all expired cookies if, at any time, an expired cookie - // exists in the cookie store - if (expired) { - cookieStore.clearExpired(now); - } - // Generate Cookie request headers - if (!matchedCookies.isEmpty()) { - final List

headers = cookieSpec.formatCookies(matchedCookies); - for (final Header header : headers) { - request.addHeader(header); - } - } - - final int ver = cookieSpec.getVersion(); - if (ver > 0) { - final Header header = cookieSpec.getVersionHeader(); - if (header != null) { - // Advertise cookie version support - request.addHeader(header); - } - } - - // Stick the CookieSpec and CookieOrigin instances to the HTTP context - // so they could be obtained by the response interceptor - context.setAttribute(HttpClientContext.COOKIE_SPEC, cookieSpec); - context.setAttribute(HttpClientContext.COOKIE_ORIGIN, cookieOrigin); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/RequestAuthCache.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/RequestAuthCache.java deleted file mode 100644 index bbb3bf22..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/RequestAuthCache.java +++ /dev/null @@ -1,148 +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 com.tracelytics.ext.apache.http.client.protocol; - -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpRequestInterceptor; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.auth.AuthProtocolState; -import com.tracelytics.ext.apache.http.auth.AuthScheme; -import com.tracelytics.ext.apache.http.auth.AuthScope; -import com.tracelytics.ext.apache.http.auth.AuthState; -import com.tracelytics.ext.apache.http.auth.Credentials; -import com.tracelytics.ext.apache.http.client.AuthCache; -import com.tracelytics.ext.apache.http.client.CredentialsProvider; -import com.tracelytics.ext.apache.http.conn.routing.RouteInfo; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Request interceptor that can preemptively authenticate against known hosts, - * if there is a cached {@link AuthScheme} instance in the local - * {@link AuthCache} associated with the given target or proxy host. - * - * @since 4.1 - */ -@Immutable -public class RequestAuthCache implements HttpRequestInterceptor { - - private final Logger log = Logger.getLogger(getClass().getName()); - - public RequestAuthCache() { - super(); - } - - @Override - public void process(final HttpRequest request, final HttpContext context) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - Args.notNull(context, "HTTP context"); - - final HttpClientContext clientContext = HttpClientContext.adapt(context); - - final AuthCache authCache = clientContext.getAuthCache(); - if (authCache == null) { - this.log.log(Level.FINE, "Auth cache not set in the context"); - return; - } - - final CredentialsProvider credsProvider = clientContext.getCredentialsProvider(); - if (credsProvider == null) { - this.log.log(Level.FINE, "Credentials provider not set in the context"); - return; - } - - final RouteInfo route = clientContext.getHttpRoute(); - if (route == null) { - this.log.log(Level.FINE, "Route info not set in the context"); - return; - } - - HttpHost target = clientContext.getTargetHost(); - if (target == null) { - this.log.log(Level.FINE, "Target host not set in the context"); - return; - } - - if (target.getPort() < 0) { - target = new HttpHost( - target.getHostName(), - route.getTargetHost().getPort(), - target.getSchemeName()); - } - - final AuthState targetState = clientContext.getTargetAuthState(); - if (targetState != null && targetState.getState() == AuthProtocolState.UNCHALLENGED) { - final AuthScheme authScheme = authCache.get(target); - if (authScheme != null) { - doPreemptiveAuth(target, authScheme, targetState, credsProvider); - } - } - - final HttpHost proxy = route.getProxyHost(); - final AuthState proxyState = clientContext.getProxyAuthState(); - if (proxy != null && proxyState != null && proxyState.getState() == AuthProtocolState.UNCHALLENGED) { - final AuthScheme authScheme = authCache.get(proxy); - if (authScheme != null) { - doPreemptiveAuth(proxy, authScheme, proxyState, credsProvider); - } - } - } - - private void doPreemptiveAuth( - final HttpHost host, - final AuthScheme authScheme, - final AuthState authState, - final CredentialsProvider credsProvider) { - final String schemeName = authScheme.getSchemeName(); - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Re-using cached '" + schemeName + "' auth scheme for " + host); - } - - final AuthScope authScope = new AuthScope(host, AuthScope.ANY_REALM, schemeName); - final Credentials creds = credsProvider.getCredentials(authScope); - - if (creds != null) { - if ("BASIC".equalsIgnoreCase(authScheme.getSchemeName())) { - authState.setState(AuthProtocolState.CHALLENGED); - } else { - authState.setState(AuthProtocolState.SUCCESS); - } - authState.update(authScheme, creds); - } else { - this.log.log(Level.FINE, "No credentials for preemptive authentication"); - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/RequestClientConnControl.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/RequestClientConnControl.java deleted file mode 100644 index 95ecd4d3..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/RequestClientConnControl.java +++ /dev/null @@ -1,93 +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 com.tracelytics.ext.apache.http.client.protocol; - -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpRequestInterceptor; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.conn.routing.RouteInfo; -import com.tracelytics.ext.apache.http.protocol.HTTP; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * This protocol interceptor is responsible for adding {@code Connection} - * or {@code Proxy-Connection} headers to the outgoing requests, which - * is essential for managing persistence of {@code HTTP/1.0} connections. - * - * @since 4.0 - */ -@Immutable -public class RequestClientConnControl implements HttpRequestInterceptor { - - private final Logger log = Logger.getLogger(getClass().getName()); - - private static final String PROXY_CONN_DIRECTIVE = "Proxy-Connection"; - - public RequestClientConnControl() { - super(); - } - - @Override - public void process(final HttpRequest request, final HttpContext context) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - - final String method = request.getRequestLine().getMethod(); - if (method.equalsIgnoreCase("CONNECT")) { - request.setHeader(PROXY_CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE); - return; - } - - final HttpClientContext clientContext = HttpClientContext.adapt(context); - - // Obtain the client connection (required) - final RouteInfo route = clientContext.getHttpRoute(); - if (route == null) { - this.log.log(Level.FINE, "Connection route not set in the context"); - return; - } - - if (route.getHopCount() == 1 || route.isTunnelled()) { - if (!request.containsHeader(HTTP.CONN_DIRECTIVE)) { - request.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE); - } - } - if (route.getHopCount() == 2 && !route.isTunnelled()) { - if (!request.containsHeader(PROXY_CONN_DIRECTIVE)) { - request.addHeader(PROXY_CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE); - } - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/RequestDefaultHeaders.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/RequestDefaultHeaders.java deleted file mode 100644 index 9e5204c5..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/RequestDefaultHeaders.java +++ /dev/null @@ -1,91 +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 com.tracelytics.ext.apache.http.client.protocol; - -import java.io.IOException; -import java.util.Collection; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpRequestInterceptor; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.client.params.ClientPNames; - -/** - * Request interceptor that adds default request headers. - * - * @since 4.0 - */ -@SuppressWarnings("deprecation") -@Immutable -public class RequestDefaultHeaders implements HttpRequestInterceptor { - - private final Collection defaultHeaders; - - /** - * @since 4.3 - */ - public RequestDefaultHeaders(final Collection defaultHeaders) { - super(); - this.defaultHeaders = defaultHeaders; - } - - public RequestDefaultHeaders() { - this(null); - } - - @Override - public void process(final HttpRequest request, final HttpContext context) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - - final String method = request.getRequestLine().getMethod(); - if (method.equalsIgnoreCase("CONNECT")) { - return; - } - - // Add default headers - @SuppressWarnings("unchecked") - Collection defHeaders = (Collection) - request.getParams().getParameter(ClientPNames.DEFAULT_HEADERS); - if (defHeaders == null) { - defHeaders = this.defaultHeaders; - } - - if (defHeaders != null) { - for (final Header defHeader : defHeaders) { - request.addHeader(defHeader); - } - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/RequestExpectContinue.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/RequestExpectContinue.java deleted file mode 100644 index 7c779d86..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/RequestExpectContinue.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 com.tracelytics.ext.apache.http.client.protocol; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpEntityEnclosingRequest; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpRequestInterceptor; -import com.tracelytics.ext.apache.http.HttpVersion; -import com.tracelytics.ext.apache.http.ProtocolVersion; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.protocol.HTTP; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.client.config.RequestConfig; - -/** - * RequestExpectContinue is responsible for enabling the 'expect-continue' - * handshake by adding {@code Expect} header. - *

- * This interceptor takes into account {@link RequestConfig#isExpectContinueEnabled()} - * setting. - *

- * - * @since 4.3 - */ -@Immutable -public class RequestExpectContinue implements HttpRequestInterceptor { - - public RequestExpectContinue() { - super(); - } - - @Override - public void process(final HttpRequest request, final HttpContext context) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - - if (!request.containsHeader(HTTP.EXPECT_DIRECTIVE)) { - if (request instanceof HttpEntityEnclosingRequest) { - final ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); - final HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity(); - // 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)) { - final HttpClientContext clientContext = HttpClientContext.adapt(context); - final RequestConfig config = clientContext.getRequestConfig(); - if (config.isExpectContinueEnabled()) { - request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE); - } - } - } - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/ResponseContentEncoding.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/ResponseContentEncoding.java deleted file mode 100644 index b880dedf..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/ResponseContentEncoding.java +++ /dev/null @@ -1,139 +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 com.tracelytics.ext.apache.http.client.protocol; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Locale; -import java.util.zip.GZIPInputStream; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HeaderElement; -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.HttpResponseInterceptor; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.config.Lookup; -import com.tracelytics.ext.apache.http.config.RegistryBuilder; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -import com.tracelytics.ext.apache.http.client.config.RequestConfig; -import com.tracelytics.ext.apache.http.client.entity.DecompressingEntity; -import com.tracelytics.ext.apache.http.client.entity.DeflateInputStream; -import com.tracelytics.ext.apache.http.client.entity.InputStreamFactory; - -/** - * {@link HttpResponseInterceptor} responsible for processing Content-Encoding - * responses. - *

- * Instances of this class are stateless and immutable, therefore threadsafe. - * - * @since 4.1 - * - */ -@Immutable -public class ResponseContentEncoding implements HttpResponseInterceptor { - - public static final String UNCOMPRESSED = "http.client.response.uncompressed"; - - private final static InputStreamFactory GZIP = new InputStreamFactory() { - - @Override - public InputStream create(final InputStream instream) throws IOException { - return new GZIPInputStream(instream); - } - }; - - private final static InputStreamFactory DEFLATE = new InputStreamFactory() { - - @Override - public InputStream create(final InputStream instream) throws IOException { - return new DeflateInputStream(instream); - } - - }; - - private final Lookup decoderRegistry; - - /** - * @since 4.4 - */ - public ResponseContentEncoding(final Lookup decoderRegistry) { - this.decoderRegistry = decoderRegistry != null ? decoderRegistry : - RegistryBuilder.create() - .register("gzip", GZIP) - .register("x-gzip", GZIP) - .register("deflate", DEFLATE) - .build(); - } - - /** - * Handles {@code gzip} and {@code deflate} compressed entities by using the following - * decoders: - *

    - *
  • gzip - see {@link GZIPInputStream}
  • - *
  • deflate - see {@link DeflateInputStream}
  • - *
- */ - public ResponseContentEncoding() { - this(null); - } - - @Override - public void process( - final HttpResponse response, - final HttpContext context) throws HttpException, IOException { - final HttpEntity entity = response.getEntity(); - - final HttpClientContext clientContext = HttpClientContext.adapt(context); - final RequestConfig requestConfig = clientContext.getRequestConfig(); - // entity can be null in case of 304 Not Modified, 204 No Content or similar - // check for zero length entity. - if (requestConfig.isDecompressionEnabled() && entity != null && entity.getContentLength() != 0) { - final Header ceheader = entity.getContentEncoding(); - if (ceheader != null) { - final HeaderElement[] codecs = ceheader.getElements(); - for (final HeaderElement codec : codecs) { - 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"); - } else { - if (!"identity".equals(codecname)) { - throw new HttpException("Unsupported Content-Coding: " + codec.getName()); - } - } - } - } - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/ResponseProcessCookies.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/ResponseProcessCookies.java deleted file mode 100644 index aa870ef5..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/ResponseProcessCookies.java +++ /dev/null @@ -1,159 +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 com.tracelytics.ext.apache.http.client.protocol; - -import java.io.IOException; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HeaderIterator; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.HttpResponseInterceptor; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.client.CookieStore; -import com.tracelytics.ext.apache.http.cookie.Cookie; -import com.tracelytics.ext.apache.http.cookie.CookieOrigin; -import com.tracelytics.ext.apache.http.cookie.CookieSpec; -import com.tracelytics.ext.apache.http.cookie.MalformedCookieException; -import com.tracelytics.ext.apache.http.cookie.SM; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Response interceptor that populates the current {@link CookieStore} with data - * contained in response cookies received in the given the HTTP response. - * - * @since 4.0 - */ -@Immutable -public class ResponseProcessCookies implements HttpResponseInterceptor { - - private final Logger log = Logger.getLogger(getClass().getName()); - - public ResponseProcessCookies() { - super(); - } - - @Override - public void process(final HttpResponse response, final HttpContext context) - throws HttpException, IOException { - Args.notNull(response, "HTTP request"); - Args.notNull(context, "HTTP context"); - - final HttpClientContext clientContext = HttpClientContext.adapt(context); - - // Obtain actual CookieSpec instance - final CookieSpec cookieSpec = clientContext.getCookieSpec(); - if (cookieSpec == null) { - this.log.log(Level.FINE, "Cookie spec not specified in HTTP context"); - return; - } - // Obtain cookie store - final CookieStore cookieStore = clientContext.getCookieStore(); - if (cookieStore == null) { - this.log.log(Level.FINE, "Cookie store not specified in HTTP context"); - return; - } - // Obtain actual CookieOrigin instance - final CookieOrigin cookieOrigin = clientContext.getCookieOrigin(); - if (cookieOrigin == null) { - this.log.log(Level.FINE, "Cookie origin not specified in HTTP context"); - return; - } - HeaderIterator it = response.headerIterator(SM.SET_COOKIE); - processCookies(it, cookieSpec, cookieOrigin, cookieStore); - - // see if the cookie spec supports cookie versioning. - if (cookieSpec.getVersion() > 0) { - // process set-cookie2 headers. - // Cookie2 will replace equivalent Cookie instances - it = response.headerIterator(SM.SET_COOKIE2); - processCookies(it, cookieSpec, cookieOrigin, cookieStore); - } - } - - private void processCookies( - final HeaderIterator iterator, - final CookieSpec cookieSpec, - final CookieOrigin cookieOrigin, - final CookieStore cookieStore) { - while (iterator.hasNext()) { - final Header header = iterator.nextHeader(); - try { - final List cookies = cookieSpec.parse(header, cookieOrigin); - for (final Cookie cookie : cookies) { - try { - cookieSpec.validate(cookie, cookieOrigin); - cookieStore.addCookie(cookie); - - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Cookie accepted [" + formatCooke(cookie) + "]"); - } - } catch (final MalformedCookieException ex) { - if (this.log.isLoggable(Level.WARNING)) { - this.log.log(Level.WARNING, "Cookie rejected [" + formatCooke(cookie) + "] " - + ex.getMessage()); - } - } - } - } catch (final MalformedCookieException ex) { - if (this.log.isLoggable(Level.WARNING)) { - this.log.log(Level.WARNING, "Invalid cookie header: \"" - + header + "\". " + ex.getMessage()); - } - } - } - } - - private static String formatCooke(final Cookie cookie) { - final StringBuilder buf = new StringBuilder(); - buf.append(cookie.getName()); - buf.append("=\""); - String v = cookie.getValue(); - if (v != null) { - if (v.length() > 100) { - v = v.substring(0, 100) + "..."; - } - buf.append(v); - } - buf.append("\""); - buf.append(", version:"); - buf.append(Integer.toString(cookie.getVersion())); - buf.append(", domain:"); - buf.append(cookie.getDomain()); - buf.append(", path:"); - buf.append(cookie.getPath()); - buf.append(", expiry:"); - buf.append(cookie.getExpiryDate()); - return buf.toString(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/package-info.java deleted file mode 100644 index 9948fd85..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/protocol/package-info.java +++ /dev/null @@ -1,31 +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 - * . - * - */ - -/** - * Client specific HTTP protocol handlers. - */ -package com.tracelytics.ext.apache.http.client.protocol; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/utils/CloneUtils.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/utils/CloneUtils.java deleted file mode 100644 index 26d96c6a..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/utils/CloneUtils.java +++ /dev/null @@ -1,86 +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 com.tracelytics.ext.apache.http.client.utils; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * A collection of utilities to workaround limitations of Java clone framework. - * - * @since 4.0 - */ -@Immutable -public class CloneUtils { - - /** - * @since 4.3 - */ - public static T cloneObject(final T obj) throws CloneNotSupportedException { - if (obj == null) { - return null; - } - if (obj instanceof Cloneable) { - final Class clazz = obj.getClass (); - final Method m; - try { - m = clazz.getMethod("clone", (Class[]) null); - } catch (final NoSuchMethodException ex) { - throw new NoSuchMethodError(ex.getMessage()); - } - try { - @SuppressWarnings("unchecked") // OK because clone() preserves the class - final T result = (T) m.invoke(obj, (Object []) null); - return result; - } catch (final InvocationTargetException ex) { - final Throwable cause = ex.getCause(); - if (cause instanceof CloneNotSupportedException) { - throw ((CloneNotSupportedException) cause); - } else { - throw new Error("Unexpected exception", cause); - } - } catch (final IllegalAccessException ex) { - throw new IllegalAccessError(ex.getMessage()); - } - } else { - throw new CloneNotSupportedException(); - } - } - - public static Object clone(final Object obj) throws CloneNotSupportedException { - return cloneObject(obj); - } - - /** - * This class should not be instantiated. - */ - private CloneUtils() { - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/utils/DateUtils.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/utils/DateUtils.java deleted file mode 100644 index 342f082b..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/utils/DateUtils.java +++ /dev/null @@ -1,250 +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 com.tracelytics.ext.apache.http.client.utils; - -import java.lang.ref.SoftReference; -import java.text.ParsePosition; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.TimeZone; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * A utility class for parsing and formatting HTTP dates as used in cookies and - * other headers. This class handles dates as defined by RFC 2616 section - * 3.3.1 as well as some other common non-standard formats. - * - * @since 4.3 - */ -@Immutable -public final class DateUtils { - - /** - * Date format pattern used to parse HTTP date headers in RFC 1123 format. - */ - public static final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz"; - - /** - * Date format pattern used to parse HTTP date headers in RFC 1036 format. - */ - public static final String PATTERN_RFC1036 = "EEE, dd-MMM-yy HH:mm:ss zzz"; - - /** - * Date format pattern used to parse HTTP date headers in ANSI C - * {@code asctime()} format. - */ - public static final String PATTERN_ASCTIME = "EEE MMM d HH:mm:ss yyyy"; - - private static final String[] DEFAULT_PATTERNS = new String[] { - PATTERN_RFC1123, - PATTERN_RFC1036, - PATTERN_ASCTIME - }; - - private static final Date DEFAULT_TWO_DIGIT_YEAR_START; - - public static final TimeZone GMT = TimeZone.getTimeZone("GMT"); - - static { - final Calendar calendar = Calendar.getInstance(); - calendar.setTimeZone(GMT); - calendar.set(2000, Calendar.JANUARY, 1, 0, 0, 0); - calendar.set(Calendar.MILLISECOND, 0); - DEFAULT_TWO_DIGIT_YEAR_START = calendar.getTime(); - } - - /** - * Parses a date value. The formats used for parsing the date value are retrieved from - * the default http params. - * - * @param dateValue the date value to parse - * - * @return the parsed date or null if input could not be parsed - */ - public static Date parseDate(final String dateValue) { - return parseDate(dateValue, null, null); - } - - /** - * Parses the date value using the given date formats. - * - * @param dateValue the date value to parse - * @param dateFormats the date formats to use - * - * @return the parsed date or null if input could not be parsed - */ - public static Date parseDate(final String dateValue, final String[] dateFormats) { - return parseDate(dateValue, dateFormats, null); - } - - /** - * Parses the date value using the given date formats. - * - * @param dateValue the date value to parse - * @param dateFormats the date formats to use - * @param startDate During parsing, two digit years will be placed in the range - * {@code startDate} to {@code startDate + 100 years}. This value may - * be {@code null}. When {@code null} is given as a parameter, year - * {@code 2000} will be used. - * - * @return the parsed date or null if input could not be parsed - */ - public static Date parseDate( - final String dateValue, - final String[] dateFormats, - final Date startDate) { - Args.notNull(dateValue, "Date value"); - final String[] localDateFormats = dateFormats != null ? dateFormats : DEFAULT_PATTERNS; - final Date localStartDate = startDate != null ? startDate : DEFAULT_TWO_DIGIT_YEAR_START; - String v = dateValue; - // trim single quotes around date if present - // see issue #5279 - if (v.length() > 1 && v.startsWith("'") && v.endsWith("'")) { - v = v.substring (1, v.length() - 1); - } - - for (final String dateFormat : localDateFormats) { - final SimpleDateFormat dateParser = DateFormatHolder.formatFor(dateFormat); - dateParser.set2DigitYearStart(localStartDate); - final ParsePosition pos = new ParsePosition(0); - final Date result = dateParser.parse(v, pos); - if (pos.getIndex() != 0) { - return result; - } - } - return null; - } - - /** - * Formats the given date according to the RFC 1123 pattern. - * - * @param date The date to format. - * @return An RFC 1123 formatted date string. - * - * @see #PATTERN_RFC1123 - */ - public static String formatDate(final Date date) { - return formatDate(date, PATTERN_RFC1123); - } - - /** - * Formats the given date according to the specified pattern. The pattern - * must conform to that used by the {@link SimpleDateFormat simple date - * format} class. - * - * @param date The date to format. - * @param pattern The pattern to use for formatting the date. - * @return A formatted date string. - * - * @throws IllegalArgumentException If the given date pattern is invalid. - * - * @see SimpleDateFormat - */ - public static String formatDate(final Date date, final String pattern) { - Args.notNull(date, "Date"); - Args.notNull(pattern, "Pattern"); - final SimpleDateFormat formatter = DateFormatHolder.formatFor(pattern); - return formatter.format(date); - } - - /** - * Clears thread-local variable containing {@link java.text.DateFormat} cache. - * - * @since 4.3 - */ - public static void clearThreadLocal() { - DateFormatHolder.clearThreadLocal(); - } - - /** This class should not be instantiated. */ - private DateUtils() { - } - - /** - * A factory for {@link SimpleDateFormat}s. The instances are stored in a - * threadlocal way because SimpleDateFormat is not threadsafe as noted in - * {@link SimpleDateFormat its javadoc}. - * - */ - final static class DateFormatHolder { - - private static final ThreadLocal>> - THREADLOCAL_FORMATS = new ThreadLocal>>() { - - @Override - protected SoftReference> initialValue() { - return new SoftReference>( - new HashMap()); - } - - }; - - /** - * creates a {@link SimpleDateFormat} for the requested format string. - * - * @param pattern - * a non-{@code null} format String according to - * {@link SimpleDateFormat}. The format is not checked against - * {@code null} since all paths go through - * {@link DateUtils}. - * @return the requested format. This simple dateformat should not be used - * to {@link SimpleDateFormat#applyPattern(String) apply} to a - * different pattern. - */ - public static SimpleDateFormat formatFor(final String pattern) { - final SoftReference> ref = THREADLOCAL_FORMATS.get(); - Map formats = ref.get(); - if (formats == null) { - formats = new HashMap(); - THREADLOCAL_FORMATS.set( - new SoftReference>(formats)); - } - - SimpleDateFormat format = formats.get(pattern); - if (format == null) { - format = new SimpleDateFormat(pattern, Locale.US); - format.setTimeZone(TimeZone.getTimeZone("GMT")); - formats.put(pattern, format); - } - - return format; - } - - public static void clearThreadLocal() { - THREADLOCAL_FORMATS.remove(); - } - - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/utils/HttpClientUtils.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/utils/HttpClientUtils.java deleted file mode 100644 index d154760d..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/utils/HttpClientUtils.java +++ /dev/null @@ -1,150 +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 com.tracelytics.ext.apache.http.client.utils; - -import java.io.Closeable; -import java.io.IOException; - -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.util.EntityUtils; - -import com.tracelytics.ext.apache.http.client.HttpClient; -import com.tracelytics.ext.apache.http.client.methods.CloseableHttpResponse; - -/** - * Convenience methods for closing response and client objects. - * - * @since 4.2 - */ -public class HttpClientUtils { - - private HttpClientUtils() { - } - - /** - * Unconditionally close a response. - *

- * Example Code: - * - *

-     * HttpResponse httpResponse = null;
-     * try {
-     *     httpResponse = httpClient.execute(httpGet);
-     * } catch (Exception e) {
-     *     // error handling
-     * } finally {
-     *     HttpClientUtils.closeQuietly(httpResponse);
-     * }
-     * 
- * - * @param response - * the HttpResponse to release resources, may be null or already - * closed. - * - * @since 4.2 - */ - public static void closeQuietly(final HttpResponse response) { - if (response != null) { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - try { - EntityUtils.consume(entity); - } catch (final IOException ex) { - } - } - } - } - - /** - * Unconditionally close a response. - *

- * Example Code: - * - *

-     * HttpResponse httpResponse = null;
-     * try {
-     *     httpResponse = httpClient.execute(httpGet);
-     * } catch (Exception e) {
-     *     // error handling
-     * } finally {
-     *     HttpClientUtils.closeQuietly(httpResponse);
-     * }
-     * 
- * - * @param response - * the HttpResponse to release resources, may be null or already - * closed. - * - * @since 4.3 - */ - public static void closeQuietly(final CloseableHttpResponse response) { - if (response != null) { - try { - try { - EntityUtils.consume(response.getEntity()); - } finally { - response.close(); - } - } catch (final IOException ignore) { - } - } - } - - /** - * Unconditionally close a httpClient. Shuts down the underlying connection - * manager and releases the resources. - *

- * Example Code: - * - *

-     * HttpClient httpClient = HttpClients.createDefault();
-     * try {
-     *   httpClient.execute(request);
-     * } catch (Exception e) {
-     *   // error handling
-     * } finally {
-     *   HttpClientUtils.closeQuietly(httpClient);
-     * }
-     * 
- * - * @param httpClient - * the HttpClient to close, may be null or already closed. - * @since 4.2 - */ - public static void closeQuietly(final HttpClient httpClient) { - if (httpClient != null) { - if (httpClient instanceof Closeable) { - try { - ((Closeable) httpClient).close(); - } catch (final IOException ignore) { - } - } - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/utils/URIBuilder.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/utils/URIBuilder.java deleted file mode 100644 index 5eb5ab9f..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/utils/URIBuilder.java +++ /dev/null @@ -1,513 +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 com.tracelytics.ext.apache.http.client.utils; - -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import com.tracelytics.ext.apache.http.Consts; -import com.tracelytics.ext.apache.http.NameValuePair; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.message.BasicNameValuePair; - -import com.tracelytics.ext.apache.http.conn.util.InetAddressUtils; - -/** - * 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 : Consts.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 : Consts.UTF_8); - } - - private String encodePath(final String path) { - return URLEncodedUtils.encPath(path, this.charset != null ? this.charset : Consts.UTF_8); - } - - private String encodeUrlForm(final List params) { - return URLEncodedUtils.format(params, this.charset != null ? this.charset : Consts.UTF_8); - } - - private String encodeUric(final String fragment) { - return URLEncodedUtils.encUric(fragment, this.charset != null ? this.charset : Consts.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. - *

- * The value is expected to be encoded form data. - * - * @deprecated (4.3) use {@link #setParameters(List)} or {@link #setParameters(NameValuePair...)} - * - * @see URLEncodedUtils#parse - */ - @Deprecated - public URIBuilder setQuery(final String query) { - this.queryParams = parseQuery(query, this.charset != null ? this.charset : Consts.UTF_8); - 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/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/utils/URIUtils.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/utils/URIUtils.java deleted file mode 100644 index 131d6c46..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/utils/URIUtils.java +++ /dev/null @@ -1,466 +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 com.tracelytics.ext.apache.http.client.utils; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.List; -import java.util.Locale; -import java.util.Stack; - -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.TextUtils; - -import com.tracelytics.ext.apache.http.conn.routing.RouteInfo; - -/** - * A collection of utilities for {@link URI URIs}, to workaround - * bugs within the class or for ease-of-use features. - * - * @since 4.0 - */ -@Immutable -public class URIUtils { - - /** - * Constructs a {@link URI} using all the parameters. This should be - * used instead of - * {@link URI#URI(String, String, String, int, String, String, String)} - * or any of the other URI multi-argument URI constructors. - * - * @param scheme - * Scheme name - * @param host - * Host name - * @param port - * Port number - * @param path - * Path - * @param query - * Query - * @param fragment - * Fragment - * - * @throws URISyntaxException - * If both a scheme and a path are given but the path is - * relative, if the URI string constructed from the given - * components violates RFC 2396, or if the authority - * component of the string is present but cannot be parsed - * as a server-based authority - * - * @deprecated (4.2) use {@link URIBuilder}. - */ - @Deprecated - public static URI createURI( - final String scheme, - final String host, - final int port, - final String path, - final String query, - final String fragment) throws URISyntaxException { - final StringBuilder buffer = new StringBuilder(); - if (host != null) { - if (scheme != null) { - buffer.append(scheme); - buffer.append("://"); - } - buffer.append(host); - if (port > 0) { - buffer.append(':'); - buffer.append(port); - } - } - if (path == null || !path.startsWith("/")) { - buffer.append('/'); - } - if (path != null) { - buffer.append(path); - } - if (query != null) { - buffer.append('?'); - buffer.append(query); - } - if (fragment != null) { - buffer.append('#'); - buffer.append(fragment); - } - return new URI(buffer.toString()); - } - - /** - * A convenience method for creating a new {@link URI} whose scheme, host - * and port are taken from the target host, but whose path, query and - * fragment are taken from the existing URI. The fragment is only used if - * dropFragment is false. The path is set to "/" if not explicitly specified. - * - * @param uri - * Contains the path, query and fragment to use. - * @param target - * Contains the scheme, host and port to use. - * @param dropFragment - * True if the fragment should not be copied. - * - * @throws URISyntaxException - * If the resulting URI is invalid. - */ - public static URI rewriteURI( - final URI uri, - final HttpHost target, - final boolean dropFragment) throws URISyntaxException { - Args.notNull(uri, "URI"); - if (uri.isOpaque()) { - return uri; - } - final URIBuilder uribuilder = new URIBuilder(uri); - if (target != null) { - uribuilder.setScheme(target.getSchemeName()); - uribuilder.setHost(target.getHostName()); - uribuilder.setPort(target.getPort()); - } else { - uribuilder.setScheme(null); - uribuilder.setHost(null); - uribuilder.setPort(-1); - } - if (dropFragment) { - uribuilder.setFragment(null); - } - if (TextUtils.isEmpty(uribuilder.getPath())) { - uribuilder.setPath("/"); - } - return uribuilder.build(); - } - - /** - * A convenience method for - * {@link URIUtils#rewriteURI(URI, HttpHost, boolean)} that always keeps the - * fragment. - */ - public static URI rewriteURI( - final URI uri, - final HttpHost target) throws URISyntaxException { - return rewriteURI(uri, target, false); - } - - /** - * A convenience method that creates a new {@link URI} whose scheme, host, port, path, - * query are taken from the existing URI, dropping any fragment or user-information. - * The path is set to "/" if not explicitly specified. The existing URI is returned - * unmodified if it has no fragment or user-information and has a path. - * - * @param uri - * original URI. - * @throws URISyntaxException - * If the resulting URI is invalid. - */ - public static URI rewriteURI(final URI uri) throws URISyntaxException { - Args.notNull(uri, "URI"); - if (uri.isOpaque()) { - return uri; - } - final URIBuilder uribuilder = new URIBuilder(uri); - if (uribuilder.getUserInfo() != null) { - uribuilder.setUserInfo(null); - } - if (TextUtils.isEmpty(uribuilder.getPath())) { - uribuilder.setPath("/"); - } - if (uribuilder.getHost() != null) { - uribuilder.setHost(uribuilder.getHost().toLowerCase(Locale.ROOT)); - } - uribuilder.setFragment(null); - 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) - * - * @param baseURI the base URI - * @param reference the URI reference - * @return the resulting URI - */ - public static URI resolve(final URI baseURI, final String reference) { - return URIUtils.resolve(baseURI, URI.create(reference)); - } - - /** - * Resolves a URI reference against a base URI. Work-around for bugs in - * java.net.URI (e.g. http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4708535) - * - * @param baseURI the base URI - * @param reference the URI reference - * @return the resulting URI - */ - public static URI resolve(final URI baseURI, final URI reference){ - Args.notNull(baseURI, "Base URI"); - Args.notNull(reference, "Reference URI"); - URI ref = reference; - final String s = ref.toString(); - if (s.startsWith("?")) { - return resolveReferenceStartingWithQueryString(baseURI, ref); - } - final boolean emptyReference = s.isEmpty(); - if (emptyReference) { - ref = URI.create("#"); - } - URI resolved = baseURI.resolve(ref); - if (emptyReference) { - final String resolvedString = resolved.toString(); - resolved = URI.create(resolvedString.substring(0, - resolvedString.indexOf('#'))); - } - return normalizeSyntax(resolved); - } - - /** - * Resolves a reference starting with a query string. - * - * @param baseURI the base URI - * @param reference the URI reference starting with a query string - * @return the resulting URI - */ - private static URI resolveReferenceStartingWithQueryString( - final URI baseURI, final URI reference) { - String baseUri = baseURI.toString(); - baseUri = baseUri.indexOf('?') > -1 ? - baseUri.substring(0, baseUri.indexOf('?')) : baseUri; - return URI.create(baseUri + reference.toString()); - } - - /** - * Removes dot segments according to RFC 3986, section 5.2.4 and - * Syntax-Based Normalization according to RFC 3986, section 6.2.2. - * - * @param uri the original URI - * @return the URI without dot segments - */ - private static URI normalizeSyntax(final URI uri) { - if (uri.isOpaque() || uri.getAuthority() == null) { - // opaque and file: URIs - return uri; - } - Args.check(uri.isAbsolute(), "Base URI must be absolute"); - final String path = uri.getPath() == null ? "" : uri.getPath(); - final String[] inputSegments = path.split("/"); - final Stack outputSegments = new Stack(); - for (final String inputSegment : inputSegments) { - if ((inputSegment.isEmpty()) - || (".".equals(inputSegment))) { - // Do nothing - } else if ("..".equals(inputSegment)) { - if (!outputSegments.isEmpty()) { - outputSegments.pop(); - } - } else { - outputSegments.push(inputSegment); - } - } - final StringBuilder outputBuffer = new StringBuilder(); - for (final String outputSegment : outputSegments) { - outputBuffer.append('/').append(outputSegment); - } - if (path.lastIndexOf('/') == path.length() - 1) { - // path.endsWith("/") || path.equals("") - outputBuffer.append('/'); - } - try { - final String scheme = uri.getScheme().toLowerCase(Locale.ROOT); - final String auth = uri.getAuthority().toLowerCase(Locale.ROOT); - final URI ref = new URI(scheme, auth, outputBuffer.toString(), - null, null); - if (uri.getQuery() == null && uri.getFragment() == null) { - return ref; - } - final StringBuilder normalized = new StringBuilder( - ref.toASCIIString()); - if (uri.getQuery() != null) { - // query string passed through unchanged - normalized.append('?').append(uri.getRawQuery()); - } - if (uri.getFragment() != null) { - // fragment passed through unchanged - normalized.append('#').append(uri.getRawFragment()); - } - return URI.create(normalized.toString()); - } catch (final URISyntaxException e) { - throw new IllegalArgumentException(e); - } - } - - /** - * Extracts target host from the given {@link URI}. - * - * @param uri - * @return the target host if the URI is absolute or {@code null} if the URI is - * relative or does not contain a valid host name. - * - * @since 4.1 - */ - public static HttpHost extractHost(final URI uri) { - if (uri == null) { - return null; - } - HttpHost target = null; - if (uri.isAbsolute()) { - int port = uri.getPort(); // may be overridden later - String host = uri.getHost(); - if (host == null) { // normal parse failed; let's do it ourselves - // authority does not seem to care about the valid character-set for host names - host = uri.getAuthority(); - if (host != null) { - // Strip off any leading user credentials - final int at = host.indexOf('@'); - if (at >= 0) { - if (host.length() > at+1 ) { - host = host.substring(at+1); - } else { - host = null; // @ on its own - } - } - // Extract the port suffix, if present - if (host != null) { - final int colon = host.indexOf(':'); - if (colon >= 0) { - final int pos = colon + 1; - int len = 0; - for (int i = pos; i < host.length(); i++) { - if (Character.isDigit(host.charAt(i))) { - len++; - } else { - break; - } - } - if (len > 0) { - try { - port = Integer.parseInt(host.substring(pos, pos + len)); - } catch (final NumberFormatException ex) { - } - } - host = host.substring(0, colon); - } - } - } - } - final String scheme = uri.getScheme(); - if (!TextUtils.isBlank(host)) { - try { - target = new HttpHost(host, port, scheme); - } catch (IllegalArgumentException ignore) { - } - } - } - return target; - } - - /** - * Derives the interpreted (absolute) URI that was used to generate the last - * request. This is done by extracting the request-uri and target origin for - * the last request and scanning all the redirect locations for the last - * fragment identifier, then combining the result into a {@link URI}. - * - * @param originalURI - * original request before any redirects - * @param target - * if the last URI is relative, it is resolved against this target, - * or {@code null} if not available. - * @param redirects - * collection of redirect locations since the original request - * or {@code null} if not available. - * @return interpreted (absolute) URI - */ - public static URI resolve( - final URI originalURI, - final HttpHost target, - final List redirects) throws URISyntaxException { - Args.notNull(originalURI, "Request URI"); - final URIBuilder uribuilder; - if (redirects == null || redirects.isEmpty()) { - uribuilder = new URIBuilder(originalURI); - } else { - uribuilder = new URIBuilder(redirects.get(redirects.size() - 1)); - String frag = uribuilder.getFragment(); - // read interpreted fragment identifier from redirect locations - for (int i = redirects.size() - 1; frag == null && i >= 0; i--) { - frag = redirects.get(i).getFragment(); - } - uribuilder.setFragment(frag); - } - // read interpreted fragment identifier from original request - if (uribuilder.getFragment() == null) { - uribuilder.setFragment(originalURI.getFragment()); - } - // last target origin - if (target != null && !uribuilder.isAbsolute()) { - uribuilder.setScheme(target.getSchemeName()); - uribuilder.setHost(target.getHostName()); - uribuilder.setPort(target.getPort()); - } - return uribuilder.build(); - } - - /** - * This class should not be instantiated. - */ - private URIUtils() { - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/utils/URLEncodedUtils.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/utils/URLEncodedUtils.java deleted file mode 100644 index 4bbf4ad3..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/utils/URLEncodedUtils.java +++ /dev/null @@ -1,680 +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 com.tracelytics.ext.apache.http.client.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.util.ArrayList; -import java.util.BitSet; -import java.util.Collections; -import java.util.List; -import java.util.Scanner; - -import com.tracelytics.ext.apache.http.Consts; -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HeaderElement; -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.NameValuePair; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.entity.ContentType; -import com.tracelytics.ext.apache.http.message.BasicNameValuePair; -import com.tracelytics.ext.apache.http.message.ParserCursor; -import com.tracelytics.ext.apache.http.message.TokenParser; -import com.tracelytics.ext.apache.http.protocol.HTTP; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.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 name to use while parsing the query - * @return a list of {@link NameValuePair} as built from the URI's query portion. - */ - public static List parse(final URI uri, final String charset) { - final String query = uri.getRawQuery(); - if (query != null && !query.isEmpty()) { - return parse(query, Charset.forName(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 { - 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() : HTTP.DEF_CONTENT_CHARSET; - 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) { - final Header h = entity.getContentType(); - if (h != null) { - final HeaderElement[] elems = h.getElements(); - if (elems.length > 0) { - final String contentType = elems[0].getName(); - return contentType.equalsIgnoreCase(CONTENT_TYPE); - } - } - return false; - } - - /** - * Adds all parameters within the Scanner to the list of {@code parameters}, as encoded by - * {@code encoding}. For example, a scanner containing the string {@code a=1&b=2&c=3} would add the - * {@link NameValuePair NameValuePairs} a=1, b=2, and c=3 to the list of parameters. By convention, {@code '&'} and - * {@code ';'} are accepted as parameter separators. - * - * @param parameters - * List to add parameters to. - * @param scanner - * Input that contains the parameters to parse. - * @param charset - * Encoding to use when decoding the parameters. - * - * @deprecated (4.4) use {@link #parse(String, java.nio.charset.Charset)} - */ - @Deprecated - public static void parse( - final List parameters, - final Scanner scanner, - final String charset) { - parse(parameters, scanner, "[" + QP_SEP_A + QP_SEP_S + "]", charset); - } - - /** - * Adds all parameters within the Scanner to the list of - * {@code parameters}, as encoded by {@code encoding}. For - * example, a scanner containing the string {@code a=1&b=2&c=3} would - * add the {@link NameValuePair NameValuePairs} a=1, b=2, and c=3 to the - * list of parameters. - * - * @param parameters - * List to add parameters to. - * @param scanner - * Input that contains the parameters to parse. - * @param parameterSepartorPattern - * The Pattern string for parameter separators, by convention {@code "[&;]"} - * @param charset - * Encoding to use when decoding the parameters. - * - * @deprecated (4.4) use {@link #parse(com.tracelytics.ext.apache.http.util.CharArrayBuffer, java.nio.charset.Charset, char...)} - */ - @Deprecated - public static void parse( - final List parameters, - final Scanner scanner, - final String parameterSepartorPattern, - final String charset) { - scanner.useDelimiter(parameterSepartorPattern); - while (scanner.hasNext()) { - final String name; - final String value; - final String token = scanner.next(); - final int i = token.indexOf(NAME_VALUE_SEPARATOR); - if (i != -1) { - name = decodeFormFields(token.substring(0, i).trim(), charset); - value = decodeFormFields(token.substring(i + 1).trim(), charset); - } else { - name = decodeFormFields(token.trim(), charset); - value = null; - } - parameters.add(new BasicNameValuePair(name, value)); - } - } - - /** - * 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) { - 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 (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 - */ - public static String format( - final List parameters, - final String 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 List parameters, - final char parameterSeparator, - final String charset) { - 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(); - } - - /** - * 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) { - 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 String charset) { - if (content == null) { - return null; - } - return urlDecode(content, charset != null ? Charset.forName(charset) : Consts.UTF_8, true); - } - - /** - * 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 : Consts.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 String charset) { - if (content == null) { - return null; - } - return urlEncode(content, charset != null ? Charset.forName(charset) : Consts.UTF_8, URLENCODER, 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 : Consts.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/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/utils/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/utils/package-info.java deleted file mode 100644 index cd71f819..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/client/utils/package-info.java +++ /dev/null @@ -1,31 +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 - * . - * - */ - -/** - * Client utility classes. - */ -package com.tracelytics.ext.apache.http.client.utils; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/concurrent/BasicFuture.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/concurrent/BasicFuture.java deleted file mode 100644 index 17c3117c..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/concurrent/BasicFuture.java +++ /dev/null @@ -1,160 +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 com.tracelytics.ext.apache.http.concurrent; - -import com.tracelytics.ext.apache.http.util.Args; - -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -/** - * Basic implementation of the {@link Future} interface. {@code BasicFuture} - * can be put into a completed state by invoking any of the following methods: - * {@link #cancel()}, {@link #failed(Exception)}, or {@link #completed(Object)}. - * - * @param the future result type of an asynchronous operation. - * @since 4.2 - */ -public class BasicFuture implements Future, Cancellable { - - private final FutureCallback callback; - - private volatile boolean completed; - private volatile boolean cancelled; - private volatile T result; - private volatile Exception ex; - - public BasicFuture(final FutureCallback callback) { - super(); - this.callback = callback; - } - - @Override - public boolean isCancelled() { - return this.cancelled; - } - - @Override - public boolean isDone() { - return this.completed; - } - - private T getResult() throws ExecutionException { - if (this.ex != null) { - throw new ExecutionException(this.ex); - } - return this.result; - } - - @Override - public synchronized T get() throws InterruptedException, ExecutionException { - while (!this.completed) { - wait(); - } - return getResult(); - } - - @Override - public synchronized T get(final long timeout, final TimeUnit unit) - throws InterruptedException, ExecutionException, TimeoutException { - Args.notNull(unit, "Time unit"); - final long msecs = unit.toMillis(timeout); - final long startTime = (msecs <= 0) ? 0 : System.currentTimeMillis(); - long waitTime = msecs; - if (this.completed) { - return getResult(); - } else if (waitTime <= 0) { - throw new TimeoutException(); - } else { - for (;;) { - wait(waitTime); - if (this.completed) { - return getResult(); - } else { - waitTime = msecs - (System.currentTimeMillis() - startTime); - if (waitTime <= 0) { - throw new TimeoutException(); - } - } - } - } - } - - public boolean completed(final T result) { - synchronized(this) { - if (this.completed) { - return false; - } - this.completed = true; - this.result = result; - notifyAll(); - } - if (this.callback != null) { - this.callback.completed(result); - } - return true; - } - - public boolean failed(final Exception exception) { - synchronized(this) { - if (this.completed) { - return false; - } - this.completed = true; - this.ex = exception; - notifyAll(); - } - if (this.callback != null) { - this.callback.failed(exception); - } - return true; - } - - @Override - public boolean cancel(final boolean mayInterruptIfRunning) { - synchronized(this) { - if (this.completed) { - return false; - } - this.completed = true; - this.cancelled = true; - notifyAll(); - } - if (this.callback != null) { - this.callback.cancelled(); - } - return true; - } - - @Override - public boolean cancel() { - return cancel(true); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/concurrent/Cancellable.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/concurrent/Cancellable.java deleted file mode 100644 index 7edcfb93..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/concurrent/Cancellable.java +++ /dev/null @@ -1,39 +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 com.tracelytics.ext.apache.http.concurrent; - -/** - * A {@code Cancellable} represents a process or an operation that can be - * canceled. - * - * @since 4.2 - */ -public interface Cancellable { - - boolean cancel(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/concurrent/FutureCallback.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/concurrent/FutureCallback.java deleted file mode 100644 index 051c1117..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/concurrent/FutureCallback.java +++ /dev/null @@ -1,44 +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 com.tracelytics.ext.apache.http.concurrent; - -/** - * A callback interface that gets invoked upon completion of - * a {@link java.util.concurrent.Future}. - * - * @param the future result type returned by this callback. - * @since 4.2 - */ -public interface FutureCallback { - - void completed(T result); - - void failed(Exception ex); - - void cancelled(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/concurrent/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/concurrent/package-info.java deleted file mode 100644 index e4cfe37e..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/concurrent/package-info.java +++ /dev/null @@ -1,31 +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 - * . - * - */ - -/** - * Core concurrency APIs. - */ -package com.tracelytics.ext.apache.http.concurrent; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/config/ConnectionConfig.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/config/ConnectionConfig.java deleted file mode 100644 index f479006f..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/config/ConnectionConfig.java +++ /dev/null @@ -1,192 +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 com.tracelytics.ext.apache.http.config; - -import java.nio.charset.Charset; -import java.nio.charset.CodingErrorAction; - -import com.tracelytics.ext.apache.http.Consts; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * HTTP connection configuration. - * - * @since 4.3 - */ -@Immutable -public class ConnectionConfig implements Cloneable { - - public static final ConnectionConfig DEFAULT = new Builder().build(); - - private final int bufferSize; - private final int fragmentSizeHint; - private final Charset charset; - private final CodingErrorAction malformedInputAction; - private final CodingErrorAction unmappableInputAction; - private final MessageConstraints messageConstraints; - - ConnectionConfig( - final int bufferSize, - final int fragmentSizeHint, - final Charset charset, - final CodingErrorAction malformedInputAction, - final CodingErrorAction unmappableInputAction, - final MessageConstraints messageConstraints) { - super(); - this.bufferSize = bufferSize; - this.fragmentSizeHint = fragmentSizeHint; - this.charset = charset; - this.malformedInputAction = malformedInputAction; - this.unmappableInputAction = unmappableInputAction; - this.messageConstraints = messageConstraints; - } - - public int getBufferSize() { - return bufferSize; - } - - public int getFragmentSizeHint() { - return fragmentSizeHint; - } - - public Charset getCharset() { - return charset; - } - - public CodingErrorAction getMalformedInputAction() { - return malformedInputAction; - } - - public CodingErrorAction getUnmappableInputAction() { - return unmappableInputAction; - } - - public MessageConstraints getMessageConstraints() { - return messageConstraints; - } - - @Override - protected ConnectionConfig clone() throws CloneNotSupportedException { - return (ConnectionConfig) super.clone(); - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("[bufferSize=").append(this.bufferSize) - .append(", fragmentSizeHint=").append(this.fragmentSizeHint) - .append(", charset=").append(this.charset) - .append(", malformedInputAction=").append(this.malformedInputAction) - .append(", unmappableInputAction=").append(this.unmappableInputAction) - .append(", messageConstraints=").append(this.messageConstraints) - .append("]"); - return builder.toString(); - } - - public static ConnectionConfig.Builder custom() { - return new Builder(); - } - - public static ConnectionConfig.Builder copy(final ConnectionConfig config) { - Args.notNull(config, "Connection config"); - return new Builder() - .setCharset(config.getCharset()) - .setMalformedInputAction(config.getMalformedInputAction()) - .setUnmappableInputAction(config.getUnmappableInputAction()) - .setMessageConstraints(config.getMessageConstraints()); - } - - public static class Builder { - - private int bufferSize; - private int fragmentSizeHint; - private Charset charset; - private CodingErrorAction malformedInputAction; - private CodingErrorAction unmappableInputAction; - private MessageConstraints messageConstraints; - - Builder() { - this.fragmentSizeHint = -1; - } - - public Builder setBufferSize(final int bufferSize) { - this.bufferSize = bufferSize; - return this; - } - - public Builder setFragmentSizeHint(final int fragmentSizeHint) { - this.fragmentSizeHint = fragmentSizeHint; - return this; - } - - public Builder setCharset(final Charset charset) { - this.charset = charset; - return this; - } - - public Builder setMalformedInputAction(final CodingErrorAction malformedInputAction) { - this.malformedInputAction = malformedInputAction; - if (malformedInputAction != null && this.charset == null) { - this.charset = Consts.ASCII; - } - return this; - } - - public Builder setUnmappableInputAction(final CodingErrorAction unmappableInputAction) { - this.unmappableInputAction = unmappableInputAction; - if (unmappableInputAction != null && this.charset == null) { - this.charset = Consts.ASCII; - } - return this; - } - - public Builder setMessageConstraints(final MessageConstraints messageConstraints) { - this.messageConstraints = messageConstraints; - return this; - } - - public ConnectionConfig build() { - Charset cs = charset; - if (cs == null && (malformedInputAction != null || unmappableInputAction != null)) { - cs = Consts.ASCII; - } - final int bufSize = this.bufferSize > 0 ? this.bufferSize : 8 * 1024; - final int fragmentHintSize = this.fragmentSizeHint >= 0 ? this.fragmentSizeHint : bufSize; - return new ConnectionConfig( - bufSize, - fragmentHintSize, - cs, - malformedInputAction, - unmappableInputAction, - messageConstraints); - } - - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/config/Lookup.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/config/Lookup.java deleted file mode 100644 index 3b036582..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/config/Lookup.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 com.tracelytics.ext.apache.http.config; - - -/** - * Generic lookup by low-case string ID. - * - * @since 4.3 - */ -public interface Lookup { - - I lookup(String name); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/config/MessageConstraints.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/config/MessageConstraints.java deleted file mode 100644 index 86ca3395..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/config/MessageConstraints.java +++ /dev/null @@ -1,118 +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 com.tracelytics.ext.apache.http.config; - -import com.tracelytics.ext.apache.http.util.Args; - -/** - * HTTP Message constraints: line length and header count. - *

- * Please note that line length is defined in bytes and not characters. - * This is only relevant however when using non-standard HTTP charsets - * for protocol elements such as UTF-8. - *

- * - * @since 4.3 - */ -public class MessageConstraints implements Cloneable { - - public static final MessageConstraints DEFAULT = new Builder().build(); - - private final int maxLineLength; - private final int maxHeaderCount; - - MessageConstraints(final int maxLineLength, final int maxHeaderCount) { - super(); - this.maxLineLength = maxLineLength; - this.maxHeaderCount = maxHeaderCount; - } - - public int getMaxLineLength() { - return maxLineLength; - } - - public int getMaxHeaderCount() { - return maxHeaderCount; - } - - @Override - protected MessageConstraints clone() throws CloneNotSupportedException { - return (MessageConstraints) super.clone(); - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("[maxLineLength=").append(maxLineLength) - .append(", maxHeaderCount=").append(maxHeaderCount) - .append("]"); - return builder.toString(); - } - - public static MessageConstraints lineLen(final int max) { - return new MessageConstraints(Args.notNegative(max, "Max line length"), -1); - } - - public static MessageConstraints.Builder custom() { - return new Builder(); - } - - public static MessageConstraints.Builder copy(final MessageConstraints config) { - Args.notNull(config, "Message constraints"); - return new Builder() - .setMaxHeaderCount(config.getMaxHeaderCount()) - .setMaxLineLength(config.getMaxLineLength()); - } - - public static class Builder { - - private int maxLineLength; - private int maxHeaderCount; - - Builder() { - this.maxLineLength = -1; - this.maxHeaderCount = -1; - } - - public Builder setMaxLineLength(final int maxLineLength) { - this.maxLineLength = maxLineLength; - return this; - } - - public Builder setMaxHeaderCount(final int maxHeaderCount) { - this.maxHeaderCount = maxHeaderCount; - return this; - } - - public MessageConstraints build() { - return new MessageConstraints(maxLineLength, maxHeaderCount); - } - - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/config/Registry.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/config/Registry.java deleted file mode 100644 index 9f0625e4..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/config/Registry.java +++ /dev/null @@ -1,64 +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 com.tracelytics.ext.apache.http.config; - -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; - -/** - * Generic registry of items keyed by low-case string ID. - * - * @since 4.3 - */ -@ThreadSafe -public final class Registry implements Lookup { - - private final Map map; - - Registry(final Map map) { - super(); - this.map = new ConcurrentHashMap(map); - } - - @Override - public I lookup(final String key) { - if (key == null) { - return null; - } - return map.get(key.toLowerCase(Locale.ROOT)); - } - - @Override - public String toString() { - return map.toString(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/config/RegistryBuilder.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/config/RegistryBuilder.java deleted file mode 100644 index e492f59d..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/config/RegistryBuilder.java +++ /dev/null @@ -1,72 +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 com.tracelytics.ext.apache.http.config; - -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Builder for {@link Registry} instances. - * - * @since 4.3 - */ -@NotThreadSafe -public final class RegistryBuilder { - - private final Map items; - - public static RegistryBuilder create() { - return new RegistryBuilder(); - } - - RegistryBuilder() { - super(); - this.items = new HashMap(); - } - - public RegistryBuilder register(final String id, final I item) { - Args.notEmpty(id, "ID"); - Args.notNull(item, "Item"); - items.put(id.toLowerCase(Locale.ROOT), item); - return this; - } - - public Registry build() { - return new Registry(items); - } - - @Override - public String toString() { - return items.toString(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/config/SocketConfig.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/config/SocketConfig.java deleted file mode 100644 index 35cca6f6..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/config/SocketConfig.java +++ /dev/null @@ -1,293 +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 com.tracelytics.ext.apache.http.config; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Socket configuration. - * - * @since 4.3 - */ -@Immutable -public class SocketConfig implements Cloneable { - - public static final SocketConfig DEFAULT = new Builder().build(); - - private final int soTimeout; - private final boolean soReuseAddress; - private final int soLinger; - private final boolean soKeepAlive; - private final boolean tcpNoDelay; - private final int sndBufSize; - private final int rcvBufSize; - private int backlogSize; - - SocketConfig( - final int soTimeout, - final boolean soReuseAddress, - final int soLinger, - final boolean soKeepAlive, - final boolean tcpNoDelay, - final int sndBufSize, - final int rcvBufSize, - final int backlogSize) { - super(); - this.soTimeout = soTimeout; - this.soReuseAddress = soReuseAddress; - this.soLinger = soLinger; - this.soKeepAlive = soKeepAlive; - this.tcpNoDelay = tcpNoDelay; - this.sndBufSize = sndBufSize; - this.rcvBufSize = rcvBufSize; - this.backlogSize = backlogSize; - } - - /** - * Determines the default socket timeout value for non-blocking I/O operations. - *

- * Default: {@code 0} (no timeout) - *

- * - * @return the default socket timeout value for non-blocking I/O operations. - * @see java.net.SocketOptions#SO_TIMEOUT - */ - public int getSoTimeout() { - return soTimeout; - } - - /** - * Determines the default value of the {@link java.net.SocketOptions#SO_REUSEADDR} parameter - * for newly created sockets. - *

- * Default: {@code false} - *

- * - * @return the default value of the {@link java.net.SocketOptions#SO_REUSEADDR} parameter. - * @see java.net.SocketOptions#SO_REUSEADDR - */ - public boolean isSoReuseAddress() { - return soReuseAddress; - } - - /** - * Determines the default value of the {@link java.net.SocketOptions#SO_LINGER} parameter - * for newly created sockets. - *

- * Default: {@code -1} - *

- * - * @return the default value of the {@link java.net.SocketOptions#SO_LINGER} parameter. - * @see java.net.SocketOptions#SO_LINGER - */ - public int getSoLinger() { - return soLinger; - } - - /** - * Determines the default value of the {@link java.net.SocketOptions#SO_KEEPALIVE} parameter - * for newly created sockets. - *

- * Default: {@code -1} - *

- * - * @return the default value of the {@link java.net.SocketOptions#SO_KEEPALIVE} parameter. - * @see java.net.SocketOptions#SO_KEEPALIVE - */ - public boolean isSoKeepAlive() { - return soKeepAlive; - } - - /** - * Determines the default value of the {@link java.net.SocketOptions#TCP_NODELAY} parameter - * for newly created sockets. - *

- * Default: {@code false} - *

- * - * @return the default value of the {@link java.net.SocketOptions#TCP_NODELAY} parameter. - * @see java.net.SocketOptions#TCP_NODELAY - */ - public boolean isTcpNoDelay() { - return tcpNoDelay; - } - - /** - * Determines the default value of the {@link java.net.SocketOptions#SO_SNDBUF} parameter - * for newly created sockets. - *

- * Default: {@code 0} (system default) - *

- * - * @return the default value of the {@link java.net.SocketOptions#SO_SNDBUF} parameter. - * @see java.net.SocketOptions#SO_SNDBUF - * @since 4.4 - */ - public int getSndBufSize() { - return sndBufSize; - } - - /** - * Determines the default value of the {@link java.net.SocketOptions#SO_RCVBUF} parameter - * for newly created sockets. - *

- * Default: {@code 0} (system default) - *

- * - * @return the default value of the {@link java.net.SocketOptions#SO_RCVBUF} parameter. - * @see java.net.SocketOptions#SO_RCVBUF - * @since 4.4 - */ - public int getRcvBufSize() { - return rcvBufSize; - } - - /** - * Determines the maximum queue length for incoming connection indications - * (a request to connect) also known as server socket backlog. - *

- * Default: {@code 0} (system default) - *

- * @return the maximum queue length for incoming connection indications - * @since 4.4 - */ - public int getBacklogSize() { - return backlogSize; - } - - @Override - protected SocketConfig clone() throws CloneNotSupportedException { - return (SocketConfig) super.clone(); - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("[soTimeout=").append(this.soTimeout) - .append(", soReuseAddress=").append(this.soReuseAddress) - .append(", soLinger=").append(this.soLinger) - .append(", soKeepAlive=").append(this.soKeepAlive) - .append(", tcpNoDelay=").append(this.tcpNoDelay) - .append(", sndBufSize=").append(this.sndBufSize) - .append(", rcvBufSize=").append(this.rcvBufSize) - .append(", backlogSize=").append(this.backlogSize) - .append("]"); - return builder.toString(); - } - - public static SocketConfig.Builder custom() { - return new Builder(); - } - - public static SocketConfig.Builder copy(final SocketConfig config) { - Args.notNull(config, "Socket config"); - return new Builder() - .setSoTimeout(config.getSoTimeout()) - .setSoReuseAddress(config.isSoReuseAddress()) - .setSoLinger(config.getSoLinger()) - .setSoKeepAlive(config.isSoKeepAlive()) - .setTcpNoDelay(config.isTcpNoDelay()) - .setSndBufSize(config.getSndBufSize()) - .setRcvBufSize(config.getRcvBufSize()) - .setBacklogSize(config.getBacklogSize()); - } - - public static class Builder { - - private int soTimeout; - private boolean soReuseAddress; - private int soLinger; - private boolean soKeepAlive; - private boolean tcpNoDelay; - private int sndBufSize; - private int rcvBufSize; - private int backlogSize; - - Builder() { - this.soLinger = -1; - this.tcpNoDelay = true; - } - - public Builder setSoTimeout(final int soTimeout) { - this.soTimeout = soTimeout; - return this; - } - - public Builder setSoReuseAddress(final boolean soReuseAddress) { - this.soReuseAddress = soReuseAddress; - return this; - } - - public Builder setSoLinger(final int soLinger) { - this.soLinger = soLinger; - return this; - } - - public Builder setSoKeepAlive(final boolean soKeepAlive) { - this.soKeepAlive = soKeepAlive; - return this; - } - - public Builder setTcpNoDelay(final boolean tcpNoDelay) { - this.tcpNoDelay = tcpNoDelay; - return this; - } - - /** - * @since 4.4 - */ - public Builder setSndBufSize(final int sndBufSize) { - this.sndBufSize = sndBufSize; - return this; - } - - /** - * @since 4.4 - */ - public Builder setRcvBufSize(final int rcvBufSize) { - this.rcvBufSize = rcvBufSize; - return this; - } - - /** - * @since 4.4 - */ - public Builder setBacklogSize(final int backlogSize) { - this.backlogSize = backlogSize; - return this; - } - - public SocketConfig build() { - return new SocketConfig(soTimeout, soReuseAddress, soLinger, soKeepAlive, tcpNoDelay, - sndBufSize, rcvBufSize, backlogSize); - } - - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/config/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/config/package-info.java deleted file mode 100644 index 82eb0af7..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/config/package-info.java +++ /dev/null @@ -1,31 +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 - * . - * - */ - -/** - * Core configuration APIs. - */ -package com.tracelytics.ext.apache.http.config; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ClientConnectionManager.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ClientConnectionManager.java deleted file mode 100644 index 34ee6cf1..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ClientConnectionManager.java +++ /dev/null @@ -1,117 +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 com.tracelytics.ext.apache.http.conn; - -import java.util.concurrent.TimeUnit; - -import com.tracelytics.ext.apache.http.conn.routing.HttpRoute; -import com.tracelytics.ext.apache.http.conn.scheme.SchemeRegistry; - -/** - * Management interface for {@link ManagedClientConnection client connections}. - * The purpose of an HTTP connection manager is to serve as a factory for new - * HTTP connections, manage persistent connections and synchronize access to - * persistent connections making sure that only one thread of execution can - * have access to a connection at a time. - *

- * Implementations of this interface must be thread-safe. Access to shared - * data must be synchronized as methods of this interface may be executed - * from multiple threads. - * - * @since 4.0 - * - * @deprecated (4.3) replaced by {@link HttpClientConnectionManager}. - */ -@Deprecated -public interface ClientConnectionManager { - - /** - * Obtains the scheme registry used by this manager. - * - * @return the scheme registry, never {@code null} - */ - SchemeRegistry getSchemeRegistry(); - - /** - * Returns a new {@link ClientConnectionRequest}, from which a - * {@link ManagedClientConnection} can be obtained or the request can be - * aborted. - */ - ClientConnectionRequest requestConnection(HttpRoute route, Object state); - - /** - * Releases a connection for use by others. - * You may optionally specify how long the connection is valid - * to be reused. Values <= 0 are considered to be valid forever. - * If the connection is not marked as reusable, the connection will - * not be reused regardless of the valid duration. - * - * If the connection has been released before, - * the call will be ignored. - * - * @param conn the connection to release - * @param validDuration the duration of time this connection is valid for reuse - * @param timeUnit the unit of time validDuration is measured in - * - * @see #closeExpiredConnections() - */ - void releaseConnection(ManagedClientConnection conn, long validDuration, TimeUnit timeUnit); - - /** - * Closes idle connections in the pool. - * Open connections in the pool that have not been used for the - * timespan given by the argument will be closed. - * Currently allocated connections are not subject to this method. - * Times will be checked with milliseconds precision - * - * All expired connections will also be closed. - * - * @param idletime the idle time of connections to be closed - * @param tunit the unit for the {@code idletime} - * - * @see #closeExpiredConnections() - */ - void closeIdleConnections(long idletime, TimeUnit tunit); - - /** - * Closes all expired connections in the pool. - * Open connections in the pool that have not been used for - * the timespan defined when the connection was released will be closed. - * Currently allocated connections are not subject to this method. - * Times will be checked with milliseconds precision. - */ - void closeExpiredConnections(); - - /** - * Shuts down this connection manager and releases allocated resources. - * This includes closing all connections, whether they are currently - * used or not. - */ - void shutdown(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ClientConnectionRequest.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ClientConnectionRequest.java deleted file mode 100644 index 8c31e9ef..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ClientConnectionRequest.java +++ /dev/null @@ -1,74 +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 com.tracelytics.ext.apache.http.conn; - -import java.util.concurrent.TimeUnit; - -/** - * Encapsulates a request for a {@link ManagedClientConnection}. - * - * @since 4.0 - * - * @deprecated (4.3) replaced by {@link ConnectionRequest}. - */ -@Deprecated -public interface ClientConnectionRequest { - - /** - * Obtains a connection within a given time. - * This method will block until a connection becomes available, - * the timeout expires, or the connection manager is - * {@link ClientConnectionManager#shutdown() shut down}. - * Timeouts are handled with millisecond precision. - * - * If {@link #abortRequest()} is called while this is blocking or - * before this began, an {@link InterruptedException} will - * be thrown. - * - * @param timeout the timeout, 0 or negative for no timeout - * @param tunit the unit for the {@code timeout}, - * may be {@code null} only if there is no timeout - * - * @return a connection that can be used to communicate - * along the given route - * - * @throws ConnectionPoolTimeoutException - * in case of a timeout - * @throws InterruptedException - * if the calling thread is interrupted while waiting - */ - ManagedClientConnection getConnection(long timeout, TimeUnit tunit) - throws InterruptedException, ConnectionPoolTimeoutException; - - /** - * Aborts the call to {@link #getConnection(long, TimeUnit)}, - * causing it to throw an {@link InterruptedException}. - */ - void abortRequest(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ConnectTimeoutException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ConnectTimeoutException.java deleted file mode 100644 index 9b1661a2..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ConnectTimeoutException.java +++ /dev/null @@ -1,94 +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 com.tracelytics.ext.apache.http.conn; - -import java.io.IOException; -import java.io.InterruptedIOException; -import java.net.InetAddress; -import java.util.Arrays; - -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * A timeout while connecting to an HTTP server or waiting for an - * available connection from an HttpConnectionManager. - * - * - * @since 4.0 - */ -@Immutable -public class ConnectTimeoutException extends InterruptedIOException { - - private static final long serialVersionUID = -4816682903149535989L; - - private final HttpHost host; - - /** - * Creates a ConnectTimeoutException with a {@code null} detail message. - */ - public ConnectTimeoutException() { - super(); - this.host = null; - } - - /** - * Creates a ConnectTimeoutException with the specified detail message. - */ - public ConnectTimeoutException(final String message) { - super(message); - this.host = null; - } - - /** - * Creates a ConnectTimeoutException based on original {@link IOException}. - * - * @since 4.3 - */ - public ConnectTimeoutException( - final IOException cause, - final HttpHost host, - final InetAddress... remoteAddresses) { - super("Connect to " + - (host != null ? host.toHostString() : "remote host") + - (remoteAddresses != null && remoteAddresses.length > 0 ? - " " + Arrays.asList(remoteAddresses) : "") + - ((cause != null && cause.getMessage() != null) ? - " failed: " + cause.getMessage() : " timed out")); - this.host = host; - initCause(cause); - } - - /** - * @since 4.3 - */ - public HttpHost getHost() { - return host; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ConnectionKeepAliveStrategy.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ConnectionKeepAliveStrategy.java deleted file mode 100644 index e34b9166..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ConnectionKeepAliveStrategy.java +++ /dev/null @@ -1,66 +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 com.tracelytics.ext.apache.http.conn; - -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -/** - * Interface for deciding how long a connection can remain - * idle before being reused. - *

- * Implementations of this interface must be thread-safe. Access to shared - * data must be synchronized as methods of this interface may be executed - * from multiple threads. - * - * @since 4.0 - */ -public interface ConnectionKeepAliveStrategy { - - /** - * Returns the duration of time which this connection can be safely kept - * idle. If the connection is left idle for longer than this period of time, - * it MUST not reused. A value of 0 or less may be returned to indicate that - * there is no suitable suggestion. - * - * When coupled with a {@link com.tracelytics.ext.apache.http.ConnectionReuseStrategy}, if - * {@link com.tracelytics.ext.apache.http.ConnectionReuseStrategy#keepAlive( - * HttpResponse, HttpContext)} returns true, this allows you to control - * how long the reuse will last. If keepAlive returns false, this should - * have no meaningful impact - * - * @param response - * The last response received over the connection. - * @param context - * the context in which the connection is being used. - * - * @return the duration in ms for which it is safe to keep the connection - * idle, or <=0 if no suggested duration. - */ - long getKeepAliveDuration(HttpResponse response, HttpContext context); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ConnectionPoolTimeoutException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ConnectionPoolTimeoutException.java deleted file mode 100644 index 6d1170ee..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ConnectionPoolTimeoutException.java +++ /dev/null @@ -1,60 +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 com.tracelytics.ext.apache.http.conn; - -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * A timeout while waiting for an available connection - * from a connection manager. - * - * - * @since 4.0 - */ -@Immutable -public class ConnectionPoolTimeoutException extends ConnectTimeoutException { - - private static final long serialVersionUID = -7898874842020245128L; - - /** - * Creates a ConnectTimeoutException with a {@code null} detail message. - */ - public ConnectionPoolTimeoutException() { - super(); - } - - /** - * Creates a ConnectTimeoutException with the specified detail message. - * - * @param message The exception detail message - */ - public ConnectionPoolTimeoutException(final String message) { - super(message); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ConnectionReleaseTrigger.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ConnectionReleaseTrigger.java deleted file mode 100644 index 76b8b660..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ConnectionReleaseTrigger.java +++ /dev/null @@ -1,70 +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 com.tracelytics.ext.apache.http.conn; - -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 stream} or an {@link BasicManagedEntity entity} - * or the {@link ManagedClientConnection connection} itself. - *

- * The methods in this interface can safely be called multiple times. - * The first invocation releases the connection, subsequent calls - * are ignored. - * - * @since 4.0 - */ -public interface ConnectionReleaseTrigger { - - /** - * Releases the connection with the option of keep-alive. This is a - * "graceful" release and may cause IO operations for consuming the - * remainder of a response entity. Use - * {@link #abortConnection abortConnection} for a hard release. The - * connection may be reused as specified by the duration. - * - * @throws IOException - * in case of an IO problem. The connection will be released - * anyway. - */ - void releaseConnection() - throws IOException; - - /** - * Releases the connection without the option of keep-alive. - * This is a "hard" release that implies a shutdown of the connection. - * Use {@link #releaseConnection()} for a graceful release. - * - * @throws IOException in case of an IO problem. - * The connection will be released anyway. - */ - void abortConnection() - throws IOException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ConnectionRequest.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ConnectionRequest.java deleted file mode 100644 index 1698e0f3..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ConnectionRequest.java +++ /dev/null @@ -1,69 +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 com.tracelytics.ext.apache.http.conn; - -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; - -import com.tracelytics.ext.apache.http.HttpClientConnection; -import com.tracelytics.ext.apache.http.concurrent.Cancellable; - -/** - * Represents a request for a {@link HttpClientConnection} whose life cycle - * is managed by a connection manager. - * - * @since 4.3 - */ -public interface ConnectionRequest extends Cancellable { - - /** - * Obtains a connection within a given time. - * This method will block until a connection becomes available, - * the timeout expires, or the connection manager is shut down. - * Timeouts are handled with millisecond precision. - * - * If {@link #cancel()} is called while this is blocking or - * before this began, an {@link InterruptedException} will - * be thrown. - * - * @param timeout the timeout, 0 or negative for no timeout - * @param tunit the unit for the {@code timeout}, - * may be {@code null} only if there is no timeout - * - * @return a connection that can be used to communicate - * along the given route - * - * @throws ConnectionPoolTimeoutException - * in case of a timeout - * @throws InterruptedException - * if the calling thread is interrupted while waiting - */ - HttpClientConnection get(long timeout, TimeUnit tunit) - throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/DnsResolver.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/DnsResolver.java deleted file mode 100644 index ed29a637..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/DnsResolver.java +++ /dev/null @@ -1,54 +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 com.tracelytics.ext.apache.http.conn; - -import java.net.InetAddress; -import java.net.UnknownHostException; - -/** - * Users may implement this interface to override the normal DNS lookup offered - * by the OS. - * - * @since 4.2 - */ -public interface DnsResolver { - - /** - * Returns the IP address for the specified host name, or null if the given - * host is not recognized or the associated IP address cannot be used to - * build an InetAddress instance. - * - * @see InetAddress - * - * @param host - * The host name to be resolved by this resolver. - * @return The IP address associated to the given host name, or null if the - * host name is not known by the implementation class. - */ - InetAddress[] resolve(String host) throws UnknownHostException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/EofSensorInputStream.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/EofSensorInputStream.java deleted file mode 100644 index e1deb4e1..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/EofSensorInputStream.java +++ /dev/null @@ -1,292 +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 com.tracelytics.ext.apache.http.conn; - -import java.io.IOException; -import java.io.InputStream; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.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 { - - if ((wrappedStream != null) && (eof < 0)) { - try { - boolean scws = true; // should close wrapped stream? - if (eofWatcher != null) { - scws = eofWatcher.eofDetected(wrappedStream); - } - if (scws) { - wrappedStream.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 { - - if (wrappedStream != null) { - try { - boolean scws = true; // should close wrapped stream? - if (eofWatcher != null) { - scws = eofWatcher.streamClosed(wrappedStream); - } - if (scws) { - wrappedStream.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 { - - if (wrappedStream != null) { - try { - boolean scws = true; // should close wrapped stream? - if (eofWatcher != null) { - scws = eofWatcher.streamAbort(wrappedStream); - } - if (scws) { - wrappedStream.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/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/EofSensorWatcher.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/EofSensorWatcher.java deleted file mode 100644 index 06d56534..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/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 com.tracelytics.ext.apache.http.conn; - -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/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/HttpClientConnectionManager.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/HttpClientConnectionManager.java deleted file mode 100644 index 10fe63ed..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/HttpClientConnectionManager.java +++ /dev/null @@ -1,183 +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 com.tracelytics.ext.apache.http.conn; - -import java.io.IOException; -import java.util.concurrent.TimeUnit; - -import com.tracelytics.ext.apache.http.HttpClientConnection; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -import com.tracelytics.ext.apache.http.conn.routing.HttpRoute; - -/** - * Represents a manager of persistent client connections. - *

- * The purpose of an HTTP connection manager is to serve as a factory for new - * HTTP connections, manage persistent connections and synchronize access to - * persistent connections making sure that only one thread of execution can - * have access to a connection at a time. - *

- *

- * Implementations of this interface must be thread-safe. Access to shared - * data must be synchronized as methods of this interface may be executed - * from multiple threads. - *

- * - * @since 4.3 - */ -public interface HttpClientConnectionManager { - - /** - * Returns a new {@link ConnectionRequest}, from which a - * {@link HttpClientConnection} can be obtained or the request can be - * aborted. - *

- * Please note that newly allocated connections can be returned - * in the closed state. The consumer of that connection is responsible - * for fully establishing the route the to the connection target - * by calling {@link #connect(com.tracelytics.ext.apache.http.HttpClientConnection, - * com.tracelytics.ext.apache.http.conn.routing.HttpRoute, int, - * com.tracelytics.ext.apache.http.protocol.HttpContext) connect} in order to connect - * directly to the target or to the first proxy hop, optionally calling - * {@link #upgrade(com.tracelytics.ext.apache.http.HttpClientConnection, - * com.tracelytics.ext.apache.http.conn.routing.HttpRoute, - * com.tracelytics.ext.apache.http.protocol.HttpContext) upgrade} method to upgrade - * the connection after having executed {@code CONNECT} method to - * all intermediate proxy hops and and finally calling {@link #routeComplete( - * com.tracelytics.ext.apache.http.HttpClientConnection, - * com.tracelytics.ext.apache.http.conn.routing.HttpRoute, - * com.tracelytics.ext.apache.http.protocol.HttpContext) routeComplete} to mark the route - * as fully completed. - *

- * - * @param route HTTP route of the requested connection. - * @param state expected state of the connection or {@code null} - * if the connection is not expected to carry any state. - */ - ConnectionRequest requestConnection(HttpRoute route, Object state); - - /** - * Releases the connection back to the manager making it potentially - * re-usable by other consumers. Optionally, the maximum period - * of how long the manager should keep the connection alive can be - * defined using {@code validDuration} and {@code timeUnit} - * parameters. - * - * @param conn the managed connection to release. - * @param validDuration the duration of time this connection is valid for reuse. - * @param timeUnit the time unit. - * - * @see #closeExpiredConnections() - */ - void releaseConnection( - HttpClientConnection conn, Object newState, long validDuration, TimeUnit timeUnit); - - /** - * Connects the underlying connection socket to the connection target in case - * of a direct route or to the first proxy hop in case of a route via a proxy - * (or multiple proxies). - * - * @param conn the managed connection. - * @param route the route of the connection. - * @param connectTimeout connect timeout in milliseconds. - * @param context the actual HTTP context. - * @throws IOException - */ - void connect( - HttpClientConnection conn, - HttpRoute route, - int connectTimeout, - HttpContext context) throws IOException; - - /** - * Upgrades the underlying connection socket to TLS/SSL (or another layering - * protocol) after having executed {@code CONNECT} method to all - * intermediate proxy hops - * - * @param conn the managed connection. - * @param route the route of the connection. - * @param context the actual HTTP context. - * @throws IOException - */ - void upgrade( - HttpClientConnection conn, - HttpRoute route, - HttpContext context) throws IOException; - - /** - * Marks the connection as fully established with all its intermediate - * hops completed. - * - * @param conn the managed connection. - * @param route the route of the connection. - * @param context the actual HTTP context. - * @throws IOException - */ - void routeComplete( - HttpClientConnection conn, - HttpRoute route, - HttpContext context) throws IOException; - - /** - * Closes idle connections in the pool. - *

- * Open connections in the pool that have not been used for the - * timespan given by the argument will be closed. - * Currently allocated connections are not subject to this method. - * Times will be checked with milliseconds precision - *

- *

- * All expired connections will also be closed. - *

- * - * @param idletime the idle time of connections to be closed - * @param tunit the unit for the {@code idletime} - * - * @see #closeExpiredConnections() - */ - void closeIdleConnections(long idletime, TimeUnit tunit); - - /** - * Closes all expired connections in the pool. - *

- * Open connections in the pool that have not been used for - * the timespan defined when the connection was released will be closed. - * Currently allocated connections are not subject to this method. - * Times will be checked with milliseconds precision. - *

- */ - void closeExpiredConnections(); - - /** - * Shuts down this connection manager and releases allocated resources. - * This includes closing all connections, whether they are currently - * used or not. - */ - void shutdown(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/HttpClientConnectionOperator.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/HttpClientConnectionOperator.java deleted file mode 100644 index ea0e14ea..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/HttpClientConnectionOperator.java +++ /dev/null @@ -1,61 +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 com.tracelytics.ext.apache.http.conn; - -import java.io.IOException; -import java.net.InetSocketAddress; - -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.config.SocketConfig; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -/** - * Connection operator that performs connection connect and upgrade operations. Usually, components - * participating in these operations are registry of {@link com.tracelytics.ext.apache.http.conn.socket.ConnectionSocketFactory}, - * {@link SchemePortResolver} and {@link DnsResolver}. In general, HTTP client user should not - * provide implementations of this interface, as HttpClient will use the default one that covers - * most of the cases needed for majority of users. - * - * @since 4.4 - */ -public interface HttpClientConnectionOperator { - - void connect( - ManagedHttpClientConnection conn, - HttpHost host, - InetSocketAddress localAddress, - int connectTimeout, - SocketConfig socketConfig, - HttpContext context) throws IOException; - - void upgrade( - ManagedHttpClientConnection conn, - HttpHost host, - HttpContext context) throws IOException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/HttpConnectionFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/HttpConnectionFactory.java deleted file mode 100644 index ea1a324d..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/HttpConnectionFactory.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 com.tracelytics.ext.apache.http.conn; - -import com.tracelytics.ext.apache.http.HttpConnection; -import com.tracelytics.ext.apache.http.config.ConnectionConfig; - -/** - * Generic {@link HttpConnection} factory. - * - * @since 4.3 - */ -public interface HttpConnectionFactory { - - C create(T route, ConnectionConfig config); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/HttpHostConnectException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/HttpHostConnectException.java deleted file mode 100644 index 324e920e..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/HttpHostConnectException.java +++ /dev/null @@ -1,82 +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 com.tracelytics.ext.apache.http.conn; - -import java.io.IOException; -import java.net.ConnectException; -import java.net.InetAddress; -import java.util.Arrays; - -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * A {@link ConnectException} that specifies the {@link HttpHost} that was - * being connected to. - * - * @since 4.0 - */ -@Immutable -public class HttpHostConnectException extends ConnectException { - - private static final long serialVersionUID = -3194482710275220224L; - - private final HttpHost host; - - /** - * @deprecated (4.3) use {@link #HttpHostConnectException(java.io.IOException, com.tracelytics.ext.apache.http.HttpHost, - * java.net.InetAddress...)} - */ - @Deprecated - public HttpHostConnectException(final HttpHost host, final ConnectException cause) { - this(cause, host, (InetAddress[]) null); - } - - /** - * Creates a HttpHostConnectException based on original {@link java.io.IOException}. - * - * @since 4.3 - */ - public HttpHostConnectException( - final IOException cause, - final HttpHost host, - final InetAddress... remoteAddresses) { - super("Connect to " + - (host != null ? host.toHostString() : "remote host") + - (remoteAddresses != null && remoteAddresses .length > 0 ? - " " + Arrays.asList(remoteAddresses) : "") + - ((cause != null && cause.getMessage() != null) ? - " failed: " + cause.getMessage() : " refused")); - this.host = host; - initCause(cause); - } - - public HttpHost getHost() { - return this.host; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/HttpInetSocketAddress.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/HttpInetSocketAddress.java deleted file mode 100644 index d3e8615e..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/HttpInetSocketAddress.java +++ /dev/null @@ -1,65 +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 com.tracelytics.ext.apache.http.conn; - -import java.net.InetAddress; -import java.net.InetSocketAddress; - -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Extended {@link InetSocketAddress} implementation that also provides access to the original - * {@link HttpHost} used to resolve the address. - * - * @since 4.2 no longer used. - * - * @deprecated (4.3) - */ -@Deprecated -public class HttpInetSocketAddress extends InetSocketAddress { - - private static final long serialVersionUID = -6650701828361907957L; - - private final HttpHost httphost; - - public HttpInetSocketAddress(final HttpHost httphost, final InetAddress addr, final int port) { - super(addr, port); - Args.notNull(httphost, "HTTP host"); - this.httphost = httphost; - } - - public HttpHost getHttpHost() { - return this.httphost; - } - - @Override - public String toString() { - return this.httphost.getHostName() + ":" + getPort(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/HttpRoutedConnection.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/HttpRoutedConnection.java deleted file mode 100644 index 96d06088..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/HttpRoutedConnection.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 com.tracelytics.ext.apache.http.conn; - -import javax.net.ssl.SSLSession; - -import com.tracelytics.ext.apache.http.HttpInetConnection; - -import com.tracelytics.ext.apache.http.conn.routing.HttpRoute; - -/** - * Interface to access routing information of a client side connection. - * - * @since 4.1 - * - * @deprecated (4.3) replaced by {@link HttpClientConnectionManager}. - */ -@Deprecated -public interface HttpRoutedConnection extends HttpInetConnection { - - /** - * Indicates whether this connection is secure. - * The return value is well-defined only while the connection is open. - * It may change even while the connection is open. - * - * @return {@code true} if this connection is secure, - * {@code false} otherwise - */ - boolean isSecure(); - - /** - * Obtains the current route of this connection. - * - * @return the route established so far, or - * {@code null} if not connected - */ - HttpRoute getRoute(); - - /** - * Obtains the SSL session of the underlying connection, if any. - * If this connection is open, and the underlying socket is an - * {@link javax.net.ssl.SSLSocket SSLSocket}, the SSL session of - * that socket is obtained. This is a potentially blocking operation. - *

- * Note: Whether the underlying socket is an SSL socket - * can not necessarily be determined via {@link #isSecure}. - * Plain sockets may be considered secure, for example if they are - * connected to a known host in the same network segment. - * On the other hand, SSL sockets may be considered insecure, - * for example depending on the chosen cipher suite. - *

- * - * @return the underlying SSL session if available, - * {@code null} otherwise - */ - SSLSession getSSLSession(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ManagedClientConnection.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ManagedClientConnection.java deleted file mode 100644 index 925e5f46..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ManagedClientConnection.java +++ /dev/null @@ -1,236 +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 com.tracelytics.ext.apache.http.conn; - -import java.io.IOException; -import java.util.concurrent.TimeUnit; - -import javax.net.ssl.SSLSession; - -import com.tracelytics.ext.apache.http.HttpClientConnection; -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -import com.tracelytics.ext.apache.http.conn.routing.HttpRoute; - -/** - * A client-side connection with advanced connection logic. - * Instances are typically obtained from a connection manager. - * - * @since 4.0 - * - * @deprecated (4.3) replaced by {@link HttpClientConnectionManager}. - */ -@Deprecated -public interface ManagedClientConnection extends - HttpClientConnection, HttpRoutedConnection, ManagedHttpClientConnection, ConnectionReleaseTrigger { - - /** - * Indicates whether this connection is secure. - * The return value is well-defined only while the connection is open. - * It may change even while the connection is open. - * - * @return {@code true} if this connection is secure, - * {@code false} otherwise - */ - @Override - boolean isSecure(); - - /** - * Obtains the current route of this connection. - * - * @return the route established so far, or - * {@code null} if not connected - */ - @Override - HttpRoute getRoute(); - - /** - * Obtains the SSL session of the underlying connection, if any. - * If this connection is open, and the underlying socket is an - * {@link javax.net.ssl.SSLSocket SSLSocket}, the SSL session of - * that socket is obtained. This is a potentially blocking operation. - *

- * Note: Whether the underlying socket is an SSL socket - * can not necessarily be determined via {@link #isSecure}. - * Plain sockets may be considered secure, for example if they are - * connected to a known host in the same network segment. - * On the other hand, SSL sockets may be considered insecure, - * for example depending on the chosen cipher suite. - *

- * - * @return the underlying SSL session if available, - * {@code null} otherwise - */ - @Override - SSLSession getSSLSession(); - - /** - * Opens this connection according to the given route. - * - * @param route the route along which to open. It will be opened to - * the first proxy if present, or directly to the target. - * @param context the context for opening this connection - * @param params the parameters for opening this connection - * - * @throws IOException in case of a problem - */ - void open(HttpRoute route, HttpContext context, HttpParams params) - throws IOException; - - /** - * Indicates that a tunnel to the target has been established. - * The route is the one previously passed to {@link #open open}. - * Subsequently, {@link #layerProtocol layerProtocol} can be called - * to layer the TLS/SSL protocol on top of the tunnelled connection. - *

- * Note: In HttpClient 3, a call to the corresponding method - * would automatically trigger the layering of the TLS/SSL protocol. - * This is not the case anymore, you can establish a tunnel without - * layering a new protocol over the connection. - *

- * - * @param secure {@code true} if the tunnel should be considered - * secure, {@code false} otherwise - * @param params the parameters for tunnelling this connection - * - * @throws IOException in case of a problem - */ - void tunnelTarget(boolean secure, HttpParams params) - throws IOException; - - /** - * Indicates that a tunnel to an intermediate proxy has been established. - * This is used exclusively for so-called proxy chains, where - * a request has to pass through multiple proxies before reaching the - * target. In that case, all proxies but the last need to be tunnelled - * when establishing the connection. Tunnelling of the last proxy to the - * target is optional and would be indicated via {@link #tunnelTarget}. - * - * @param next the proxy to which the tunnel was established. - * This is not the proxy through which - * the tunnel was established, but the new end point - * of the tunnel. The tunnel does not yet - * reach to the target, use {@link #tunnelTarget} - * to indicate an end-to-end tunnel. - * @param secure {@code true} if the connection should be - * considered secure, {@code false} otherwise - * @param params the parameters for tunnelling this connection - * - * @throws IOException in case of a problem - */ - void tunnelProxy(HttpHost next, boolean secure, HttpParams params) - throws IOException; - - /** - * Layers a new protocol on top of a {@link #tunnelTarget tunnelled} - * connection. This is typically used to create a TLS/SSL connection - * through a proxy. - * The route is the one previously passed to {@link #open open}. - * It is not guaranteed that the layered connection is - * {@link #isSecure secure}. - * - * @param context the context for layering on top of this connection - * @param params the parameters for layering on top of this connection - * - * @throws IOException in case of a problem - */ - void layerProtocol(HttpContext context, HttpParams params) - throws IOException; - - /** - * Marks this connection as being in a reusable communication state. - * The checkpoints for reuseable communication states (in the absence - * of pipelining) are before sending a request and after receiving - * the response in its entirety. - * The connection will automatically clear the checkpoint when - * used for communication. A call to this method indicates that - * the next checkpoint has been reached. - *

- * A reusable communication state is necessary but not sufficient - * for the connection to be reused. - * A {@link #getRoute route} mismatch, the connection being closed, - * or other circumstances might prevent reuse. - *

- */ - void markReusable(); - - /** - * Marks this connection as not being in a reusable state. - * This can be used immediately before releasing this connection - * to prevent its reuse. Reasons for preventing reuse include - * error conditions and the evaluation of a - * {@link com.tracelytics.ext.apache.http.ConnectionReuseStrategy reuse strategy}. - *

- * Note: - * It is not necessary to call here before writing to - * or reading from this connection. Communication attempts will - * automatically unmark the state as non-reusable. It can then - * be switched back using {@link #markReusable markReusable}. - *

- */ - void unmarkReusable(); - - /** - * Indicates whether this connection is in a reusable communication state. - * See {@link #markReusable markReusable} and - * {@link #unmarkReusable unmarkReusable} for details. - * - * @return {@code true} if this connection is marked as being in - * a reusable communication state, - * {@code false} otherwise - */ - boolean isMarkedReusable(); - - /** - * Assigns a state object to this connection. Connection managers may make - * use of the connection state when allocating persistent connections. - * - * @param state The state object - */ - void setState(Object state); - - /** - * Returns the state object associated with this connection. - * - * @return The state object - */ - Object getState(); - - /** - * Sets the duration that this connection can remain idle before it is - * reused. The connection should not be used again if this time elapses. The - * idle duration must be reset after each request sent over this connection. - * The elapsed time starts counting when the connection is released, which - * is typically after the headers (and any response body, if present) is - * fully consumed. - */ - void setIdleDuration(long duration, TimeUnit unit); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ManagedHttpClientConnection.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ManagedHttpClientConnection.java deleted file mode 100644 index 32bc6939..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ManagedHttpClientConnection.java +++ /dev/null @@ -1,80 +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 com.tracelytics.ext.apache.http.conn; - -import java.io.IOException; -import java.net.Socket; - -import javax.net.ssl.SSLSession; - -import com.tracelytics.ext.apache.http.HttpClientConnection; -import com.tracelytics.ext.apache.http.HttpInetConnection; - -/** - * Represents a managed connection whose state and life cycle is managed by - * a connection manager. This interface extends {@link HttpClientConnection} - * with methods to bind the connection to an arbitrary socket and - * to obtain SSL session details. - * - * @since 4.3 - */ -public interface ManagedHttpClientConnection extends HttpClientConnection, HttpInetConnection { - - /** - * Returns connection ID which is expected to be unique - * for the life span of the connection manager. - */ - String getId(); - - /** - * Binds this connection to the given socket. The connection - * is considered open if it is bound and the underlying socket - * is connection to a remote host. - * - * @param socket the socket to bind the connection to. - * @throws IOException - */ - void bind(Socket socket) throws IOException; - - /** - * Returns the underlying socket. - */ - Socket getSocket(); - - /** - * Obtains the SSL session of the underlying connection, if any. - * If this connection is open, and the underlying socket is an - * {@link javax.net.ssl.SSLSocket SSLSocket}, the SSL session of - * that socket is obtained. This is a potentially blocking operation. - * - * @return the underlying SSL session if available, - * {@code null} otherwise - */ - SSLSession getSSLSession(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/SchemePortResolver.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/SchemePortResolver.java deleted file mode 100644 index 09e674d9..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/SchemePortResolver.java +++ /dev/null @@ -1,43 +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 com.tracelytics.ext.apache.http.conn; - -import com.tracelytics.ext.apache.http.HttpHost; - -/** - * Strategy for default port resolution for protocol schemes. - * - * @since 4.3 - */ -public interface SchemePortResolver { - - /** - * Returns the actual port for the host based on the protocol scheme. - */ - int resolve(HttpHost host) throws UnsupportedSchemeException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/UnsupportedSchemeException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/UnsupportedSchemeException.java deleted file mode 100644 index 9ef8a981..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/UnsupportedSchemeException.java +++ /dev/null @@ -1,51 +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 com.tracelytics.ext.apache.http.conn; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.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; - - /** - * Creates a UnsupportedSchemeException with the specified detail message. - */ - public UnsupportedSchemeException(final String message) { - super(message); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/package-info.java deleted file mode 100644 index 0b06edd1..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/package-info.java +++ /dev/null @@ -1,31 +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 - * . - * - */ - -/** - * Client connection management APIs. - */ -package com.tracelytics.ext.apache.http.conn; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/params/ConnConnectionPNames.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/params/ConnConnectionPNames.java deleted file mode 100644 index af119bc7..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/params/ConnConnectionPNames.java +++ /dev/null @@ -1,64 +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 com.tracelytics.ext.apache.http.conn.params; - -/** - * Parameter names for HTTP client connections. - * - * @since 4.0 - * - * @deprecated (4.1) use custom {@link - * com.tracelytics.ext.apache.http.impl.conn.DefaultHttpResponseParser} implementation. - */ -@Deprecated -public interface ConnConnectionPNames { - - /** - * Defines the maximum number of ignorable lines before we expect - * a HTTP response's status line. - *

- * With HTTP/1.1 persistent connections, the problem arises that - * broken scripts could return a wrong Content-Length - * (there are more bytes sent than specified). - * Unfortunately, in some cases, this cannot be detected after the - * bad response, but only before the next one. - * So HttpClient must be able to skip those surplus lines this way. - *

- *

- * This parameter expects a value of type {@link Integer}. - * 0 disallows all garbage/empty lines before the status line. - * Use {@link java.lang.Integer#MAX_VALUE} for unlimited number. - *

- * - * @deprecated (4.1) Use custom {@link - * com.tracelytics.ext.apache.http.impl.conn.DefaultHttpResponseParser} implementation - */ - @Deprecated - public static final String MAX_STATUS_LINE_GARBAGE = "http.connection.max-status-line-garbage"; - - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/params/ConnManagerPNames.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/params/ConnManagerPNames.java deleted file mode 100644 index 2bbd941f..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/params/ConnManagerPNames.java +++ /dev/null @@ -1,67 +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 com.tracelytics.ext.apache.http.conn.params; - -/** - * Parameter names for connection managers in HttpConn. - * - * @since 4.0 - * - * @deprecated (4.1) use configuration methods of the specific connection manager implementation. -*/ -@Deprecated -public interface ConnManagerPNames { - - /** - * Defines the timeout in milliseconds used when retrieving an instance of - * {@link com.tracelytics.ext.apache.http.conn.ManagedClientConnection} from the - * {@link com.tracelytics.ext.apache.http.conn.ClientConnectionManager}. - *

- * This parameter expects a value of type {@link Long}. - */ - public static final String TIMEOUT = "http.conn-manager.timeout"; - - /** - * Defines the maximum number of connections per route. - * This limit is interpreted by client connection managers - * and applies to individual manager instances. - *

- * This parameter expects a value of type {@link ConnPerRoute}. - *

- */ - public static final String MAX_CONNECTIONS_PER_ROUTE = "http.conn-manager.max-per-route"; - - /** - * Defines the maximum number of connections in total. - * This limit is interpreted by client connection managers - * and applies to individual manager instances. - *

- * This parameter expects a value of type {@link Integer}. - */ - public static final String MAX_TOTAL_CONNECTIONS = "http.conn-manager.max-total"; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/params/ConnRoutePNames.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/params/ConnRoutePNames.java deleted file mode 100644 index dccd63f6..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/params/ConnRoutePNames.java +++ /dev/null @@ -1,79 +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 com.tracelytics.ext.apache.http.conn.params; - -/** - * Parameter names for connection routing. - * - * @since 4.0 - * - * @deprecated (4.3) use {@link com.tracelytics.ext.apache.http.client.config.RequestConfig}. - */ -@Deprecated -public interface ConnRoutePNames { - - /** - * Parameter for the default proxy. - * The default value will be used by some - * {@link com.tracelytics.ext.apache.http.conn.routing.HttpRoutePlanner HttpRoutePlanner} - * implementations, in particular the default implementation. - *

- * This parameter expects a value of type {@link com.tracelytics.ext.apache.http.HttpHost}. - *

- */ - public static final String DEFAULT_PROXY = "http.route.default-proxy"; - - /** - * Parameter for the local address. - * On machines with multiple network interfaces, this parameter - * can be used to select the network interface from which the - * connection originates. - * It will be interpreted by the standard - * {@link com.tracelytics.ext.apache.http.conn.routing.HttpRoutePlanner HttpRoutePlanner} - * implementations, in particular the default implementation. - *

- * This parameter expects a value of type {@link java.net.InetAddress}. - *

- */ - public static final String LOCAL_ADDRESS = "http.route.local-address"; - - /** - * Parameter for an forced route. - * The forced route will be interpreted by the standard - * {@link com.tracelytics.ext.apache.http.conn.routing.HttpRoutePlanner HttpRoutePlanner} - * implementations. - * Instead of computing a route, the given forced route will be - * returned, even if it points to the wrong target host. - *

- * This parameter expects a value of type - * {@link com.tracelytics.ext.apache.http.conn.routing.HttpRoute HttpRoute}. - *

- */ - public static final String FORCED_ROUTE = "http.route.forced-route"; - -} - diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/params/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/params/package-info.java deleted file mode 100644 index 570841e0..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/params/package-info.java +++ /dev/null @@ -1,32 +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 - * . - * - */ - -/** - * Deprecated. - * @deprecated (4.3). - */ -package com.tracelytics.ext.apache.http.conn.params; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/routing/BasicRouteDirector.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/routing/BasicRouteDirector.java deleted file mode 100644 index f415b2aa..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/routing/BasicRouteDirector.java +++ /dev/null @@ -1,182 +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 com.tracelytics.ext.apache.http.conn.routing; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Basic {@link HttpRouteDirector} implementation. - * - * @since 4.0 - */ -@Immutable -public class BasicRouteDirector implements HttpRouteDirector { - - /** - * Provides the next step. - * - * @param plan the planned route - * @param fact the currently established route, or - * {@code null} if nothing is established - * - * @return one of the constants defined in this class, indicating - * either the next step to perform, or success, or failure. - * 0 is for success, a negative value for failure. - */ - @Override - public int nextStep(final RouteInfo plan, final RouteInfo fact) { - Args.notNull(plan, "Planned route"); - - int step = UNREACHABLE; - - if ((fact == null) || (fact.getHopCount() < 1)) { - step = firstStep(plan); - } else if (plan.getHopCount() > 1) { - step = proxiedStep(plan, fact); - } else { - step = directStep(plan, fact); - } - - return step; - - } // nextStep - - - /** - * Determines the first step to establish a route. - * - * @param plan the planned route - * - * @return the first step - */ - protected int firstStep(final RouteInfo plan) { - - return (plan.getHopCount() > 1) ? - CONNECT_PROXY : CONNECT_TARGET; - } - - - /** - * Determines the next step to establish a direct connection. - * - * @param plan the planned route - * @param fact the currently established route - * - * @return one of the constants defined in this class, indicating - * either the next step to perform, or success, or failure - */ - protected int directStep(final RouteInfo plan, final RouteInfo fact) { - - if (fact.getHopCount() > 1) { - return UNREACHABLE; - } - if (!plan.getTargetHost().equals(fact.getTargetHost())) - { - return UNREACHABLE; - // If the security is too low, we could now suggest to layer - // a secure protocol on the direct connection. Layering on direct - // connections has not been supported in HttpClient 3.x, we don't - // consider it here until there is a real-life use case for it. - } - - // Should we tolerate if security is better than planned? - // (plan.isSecure() && !fact.isSecure()) - if (plan.isSecure() != fact.isSecure()) { - return UNREACHABLE; - } - - // Local address has to match only if the plan specifies one. - if ((plan.getLocalAddress() != null) && - !plan.getLocalAddress().equals(fact.getLocalAddress()) - ) { - return UNREACHABLE; - } - - return COMPLETE; - } - - - /** - * Determines the next step to establish a connection via proxy. - * - * @param plan the planned route - * @param fact the currently established route - * - * @return one of the constants defined in this class, indicating - * either the next step to perform, or success, or failure - */ - protected int proxiedStep(final RouteInfo plan, final RouteInfo fact) { - - if (fact.getHopCount() <= 1) { - return UNREACHABLE; - } - if (!plan.getTargetHost().equals(fact.getTargetHost())) { - return UNREACHABLE; - } - final int phc = plan.getHopCount(); - final int fhc = fact.getHopCount(); - if (phc < fhc) { - return UNREACHABLE; - } - - for (int i=0; i fhc) - { - return TUNNEL_PROXY; // need to extend the proxy chain - } - - // proxy chain and target are the same, check tunnelling and layering - if ((fact.isTunnelled() && !plan.isTunnelled()) || - (fact.isLayered() && !plan.isLayered())) { - return UNREACHABLE; - } - - if (plan.isTunnelled() && !fact.isTunnelled()) { - return TUNNEL_TARGET; - } - if (plan.isLayered() && !fact.isLayered()) { - return LAYER_PROTOCOL; - } - - // tunnel and layering are the same, remains to check the security - // Should we tolerate if security is better than planned? - // (plan.isSecure() && !fact.isSecure()) - if (plan.isSecure() != fact.isSecure()) { - return UNREACHABLE; - } - - return COMPLETE; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/routing/HttpRoute.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/routing/HttpRoute.java deleted file mode 100644 index caa78c37..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/routing/HttpRoute.java +++ /dev/null @@ -1,366 +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 com.tracelytics.ext.apache.http.conn.routing; - -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.LangUtils; - -/** - * The route for a request. - * - * @since 4.0 - */ -@Immutable -public final class HttpRoute implements RouteInfo, Cloneable { - - /** The target host to connect to. */ - private final HttpHost targetHost; - - /** - * The local address to connect from. - * {@code null} indicates that the default should be used. - */ - private final InetAddress localAddress; - - /** The proxy servers, if any. Never null. */ - private final List proxyChain; - - /** Whether the the route is tunnelled through the proxy. */ - private final TunnelType tunnelled; - - /** Whether the route is layered. */ - private final LayerType layered; - - /** Whether the route is (supposed to be) secure. */ - private final boolean secure; - - private HttpRoute(final HttpHost target, final InetAddress local, final List proxies, - final boolean secure, final TunnelType tunnelled, final LayerType layered) { - Args.notNull(target, "Target host"); - this.targetHost = normalize(target); - this.localAddress = local; - if (proxies != null && !proxies.isEmpty()) { - this.proxyChain = new ArrayList(proxies); - } else { - this.proxyChain = null; - } - if (tunnelled == TunnelType.TUNNELLED) { - Args.check(this.proxyChain != null, "Proxy required if tunnelled"); - } - this.secure = secure; - this.tunnelled = tunnelled != null ? tunnelled : TunnelType.PLAIN; - this.layered = layered != null ? layered : LayerType.PLAIN; - } - - //TODO: to be removed in 5.0 - private static int getDefaultPort(final String schemeName) { - if ("http".equalsIgnoreCase(schemeName)) { - return 80; - } else if ("https".equalsIgnoreCase(schemeName)) { - return 443; - } else { - return -1; - } - - } - - //TODO: to be removed in 5.0 - private static HttpHost normalize(final HttpHost target) { - if (target.getPort() >= 0 ) { - return target; - } else { - final InetAddress address = target.getAddress(); - final String schemeName = target.getSchemeName(); - if (address != null) { - return new HttpHost(address, getDefaultPort(schemeName), schemeName); - } else { - final String hostName = target.getHostName(); - return new HttpHost(hostName, getDefaultPort(schemeName), schemeName); - } - } - } - - /** - * Creates a new route with all attributes specified explicitly. - * - * @param target the host to which to route - * @param local the local address to route from, or - * {@code null} for the default - * @param proxies the proxy chain to use, or - * {@code null} for a direct route - * @param secure {@code true} if the route is (to be) secure, - * {@code false} otherwise - * @param tunnelled the tunnel type of this route - * @param layered the layering type of this route - */ - public HttpRoute(final HttpHost target, final InetAddress local, final HttpHost[] proxies, - final boolean secure, final TunnelType tunnelled, final LayerType layered) { - this(target, local, proxies != null ? Arrays.asList(proxies) : null, - secure, tunnelled, layered); - } - - /** - * Creates a new route with at most one proxy. - * - * @param target the host to which to route - * @param local the local address to route from, or - * {@code null} for the default - * @param proxy the proxy to use, or - * {@code null} for a direct route - * @param secure {@code true} if the route is (to be) secure, - * {@code false} otherwise - * @param tunnelled {@code true} if the route is (to be) tunnelled - * via the proxy, - * {@code false} otherwise - * @param layered {@code true} if the route includes a - * layered protocol, - * {@code false} otherwise - */ - public HttpRoute(final HttpHost target, final InetAddress local, final HttpHost proxy, - final boolean secure, final TunnelType tunnelled, final LayerType layered) { - this(target, local, proxy != null ? Collections.singletonList(proxy) : null, - secure, tunnelled, layered); - } - - /** - * Creates a new direct route. - * That is a route without a proxy. - * - * @param target the host to which to route - * @param local the local address to route from, or - * {@code null} for the default - * @param secure {@code true} if the route is (to be) secure, - * {@code false} otherwise - */ - public HttpRoute(final HttpHost target, final InetAddress local, final boolean secure) { - this(target, local, Collections.emptyList(), secure, - TunnelType.PLAIN, LayerType.PLAIN); - } - - /** - * Creates a new direct insecure route. - * - * @param target the host to which to route - */ - public HttpRoute(final HttpHost target) { - this(target, null, Collections.emptyList(), false, - TunnelType.PLAIN, LayerType.PLAIN); - } - - /** - * Creates a new route through a proxy. - * When using this constructor, the {@code proxy} MUST be given. - * For convenience, it is assumed that a secure connection will be - * layered over a tunnel through the proxy. - * - * @param target the host to which to route - * @param local the local address to route from, or - * {@code null} for the default - * @param proxy the proxy to use - * @param secure {@code true} if the route is (to be) secure, - * {@code false} otherwise - */ - public HttpRoute(final HttpHost target, final InetAddress local, final HttpHost proxy, - final boolean secure) { - this(target, local, Collections.singletonList(Args.notNull(proxy, "Proxy host")), secure, - secure ? TunnelType.TUNNELLED : TunnelType.PLAIN, - secure ? LayerType.LAYERED : LayerType.PLAIN); - } - - /** - * Creates a new plain route through a proxy. - * - * @param target the host to which to route - * @param proxy the proxy to use - * - * @since 4.3 - */ - public HttpRoute(final HttpHost target, final HttpHost proxy) { - this(target, null, proxy, false); - } - - @Override - public final HttpHost getTargetHost() { - return this.targetHost; - } - - @Override - public final InetAddress getLocalAddress() { - return this.localAddress; - } - - public final InetSocketAddress getLocalSocketAddress() { - return this.localAddress != null ? new InetSocketAddress(this.localAddress, 0) : null; - } - - @Override - public final int getHopCount() { - return proxyChain != null ? proxyChain.size() + 1 : 1; - } - - @Override - public final HttpHost getHopTarget(final int hop) { - Args.notNegative(hop, "Hop index"); - final int hopcount = getHopCount(); - Args.check(hop < hopcount, "Hop index exceeds tracked route length"); - if (hop < hopcount - 1) { - return this.proxyChain.get(hop); - } else { - return this.targetHost; - } - } - - @Override - public final HttpHost getProxyHost() { - return proxyChain != null && !this.proxyChain.isEmpty() ? this.proxyChain.get(0) : null; - } - - @Override - public final TunnelType getTunnelType() { - return this.tunnelled; - } - - @Override - public final boolean isTunnelled() { - return (this.tunnelled == TunnelType.TUNNELLED); - } - - @Override - public final LayerType getLayerType() { - return this.layered; - } - - @Override - public final boolean isLayered() { - return (this.layered == LayerType.LAYERED); - } - - @Override - public final boolean isSecure() { - return this.secure; - } - - /** - * Compares this route to another. - * - * @param obj the object to compare with - * - * @return {@code true} if the argument is the same route, - * {@code false} - */ - @Override - public final boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof HttpRoute) { - final HttpRoute that = (HttpRoute) obj; - return - // Do the cheapest tests first - (this.secure == that.secure) && - (this.tunnelled == that.tunnelled) && - (this.layered == that.layered) && - LangUtils.equals(this.targetHost, that.targetHost) && - LangUtils.equals(this.localAddress, that.localAddress) && - LangUtils.equals(this.proxyChain, that.proxyChain); - } else { - return false; - } - } - - - /** - * Generates a hash code for this route. - * - * @return the hash code - */ - @Override - public final int hashCode() { - int hash = LangUtils.HASH_SEED; - hash = LangUtils.hashCode(hash, this.targetHost); - hash = LangUtils.hashCode(hash, this.localAddress); - if (this.proxyChain != null) { - for (final HttpHost element : this.proxyChain) { - hash = LangUtils.hashCode(hash, element); - } - } - hash = LangUtils.hashCode(hash, this.secure); - hash = LangUtils.hashCode(hash, this.tunnelled); - hash = LangUtils.hashCode(hash, this.layered); - return hash; - } - - /** - * Obtains a description of this route. - * - * @return a human-readable representation of this route - */ - @Override - public final String toString() { - final StringBuilder cab = new StringBuilder(50 + getHopCount()*30); - if (this.localAddress != null) { - cab.append(this.localAddress); - cab.append("->"); - } - cab.append('{'); - if (this.tunnelled == TunnelType.TUNNELLED) { - cab.append('t'); - } - if (this.layered == LayerType.LAYERED) { - cab.append('l'); - } - if (this.secure) { - cab.append('s'); - } - cab.append("}->"); - if (this.proxyChain != null) { - for (final HttpHost aProxyChain : this.proxyChain) { - cab.append(aProxyChain); - cab.append("->"); - } - } - cab.append(this.targetHost); - return cab.toString(); - } - - // default implementation of clone() is sufficient - @Override - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/routing/HttpRouteDirector.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/routing/HttpRouteDirector.java deleted file mode 100644 index 15c5b88a..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/routing/HttpRouteDirector.java +++ /dev/null @@ -1,74 +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 com.tracelytics.ext.apache.http.conn.routing; - -/** - * Provides directions on establishing a route. - * Implementations of this interface compare a planned route with - * a tracked route and indicate the next step required. - * - * @since 4.0 - */ -public interface HttpRouteDirector { - - /** Indicates that the route can not be established at all. */ - public final static int UNREACHABLE = -1; - - /** Indicates that the route is complete. */ - public final static int COMPLETE = 0; - - /** Step: open connection to target. */ - public final static int CONNECT_TARGET = 1; - - /** Step: open connection to proxy. */ - public final static int CONNECT_PROXY = 2; - - /** Step: tunnel through proxy to target. */ - public final static int TUNNEL_TARGET = 3; - - /** Step: tunnel through proxy to other proxy. */ - public final static int TUNNEL_PROXY = 4; - - /** Step: layer protocol (over tunnel). */ - public final static int LAYER_PROTOCOL = 5; - - - /** - * Provides the next step. - * - * @param plan the planned route - * @param fact the currently established route, or - * {@code null} if nothing is established - * - * @return one of the constants defined in this interface, indicating - * either the next step to perform, or success, or failure. - * 0 is for success, a negative value for failure. - */ - public int nextStep(RouteInfo plan, RouteInfo fact); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/routing/HttpRoutePlanner.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/routing/HttpRoutePlanner.java deleted file mode 100644 index 3079eabb..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/routing/HttpRoutePlanner.java +++ /dev/null @@ -1,68 +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 com.tracelytics.ext.apache.http.conn.routing; - -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -/** - * Encapsulates logic to compute a {@link HttpRoute} to a target host. - * Implementations may for example be based on parameters, or on the - * standard Java system properties. - *

- * Implementations of this interface must be thread-safe. Access to shared - * data must be synchronized as methods of this interface may be executed - * from multiple threads. - *

- * - * @since 4.0 - */ -public interface HttpRoutePlanner { - - /** - * Determines the route for a request. - * - * @param target the target host for the request. - * Implementations may accept {@code null} - * if they can still determine a route, for example - * to a default target or by inspecting the request. - * @param request the request to execute - * @param context the context to use for the subsequent execution. - * Implementations may accept {@code null}. - * - * @return the route that the request should take - * - * @throws HttpException in case of a problem - */ - public HttpRoute determineRoute(HttpHost target, - HttpRequest request, - HttpContext context) throws HttpException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/routing/RouteInfo.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/routing/RouteInfo.java deleted file mode 100644 index 40044e57..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/routing/RouteInfo.java +++ /dev/null @@ -1,162 +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 com.tracelytics.ext.apache.http.conn.routing; - -import java.net.InetAddress; - -import com.tracelytics.ext.apache.http.HttpHost; - -/** - * Read-only interface for route information. - * - * @since 4.0 - */ -public interface RouteInfo { - - /** - * The tunnelling type of a route. - * Plain routes are established by connecting to the target or - * the first proxy. - * Tunnelled routes are established by connecting to the first proxy - * and tunnelling through all proxies to the target. - * Routes without a proxy cannot be tunnelled. - */ - public enum TunnelType { PLAIN, TUNNELLED } - - /** - * The layering type of a route. - * Plain routes are established by connecting or tunnelling. - * Layered routes are established by layering a protocol such as TLS/SSL - * over an existing connection. - * Protocols can only be layered over a tunnel to the target, or - * or over a direct connection without proxies. - *

- * Layering a protocol - * over a direct connection makes little sense, since the connection - * could be established with the new protocol in the first place. - * But we don't want to exclude that use case. - *

- */ - public enum LayerType { PLAIN, LAYERED } - - /** - * Obtains the target host. - * - * @return the target host - */ - HttpHost getTargetHost(); - - /** - * Obtains the local address to connect from. - * - * @return the local address, - * or {@code null} - */ - InetAddress getLocalAddress(); - - /** - * Obtains the number of hops in this route. - * A direct route has one hop. A route through a proxy has two hops. - * A route through a chain of n proxies has n+1 hops. - * - * @return the number of hops in this route - */ - int getHopCount(); - - /** - * Obtains the target of a hop in this route. - * The target of the last hop is the {@link #getTargetHost target host}, - * the target of previous hops is the respective proxy in the chain. - * For a route through exactly one proxy, target of hop 0 is the proxy - * and target of hop 1 is the target host. - * - * @param hop index of the hop for which to get the target, - * 0 for first - * - * @return the target of the given hop - * - * @throws IllegalArgumentException - * if the argument is negative or not less than - * {@link #getHopCount getHopCount()} - */ - HttpHost getHopTarget(int hop); - - /** - * Obtains the first proxy host. - * - * @return the first proxy in the proxy chain, or - * {@code null} if this route is direct - */ - HttpHost getProxyHost(); - - /** - * Obtains the tunnel type of this route. - * If there is a proxy chain, only end-to-end tunnels are considered. - * - * @return the tunnelling type - */ - TunnelType getTunnelType(); - - /** - * Checks whether this route is tunnelled through a proxy. - * If there is a proxy chain, only end-to-end tunnels are considered. - * - * @return {@code true} if tunnelled end-to-end through at least - * one proxy, - * {@code false} otherwise - */ - boolean isTunnelled(); - - /** - * Obtains the layering type of this route. - * In the presence of proxies, only layering over an end-to-end tunnel - * is considered. - * - * @return the layering type - */ - LayerType getLayerType(); - - /** - * Checks whether this route includes a layered protocol. - * In the presence of proxies, only layering over an end-to-end tunnel - * is considered. - * - * @return {@code true} if layered, - * {@code false} otherwise - */ - boolean isLayered(); - - /** - * Checks whether this route is secure. - * - * @return {@code true} if secure, - * {@code false} otherwise - */ - boolean isSecure(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/routing/RouteTracker.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/routing/RouteTracker.java deleted file mode 100644 index a178a864..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/routing/RouteTracker.java +++ /dev/null @@ -1,376 +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 com.tracelytics.ext.apache.http.conn.routing; - -import java.net.InetAddress; - -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.Asserts; -import com.tracelytics.ext.apache.http.util.LangUtils; - -/** - * Helps tracking the steps in establishing a route. - * - * @since 4.0 - */ -@NotThreadSafe -public final class RouteTracker implements RouteInfo, Cloneable { - - /** The target host to connect to. */ - private final HttpHost targetHost; - - /** - * The local address to connect from. - * {@code null} indicates that the default should be used. - */ - private final InetAddress localAddress; - - // the attributes above are fixed at construction time - // now follow attributes that indicate the established route - - /** Whether the first hop of the route is established. */ - private boolean connected; - - /** The proxy chain, if any. */ - private HttpHost[] proxyChain; - - /** Whether the the route is tunnelled end-to-end through proxies. */ - private TunnelType tunnelled; - - /** Whether the route is layered over a tunnel. */ - private LayerType layered; - - /** Whether the route is secure. */ - private boolean secure; - - /** - * Creates a new route tracker. - * The target and origin need to be specified at creation time. - * - * @param target the host to which to route - * @param local the local address to route from, or - * {@code null} for the default - */ - public RouteTracker(final HttpHost target, final InetAddress local) { - Args.notNull(target, "Target host"); - this.targetHost = target; - this.localAddress = local; - this.tunnelled = TunnelType.PLAIN; - this.layered = LayerType.PLAIN; - } - - /** - * @since 4.2 - */ - public void reset() { - this.connected = false; - this.proxyChain = null; - this.tunnelled = TunnelType.PLAIN; - this.layered = LayerType.PLAIN; - this.secure = false; - } - - /** - * Creates a new tracker for the given route. - * Only target and origin are taken from the route, - * everything else remains to be tracked. - * - * @param route the route to track - */ - public RouteTracker(final HttpRoute route) { - this(route.getTargetHost(), route.getLocalAddress()); - } - - /** - * Tracks connecting to the target. - * - * @param secure {@code true} if the route is secure, - * {@code false} otherwise - */ - public final void connectTarget(final boolean secure) { - Asserts.check(!this.connected, "Already connected"); - this.connected = true; - this.secure = secure; - } - - /** - * Tracks connecting to the first proxy. - * - * @param proxy the proxy connected to - * @param secure {@code true} if the route is secure, - * {@code false} otherwise - */ - public final void connectProxy(final HttpHost proxy, final boolean secure) { - Args.notNull(proxy, "Proxy host"); - Asserts.check(!this.connected, "Already connected"); - this.connected = true; - this.proxyChain = new HttpHost[]{ proxy }; - this.secure = secure; - } - - /** - * Tracks tunnelling to the target. - * - * @param secure {@code true} if the route is secure, - * {@code false} otherwise - */ - public final void tunnelTarget(final boolean secure) { - Asserts.check(this.connected, "No tunnel unless connected"); - Asserts.notNull(this.proxyChain, "No tunnel without proxy"); - this.tunnelled = TunnelType.TUNNELLED; - this.secure = secure; - } - - /** - * Tracks tunnelling to a proxy in a proxy chain. - * This will extend the tracked proxy chain, but it does not mark - * the route as tunnelled. Only end-to-end tunnels are considered there. - * - * @param proxy the proxy tunnelled to - * @param secure {@code true} if the route is secure, - * {@code false} otherwise - */ - public final void tunnelProxy(final HttpHost proxy, final boolean secure) { - Args.notNull(proxy, "Proxy host"); - Asserts.check(this.connected, "No tunnel unless connected"); - Asserts.notNull(this.proxyChain, "No tunnel without proxy"); - // prepare an extended proxy chain - final HttpHost[] proxies = new HttpHost[this.proxyChain.length+1]; - System.arraycopy(this.proxyChain, 0, - proxies, 0, this.proxyChain.length); - proxies[proxies.length-1] = proxy; - - this.proxyChain = proxies; - this.secure = secure; - } - - /** - * Tracks layering a protocol. - * - * @param secure {@code true} if the route is secure, - * {@code false} otherwise - */ - public final void layerProtocol(final boolean secure) { - // it is possible to layer a protocol over a direct connection, - // although this case is probably not considered elsewhere - Asserts.check(this.connected, "No layered protocol unless connected"); - this.layered = LayerType.LAYERED; - this.secure = secure; - } - - @Override - public final HttpHost getTargetHost() { - return this.targetHost; - } - - @Override - public final InetAddress getLocalAddress() { - return this.localAddress; - } - - @Override - public final int getHopCount() { - int hops = 0; - if (this.connected) { - if (proxyChain == null) { - hops = 1; - } else { - hops = proxyChain.length + 1; - } - } - return hops; - } - - @Override - public final HttpHost getHopTarget(final int hop) { - Args.notNegative(hop, "Hop index"); - final int hopcount = getHopCount(); - Args.check(hop < hopcount, "Hop index exceeds tracked route length"); - HttpHost result = null; - if (hop < hopcount-1) { - result = this.proxyChain[hop]; - } else { - result = this.targetHost; - } - - return result; - } - - @Override - public final HttpHost getProxyHost() { - return (this.proxyChain == null) ? null : this.proxyChain[0]; - } - - public final boolean isConnected() { - return this.connected; - } - - @Override - public final TunnelType getTunnelType() { - return this.tunnelled; - } - - @Override - public final boolean isTunnelled() { - return (this.tunnelled == TunnelType.TUNNELLED); - } - - @Override - public final LayerType getLayerType() { - return this.layered; - } - - @Override - public final boolean isLayered() { - return (this.layered == LayerType.LAYERED); - } - - @Override - public final boolean isSecure() { - return this.secure; - } - - /** - * Obtains the tracked route. - * If a route has been tracked, it is {@link #isConnected connected}. - * If not connected, nothing has been tracked so far. - * - * @return the tracked route, or - * {@code null} if nothing has been tracked so far - */ - public final HttpRoute toRoute() { - return !this.connected ? - null : new HttpRoute(this.targetHost, this.localAddress, - this.proxyChain, this.secure, - this.tunnelled, this.layered); - } - - /** - * Compares this tracked route to another. - * - * @param o the object to compare with - * - * @return {@code true} if the argument is the same tracked route, - * {@code false} - */ - @Override - public final boolean equals(final Object o) { - if (o == this) { - return true; - } - if (!(o instanceof RouteTracker)) { - return false; - } - - final RouteTracker that = (RouteTracker) o; - return - // Do the cheapest checks first - (this.connected == that.connected) && - (this.secure == that.secure) && - (this.tunnelled == that.tunnelled) && - (this.layered == that.layered) && - LangUtils.equals(this.targetHost, that.targetHost) && - LangUtils.equals(this.localAddress, that.localAddress) && - LangUtils.equals(this.proxyChain, that.proxyChain); - } - - /** - * Generates a hash code for this tracked route. - * Route trackers are modifiable and should therefore not be used - * as lookup keys. Use {@link #toRoute toRoute} to obtain an - * unmodifiable representation of the tracked route. - * - * @return the hash code - */ - @Override - public final int hashCode() { - int hash = LangUtils.HASH_SEED; - hash = LangUtils.hashCode(hash, this.targetHost); - hash = LangUtils.hashCode(hash, this.localAddress); - if (this.proxyChain != null) { - for (final HttpHost element : this.proxyChain) { - hash = LangUtils.hashCode(hash, element); - } - } - hash = LangUtils.hashCode(hash, this.connected); - hash = LangUtils.hashCode(hash, this.secure); - hash = LangUtils.hashCode(hash, this.tunnelled); - hash = LangUtils.hashCode(hash, this.layered); - return hash; - } - - /** - * Obtains a description of the tracked route. - * - * @return a human-readable representation of the tracked route - */ - @Override - public final String toString() { - final StringBuilder cab = new StringBuilder(50 + getHopCount()*30); - - cab.append("RouteTracker["); - if (this.localAddress != null) { - cab.append(this.localAddress); - cab.append("->"); - } - cab.append('{'); - if (this.connected) { - cab.append('c'); - } - if (this.tunnelled == TunnelType.TUNNELLED) { - cab.append('t'); - } - if (this.layered == LayerType.LAYERED) { - cab.append('l'); - } - if (this.secure) { - cab.append('s'); - } - cab.append("}->"); - if (this.proxyChain != null) { - for (final HttpHost element : this.proxyChain) { - cab.append(element); - cab.append("->"); - } - } - cab.append(this.targetHost); - cab.append(']'); - - return cab.toString(); - } - - - // default implementation of clone() is sufficient - @Override - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/routing/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/routing/package-info.java deleted file mode 100644 index 77648c7b..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/routing/package-info.java +++ /dev/null @@ -1,31 +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 - * . - * - */ - -/** - * Client connection routing APIs. - */ -package com.tracelytics.ext.apache.http.conn.routing; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/LayeredSchemeSocketFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/LayeredSchemeSocketFactory.java deleted file mode 100644 index f2fe2716..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/LayeredSchemeSocketFactory.java +++ /dev/null @@ -1,68 +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 com.tracelytics.ext.apache.http.conn.scheme; - -import java.io.IOException; -import java.net.Socket; -import java.net.UnknownHostException; - -/** - * Extended {@link SchemeSocketFactory} interface for layered sockets such as SSL/TLS. - * - * @since 4.1 - * - * @deprecated (4.2) use {@link SchemeLayeredSocketFactory} - */ -@Deprecated -public interface LayeredSchemeSocketFactory extends SchemeSocketFactory { - - /** - * Returns a socket connected to the given host that is layered over an - * existing socket. Used primarily for creating secure sockets through - * proxies. - * - * @param socket the existing socket - * @param target the name of the target host. - * @param port the port to connect to on the target host - * @param autoClose a flag for closing the underling socket when the created - * socket is closed - * - * @return Socket a new socket - * - * @throws IOException if an I/O error occurs while creating the socket - * @throws UnknownHostException if the IP address of the host cannot be - * determined - */ - Socket createLayeredSocket( - Socket socket, - String target, - int port, - boolean autoClose - ) throws IOException, UnknownHostException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/LayeredSocketFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/LayeredSocketFactory.java deleted file mode 100644 index d6e1d32e..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/LayeredSocketFactory.java +++ /dev/null @@ -1,69 +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 com.tracelytics.ext.apache.http.conn.scheme; - -import java.io.IOException; -import java.net.Socket; -import java.net.UnknownHostException; - -/** - * A {@link SocketFactory SocketFactory} for layered sockets (SSL/TLS). - * See there for things to consider when implementing a socket factory. - * - * @since 4.0 - * - * @deprecated (4.1) use {@link SchemeSocketFactory} - */ -@Deprecated -public interface LayeredSocketFactory extends SocketFactory { - - /** - * Returns a socket connected to the given host that is layered over an - * existing socket. Used primarily for creating secure sockets through - * proxies. - * - * @param socket the existing socket - * @param host the host name/IP - * @param port the port on the host - * @param autoClose a flag for closing the underling socket when the created - * socket is closed - * - * @return Socket a new socket - * - * @throws IOException if an I/O error occurs while creating the socket - * @throws UnknownHostException if the IP address of the host cannot be - * determined - */ - Socket createSocket( - Socket socket, - String host, - int port, - boolean autoClose - ) throws IOException, UnknownHostException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/LayeredSocketFactoryAdaptor.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/LayeredSocketFactoryAdaptor.java deleted file mode 100644 index e21d5021..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/LayeredSocketFactoryAdaptor.java +++ /dev/null @@ -1,54 +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 com.tracelytics.ext.apache.http.conn.scheme; - -import java.io.IOException; -import java.net.Socket; -import java.net.UnknownHostException; - -/** - * @deprecated (4.1) do not use - */ -@Deprecated -class LayeredSocketFactoryAdaptor extends SocketFactoryAdaptor implements LayeredSocketFactory { - - private final LayeredSchemeSocketFactory factory; - - LayeredSocketFactoryAdaptor(final LayeredSchemeSocketFactory factory) { - super(factory); - this.factory = factory; - } - - @Override - public Socket createSocket( - final Socket socket, - final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException { - return this.factory.createLayeredSocket(socket, host, port, autoClose); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/Scheme.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/Scheme.java deleted file mode 100644 index 06b0a810..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/Scheme.java +++ /dev/null @@ -1,261 +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 com.tracelytics.ext.apache.http.conn.scheme; - -import java.util.Locale; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.LangUtils; - -/** - * Encapsulates specifics of a protocol scheme such as "http" or "https". Schemes are identified - * by lowercase names. Supported schemes are typically collected in a {@link SchemeRegistry - * SchemeRegistry}. - *

- * For example, to configure support for "https://" URLs, you could write code like the following: - *

- *
- * Scheme https = new Scheme("https", 443, new MySecureSocketFactory());
- * SchemeRegistry registry = new SchemeRegistry();
- * registry.register(https);
- * 
- * - * @since 4.0 - * - * @deprecated (4.3) use {@link com.tracelytics.ext.apache.http.conn.SchemePortResolver} for default port - * resolution and {@link com.tracelytics.ext.apache.http.config.Registry} for socket factory lookups. - */ -@Immutable -@Deprecated -public final class Scheme { - - /** The name of this scheme, in lowercase. (e.g. http, https) */ - private final String name; - - /** The socket factory for this scheme */ - private final SchemeSocketFactory socketFactory; - - /** The default port for this scheme */ - private final int defaultPort; - - /** Indicates whether this scheme allows for layered connections */ - private final boolean layered; - - /** A string representation, for {@link #toString toString}. */ - private String stringRep; - /* - * This is used to cache the result of the toString() method - * Since the method always generates the same value, there's no - * need to synchronize, and it does not affect immutability. - */ - - /** - * Creates a new scheme. - * Whether the created scheme allows for layered connections - * depends on the class of {@code factory}. - * - * @param name the scheme name, for example "http". - * The name will be converted to lowercase. - * @param port the default port for this scheme - * @param factory the factory for creating sockets for communication - * with this scheme - * - * @since 4.1 - */ - public Scheme(final String name, final int port, final SchemeSocketFactory factory) { - Args.notNull(name, "Scheme name"); - Args.check(port > 0 && port <= 0xffff, "Port is invalid"); - Args.notNull(factory, "Socket factory"); - this.name = name.toLowerCase(Locale.ENGLISH); - this.defaultPort = port; - if (factory instanceof SchemeLayeredSocketFactory) { - this.layered = true; - this.socketFactory = factory; - } else if (factory instanceof LayeredSchemeSocketFactory) { - this.layered = true; - this.socketFactory = new SchemeLayeredSocketFactoryAdaptor2((LayeredSchemeSocketFactory) factory); - } else { - this.layered = false; - this.socketFactory = factory; - } - } - - /** - * Creates a new scheme. - * Whether the created scheme allows for layered connections - * depends on the class of {@code factory}. - * - * @param name the scheme name, for example "http". - * The name will be converted to lowercase. - * @param factory the factory for creating sockets for communication - * with this scheme - * @param port the default port for this scheme - * - * @deprecated (4.1) Use {@link #Scheme(String, int, SchemeSocketFactory)} - */ - @Deprecated - public Scheme(final String name, - final SocketFactory factory, - final int port) { - - Args.notNull(name, "Scheme name"); - Args.notNull(factory, "Socket factory"); - Args.check(port > 0 && port <= 0xffff, "Port is invalid"); - - this.name = name.toLowerCase(Locale.ENGLISH); - if (factory instanceof LayeredSocketFactory) { - this.socketFactory = new SchemeLayeredSocketFactoryAdaptor( - (LayeredSocketFactory) factory); - this.layered = true; - } else { - this.socketFactory = new SchemeSocketFactoryAdaptor(factory); - this.layered = false; - } - this.defaultPort = port; - } - - /** - * Obtains the default port. - * - * @return the default port for this scheme - */ - public final int getDefaultPort() { - return defaultPort; - } - - - /** - * Obtains the socket factory. - * If this scheme is {@link #isLayered layered}, the factory implements - * {@link LayeredSocketFactory LayeredSocketFactory}. - * - * @return the socket factory for this scheme - * - * @deprecated (4.1) Use {@link #getSchemeSocketFactory()} - */ - @Deprecated - public final SocketFactory getSocketFactory() { - if (this.socketFactory instanceof SchemeSocketFactoryAdaptor) { - return ((SchemeSocketFactoryAdaptor) this.socketFactory).getFactory(); - } else { - if (this.layered) { - return new LayeredSocketFactoryAdaptor( - (LayeredSchemeSocketFactory) this.socketFactory); - } else { - return new SocketFactoryAdaptor(this.socketFactory); - } - } - } - - /** - * Obtains the socket factory. - * If this scheme is {@link #isLayered layered}, the factory implements - * {@link LayeredSocketFactory LayeredSchemeSocketFactory}. - * - * @return the socket factory for this scheme - * - * @since 4.1 - */ - public final SchemeSocketFactory getSchemeSocketFactory() { - return this.socketFactory; - } - - /** - * Obtains the scheme name. - * - * @return the name of this scheme, in lowercase - */ - public final String getName() { - return name; - } - - /** - * Indicates whether this scheme allows for layered connections. - * - * @return {@code true} if layered connections are possible, - * {@code false} otherwise - */ - public final boolean isLayered() { - return layered; - } - - /** - * Resolves the correct port for this scheme. - * Returns the given port if it is valid, the default port otherwise. - * - * @param port the port to be resolved, - * a negative number to obtain the default port - * - * @return the given port or the defaultPort - */ - public final int resolvePort(final int port) { - return port <= 0 ? defaultPort : port; - } - - /** - * Return a string representation of this object. - * - * @return a human-readable string description of this scheme - */ - @Override - public final String toString() { - if (stringRep == null) { - final StringBuilder buffer = new StringBuilder(); - buffer.append(this.name); - buffer.append(':'); - buffer.append(Integer.toString(this.defaultPort)); - stringRep = buffer.toString(); - } - return stringRep; - } - - @Override - public final boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof Scheme) { - final Scheme that = (Scheme) obj; - return this.name.equals(that.name) - && this.defaultPort == that.defaultPort - && this.layered == that.layered; - } else { - return false; - } - } - - @Override - public int hashCode() { - int hash = LangUtils.HASH_SEED; - hash = LangUtils.hashCode(hash, this.defaultPort); - hash = LangUtils.hashCode(hash, this.name); - hash = LangUtils.hashCode(hash, this.layered); - return hash; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SchemeLayeredSocketFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SchemeLayeredSocketFactory.java deleted file mode 100644 index 9c4781bb..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SchemeLayeredSocketFactory.java +++ /dev/null @@ -1,69 +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 com.tracelytics.ext.apache.http.conn.scheme; - -import java.io.IOException; -import java.net.Socket; -import java.net.UnknownHostException; - -import com.tracelytics.ext.apache.http.params.HttpParams; - -/** - * Extended {@link SchemeSocketFactory} interface for layered sockets such as SSL/TLS. - * - * @since 4.2 - * - * @deprecated (4.3) use {@link - * com.tracelytics.ext.apache.http.conn.socket.LayeredConnectionSocketFactory} - */ -@Deprecated -public interface SchemeLayeredSocketFactory extends SchemeSocketFactory { - - /** - * Returns a socket connected to the given host that is layered over an - * existing socket. Used primarily for creating secure sockets through - * proxies. - * - * @param socket the existing socket - * @param target the name of the target host. - * @param port the port to connect to on the target host - * @param params HTTP parameters - * - * @return Socket a new socket - * - * @throws IOException if an I/O error occurs while creating the socket - * @throws UnknownHostException if the IP address of the host cannot be - * determined - */ - Socket createLayeredSocket( - Socket socket, - String target, - int port, - HttpParams params) throws IOException, UnknownHostException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SchemeLayeredSocketFactoryAdaptor.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SchemeLayeredSocketFactoryAdaptor.java deleted file mode 100644 index b28864e2..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SchemeLayeredSocketFactoryAdaptor.java +++ /dev/null @@ -1,58 +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 com.tracelytics.ext.apache.http.conn.scheme; - -import java.io.IOException; -import java.net.Socket; -import java.net.UnknownHostException; - -import com.tracelytics.ext.apache.http.params.HttpParams; - -/** - * @deprecated (4.2) do not use - */ -@Deprecated -class SchemeLayeredSocketFactoryAdaptor extends SchemeSocketFactoryAdaptor - implements SchemeLayeredSocketFactory { - - private final LayeredSocketFactory factory; - - SchemeLayeredSocketFactoryAdaptor(final LayeredSocketFactory factory) { - super(factory); - this.factory = factory; - } - - @Override - public Socket createLayeredSocket( - final Socket socket, - final String target, final int port, - final HttpParams params) throws IOException, UnknownHostException { - return this.factory.createSocket(socket, target, port, true); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SchemeLayeredSocketFactoryAdaptor2.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SchemeLayeredSocketFactoryAdaptor2.java deleted file mode 100644 index c5de8af9..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SchemeLayeredSocketFactoryAdaptor2.java +++ /dev/null @@ -1,79 +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 com.tracelytics.ext.apache.http.conn.scheme; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.net.UnknownHostException; - -import com.tracelytics.ext.apache.http.params.HttpParams; - -import com.tracelytics.ext.apache.http.conn.ConnectTimeoutException; - -/** - * @deprecated (4.2) do not use - */ -@Deprecated -class SchemeLayeredSocketFactoryAdaptor2 implements SchemeLayeredSocketFactory { - - private final LayeredSchemeSocketFactory factory; - - SchemeLayeredSocketFactoryAdaptor2(final LayeredSchemeSocketFactory factory) { - super(); - this.factory = factory; - } - - @Override - public Socket createSocket(final HttpParams params) throws IOException { - return this.factory.createSocket(params); - } - - @Override - public Socket connectSocket( - final Socket sock, - final InetSocketAddress remoteAddress, - final InetSocketAddress localAddress, - final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { - return this.factory.connectSocket(sock, remoteAddress, localAddress, params); - } - - @Override - public boolean isSecure(final Socket sock) throws IllegalArgumentException { - return this.factory.isSecure(sock); - } - - @Override - public Socket createLayeredSocket( - final Socket socket, - final String target, final int port, - final HttpParams params) throws IOException, UnknownHostException { - return this.factory.createLayeredSocket(socket, target, port, true); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SchemeRegistry.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SchemeRegistry.java deleted file mode 100644 index 4f674729..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SchemeRegistry.java +++ /dev/null @@ -1,168 +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 com.tracelytics.ext.apache.http.conn.scheme; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * A set of supported protocol {@link Scheme}s. - * Schemes are identified by lowercase names. - * - * @since 4.0 - * - * @deprecated (4.3) use {@link com.tracelytics.ext.apache.http.config.Registry} - */ -@ThreadSafe -@Deprecated -public final class SchemeRegistry { - - /** The available schemes in this registry. */ - private final ConcurrentHashMap registeredSchemes; - - /** - * Creates a new, empty scheme registry. - */ - public SchemeRegistry() { - super(); - registeredSchemes = new ConcurrentHashMap(); - } - - /** - * Obtains a scheme by name. - * - * @param name the name of the scheme to look up (in lowercase) - * - * @return the scheme, never {@code null} - * - * @throws IllegalStateException - * if the scheme with the given name is not registered - */ - public final Scheme getScheme(final String name) { - final Scheme found = get(name); - if (found == null) { - throw new IllegalStateException - ("Scheme '"+name+"' not registered."); - } - return found; - } - - /** - * Obtains the scheme for a host. - * Convenience method for {@code getScheme(host.getSchemeName())} - * - * @param host the host for which to obtain the scheme - * - * @return the scheme for the given host, never {@code null} - * - * @throws IllegalStateException - * if a scheme with the respective name is not registered - */ - public final Scheme getScheme(final HttpHost host) { - Args.notNull(host, "Host"); - return getScheme(host.getSchemeName()); - } - - /** - * Obtains a scheme by name, if registered. - * - * @param name the name of the scheme to look up (in lowercase) - * - * @return the scheme, or - * {@code null} if there is none by this name - */ - public final Scheme get(final String name) { - Args.notNull(name, "Scheme name"); - // leave it to the caller to use the correct name - all lowercase - //name = name.toLowerCase(Locale.ENGLISH); - final Scheme found = registeredSchemes.get(name); - return found; - } - - /** - * Registers a scheme. - * The scheme can later be retrieved by its name - * using {@link #getScheme(String) getScheme} or {@link #get get}. - * - * @param sch the scheme to register - * - * @return the scheme previously registered with that name, or - * {@code null} if none was registered - */ - public final Scheme register(final Scheme sch) { - Args.notNull(sch, "Scheme"); - final Scheme old = registeredSchemes.put(sch.getName(), sch); - return old; - } - - /** - * Unregisters a scheme. - * - * @param name the name of the scheme to unregister (in lowercase) - * - * @return the unregistered scheme, or - * {@code null} if there was none - */ - public final Scheme unregister(final String name) { - Args.notNull(name, "Scheme name"); - // leave it to the caller to use the correct name - all lowercase - //name = name.toLowerCase(Locale.ENGLISH); - final Scheme gone = registeredSchemes.remove(name); - return gone; - } - - /** - * Obtains the names of the registered schemes. - * - * @return List containing registered scheme names. - */ - public final List getSchemeNames() { - return new ArrayList(registeredSchemes.keySet()); - } - - /** - * Populates the internal collection of registered {@link Scheme protocol schemes} - * with the content of the map passed as a parameter. - * - * @param map protocol schemes - */ - public void setItems(final Map map) { - if (map == null) { - return; - } - registeredSchemes.clear(); - registeredSchemes.putAll(map); - } - -} - diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SchemeSocketFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SchemeSocketFactory.java deleted file mode 100644 index 0aaf9ef4..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SchemeSocketFactory.java +++ /dev/null @@ -1,132 +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 com.tracelytics.ext.apache.http.conn.scheme; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.net.UnknownHostException; - -import com.tracelytics.ext.apache.http.params.HttpParams; - -import com.tracelytics.ext.apache.http.conn.ConnectTimeoutException; - -/** - * A factory for creating, initializing and connecting sockets. The factory encapsulates the logic - * for establishing a socket connection. - * - * @since 4.1 - * - * @deprecated (4.3) use {@link com.tracelytics.ext.apache.http.conn.socket.ConnectionSocketFactory} - */ -@Deprecated -public interface SchemeSocketFactory { - - /** - * Creates a new, unconnected socket. The socket should subsequently be passed to - * {@link #connectSocket(Socket, InetSocketAddress, InetSocketAddress, HttpParams)}. - * - * @param params Optional {@link HttpParams parameters}. In most cases these parameters - * will not be required and will have no effect, as usually socket - * initialization should take place in the - * {@link #connectSocket(Socket, InetSocketAddress, InetSocketAddress, HttpParams)} - * method. However, in rare cases one may want to pass additional parameters - * to this method in order to create a customized {@link Socket} instance, - * for instance bound to a SOCKS proxy server. - * - * @return a new socket - * - * @throws IOException if an I/O error occurs while creating the socket - */ - Socket createSocket(HttpParams params) throws IOException; - - /** - * Connects a socket to the target host with the given remote address. - *

- * Please note that {@link com.tracelytics.ext.apache.http.conn.HttpInetSocketAddress} class should - * be used in order to pass the target remote address along with the original - * {@link com.tracelytics.ext.apache.http.HttpHost} value used to resolve the address. The use of - * {@link com.tracelytics.ext.apache.http.conn.HttpInetSocketAddress} can also ensure that no reverse - * DNS lookup will be performed if the target remote address was specified - * as an IP address. - *

- * - * @param sock the socket to connect, as obtained from - * {@link #createSocket(HttpParams) createSocket}. - * {@code null} indicates that a new socket - * should be created and connected. - * @param remoteAddress the remote address to connect to. - * @param localAddress the local address to bind the socket to, or - * {@code null} for any - * @param params additional {@link HttpParams parameters} for connecting - * - * @return the connected socket. The returned object may be different - * from the {@code sock} argument if this factory supports - * a layered protocol. - * - * @throws IOException if an I/O error occurs - * @throws UnknownHostException if the IP address of the target host - * can not be determined - * @throws ConnectTimeoutException if the socket cannot be connected - * within the time limit defined in the {@code params} - * - * @see com.tracelytics.ext.apache.http.conn.HttpInetSocketAddress - */ - Socket connectSocket( - Socket sock, - InetSocketAddress remoteAddress, - InetSocketAddress localAddress, - HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException; - - /** - * Checks whether a socket provides a secure connection. The socket must be - * {@link #connectSocket(Socket, InetSocketAddress, InetSocketAddress, HttpParams) connected} - * by this factory. The factory will not perform I/O operations in this method. - *

- * As a rule of thumb, plain sockets are not secure and TLS/SSL sockets are secure. However, - * there may be application specific deviations. For example, a plain socket to a host in the - * same intranet ("trusted zone") could be considered secure. On the other hand, a TLS/SSL - * socket could be considered insecure based on the cipher suite chosen for the connection. - * - * @param sock the connected socket to check - * - * @return {@code true} if the connection of the socket - * should be considered secure, or - * {@code false} if it should not - * - * @throws IllegalArgumentException - * if the argument is invalid, for example because it is - * not a connected socket or was created by a different - * socket factory. - * Note that socket factories are not required to - * check these conditions, they may simply return a default - * value when called with an invalid socket argument. - */ - boolean isSecure(Socket sock) throws IllegalArgumentException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SchemeSocketFactoryAdaptor.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SchemeSocketFactoryAdaptor.java deleted file mode 100644 index 80a9aa6e..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SchemeSocketFactoryAdaptor.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 com.tracelytics.ext.apache.http.conn.scheme; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.net.UnknownHostException; - -import com.tracelytics.ext.apache.http.params.HttpParams; - -import com.tracelytics.ext.apache.http.conn.ConnectTimeoutException; - -/** - * @deprecated (4.1) do not use - */ -@Deprecated -class SchemeSocketFactoryAdaptor implements SchemeSocketFactory { - - private final SocketFactory factory; - - SchemeSocketFactoryAdaptor(final SocketFactory factory) { - super(); - this.factory = factory; - } - - @Override - public Socket connectSocket( - final Socket sock, - final InetSocketAddress remoteAddress, - final InetSocketAddress localAddress, - final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { - final String host = remoteAddress.getHostName(); - final int port = remoteAddress.getPort(); - InetAddress local = null; - int localPort = 0; - if (localAddress != null) { - local = localAddress.getAddress(); - localPort = localAddress.getPort(); - } - return this.factory.connectSocket(sock, host, port, local, localPort, params); - } - - @Override - public Socket createSocket(final HttpParams params) throws IOException { - return this.factory.createSocket(); - } - - @Override - public boolean isSecure(final Socket sock) throws IllegalArgumentException { - return this.factory.isSecure(sock); - } - - public SocketFactory getFactory() { - return this.factory; - } - - @Override - public boolean equals(final Object obj) { - if (obj == null) { - return false; - } - if (this == obj) { - return true; - } - if (obj instanceof SchemeSocketFactoryAdaptor) { - return this.factory.equals(((SchemeSocketFactoryAdaptor)obj).factory); - } else { - return this.factory.equals(obj); - } - } - - @Override - public int hashCode() { - return this.factory.hashCode(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SocketFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SocketFactory.java deleted file mode 100644 index cfe39436..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SocketFactory.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 com.tracelytics.ext.apache.http.conn.scheme; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.Socket; -import java.net.UnknownHostException; - -import com.tracelytics.ext.apache.http.params.HttpParams; - -import com.tracelytics.ext.apache.http.conn.ConnectTimeoutException; - -/** - * A factory for creating, initializing and connecting sockets. - * The factory encapsulates the logic for establishing a socket connection. - * - * @since 4.0 - * - * @deprecated (4.1) use {@link SchemeSocketFactory} - */ -@Deprecated -public interface SocketFactory { - - /** - * Creates a new, unconnected socket. - * The socket should subsequently be passed to - * {@link #connectSocket connectSocket}. - * - * @return a new socket - * - * @throws IOException if an I/O error occurs while creating the socket - */ - Socket createSocket() - throws IOException; - - /** - * Connects a socket to the given host. - * - * @param sock the socket to connect, as obtained from - * {@link #createSocket createSocket}. - * {@code null} indicates that a new socket - * should be created and connected. - * @param host the host to connect to - * @param port the port to connect to on the host - * @param localAddress the local address to bind the socket to, or - * {@code null} for any - * @param localPort the port on the local machine, - * 0 or a negative number for any - * @param params additional {@link HttpParams parameters} for connecting - * - * @return the connected socket. The returned object may be different - * from the {@code sock} argument if this factory supports - * a layered protocol. - * - * @throws IOException if an I/O error occurs - * @throws UnknownHostException if the IP address of the target host - * can not be determined - * @throws ConnectTimeoutException if the socket cannot be connected - * within the time limit defined in the {@code params} - */ - Socket connectSocket( - Socket sock, - String host, - int port, - InetAddress localAddress, - int localPort, - HttpParams params - ) throws IOException, UnknownHostException, ConnectTimeoutException; - - /** - * Checks whether a socket provides a secure connection. - * The socket must be {@link #connectSocket connected} - * by this factory. - * The factory will not perform I/O operations - * in this method. - *

- * As a rule of thumb, plain sockets are not secure and - * TLS/SSL sockets are secure. However, there may be - * application specific deviations. For example, a plain - * socket to a host in the same intranet ("trusted zone") - * could be considered secure. On the other hand, a - * TLS/SSL socket could be considered insecure based on - * the cipher suite chosen for the connection. - *

- * - * @param sock the connected socket to check - * - * @return {@code true} if the connection of the socket - * should be considered secure, or - * {@code false} if it should not - * - * @throws IllegalArgumentException - * if the argument is invalid, for example because it is - * not a connected socket or was created by a different - * socket factory. - * Note that socket factories are not required to - * check these conditions, they may simply return a default - * value when called with an invalid socket argument. - */ - boolean isSecure(Socket sock) - throws IllegalArgumentException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SocketFactoryAdaptor.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SocketFactoryAdaptor.java deleted file mode 100644 index 19b12a70..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/SocketFactoryAdaptor.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 com.tracelytics.ext.apache.http.conn.scheme; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.net.UnknownHostException; - -import com.tracelytics.ext.apache.http.params.BasicHttpParams; -import com.tracelytics.ext.apache.http.params.HttpParams; - -import com.tracelytics.ext.apache.http.conn.ConnectTimeoutException; - -@Deprecated -class SocketFactoryAdaptor implements SocketFactory { - - private final SchemeSocketFactory factory; - - SocketFactoryAdaptor(final SchemeSocketFactory factory) { - super(); - this.factory = factory; - } - - @Override - public Socket createSocket() throws IOException { - final HttpParams params = new BasicHttpParams(); - return this.factory.createSocket(params); - } - - @Override - public Socket connectSocket( - final Socket socket, - final String host, final int port, - final InetAddress localAddress, final int localPort, - final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { - InetSocketAddress local = null; - if (localAddress != null || localPort > 0) { - local = new InetSocketAddress(localAddress, localPort > 0 ? localPort : 0); - } - final InetAddress remoteAddress = InetAddress.getByName(host); - final InetSocketAddress remote = new InetSocketAddress(remoteAddress, port); - return this.factory.connectSocket(socket, remote, local, params); - } - - @Override - public boolean isSecure(final Socket socket) throws IllegalArgumentException { - return this.factory.isSecure(socket); - } - - public SchemeSocketFactory getFactory() { - return this.factory; - } - - @Override - public boolean equals(final Object obj) { - if (obj == null) { - return false; - } - if (this == obj) { - return true; - } - if (obj instanceof SocketFactoryAdaptor) { - return this.factory.equals(((SocketFactoryAdaptor)obj).factory); - } else { - return this.factory.equals(obj); - } - } - - @Override - public int hashCode() { - return this.factory.hashCode(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/package-info.java deleted file mode 100644 index 579fb485..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/scheme/package-info.java +++ /dev/null @@ -1,32 +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 - * . - * - */ - -/** - * Deprecated. - * @deprecated (4.3). - */ -package com.tracelytics.ext.apache.http.conn.scheme; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/socket/ConnectionSocketFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/socket/ConnectionSocketFactory.java deleted file mode 100644 index 26d892e0..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/socket/ConnectionSocketFactory.java +++ /dev/null @@ -1,80 +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 com.tracelytics.ext.apache.http.conn.socket; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.Socket; - -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -/** - * A factory for creating and connecting connection sockets. - * - * @since 4.3 - */ -public interface ConnectionSocketFactory { - - /** - * Creates new, unconnected socket. The socket should subsequently be passed to - * {@link #connectSocket(int, Socket, HttpHost, InetSocketAddress, InetSocketAddress, - * HttpContext) connectSocket} method. - * - * @return a new socket - * - * @throws IOException if an I/O error occurs while creating the socket - */ - Socket createSocket(HttpContext context) throws IOException; - - /** - * Connects the socket to the target host with the given resolved remote address. - * - * @param connectTimeout connect timeout. - * @param sock the socket to connect, as obtained from {@link #createSocket(HttpContext)}. - * {@code null} indicates that a new socket should be created and connected. - * @param host target host as specified by the caller (end user). - * @param remoteAddress the resolved remote address to connect to. - * @param localAddress the local address to bind the socket to, or {@code null} for any. - * @param context the actual HTTP context. - * - * @return the connected socket. The returned object may be different - * from the {@code sock} argument if this factory supports - * a layered protocol. - * - * @throws IOException if an I/O error occurs - */ - Socket connectSocket( - int connectTimeout, - Socket sock, - HttpHost host, - InetSocketAddress remoteAddress, - InetSocketAddress localAddress, - HttpContext context) throws IOException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/socket/LayeredConnectionSocketFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/socket/LayeredConnectionSocketFactory.java deleted file mode 100644 index 223725dc..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/socket/LayeredConnectionSocketFactory.java +++ /dev/null @@ -1,63 +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 com.tracelytics.ext.apache.http.conn.socket; - -import java.io.IOException; -import java.net.Socket; -import java.net.UnknownHostException; - -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -/** - * Extended {@link ConnectionSocketFactory} interface for layered sockets such as SSL/TLS. - * - * @since 4.3 - */ -public interface LayeredConnectionSocketFactory extends ConnectionSocketFactory { - - /** - * Returns a socket connected to the given host that is layered over an - * existing socket. Used primarily for creating secure sockets through - * proxies. - * - * @param socket the existing socket - * @param target the name of the target host. - * @param port the port to connect to on the target host. - * @param context the actual HTTP context. - * - * @return Socket a new socket - * - * @throws IOException if an I/O error occurs while creating the socket - */ - Socket createLayeredSocket( - Socket socket, - String target, - int port, - HttpContext context) throws IOException, UnknownHostException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/socket/PlainConnectionSocketFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/socket/PlainConnectionSocketFactory.java deleted file mode 100644 index 6b7b92d2..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/socket/PlainConnectionSocketFactory.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 com.tracelytics.ext.apache.http.conn.socket; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.Socket; - -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -/** - * The default class for creating plain (unencrypted) sockets. - * - * @since 4.3 - */ -@Immutable -public class PlainConnectionSocketFactory implements ConnectionSocketFactory { - - public static final PlainConnectionSocketFactory INSTANCE = new PlainConnectionSocketFactory(); - - public static PlainConnectionSocketFactory getSocketFactory() { - return INSTANCE; - } - - public PlainConnectionSocketFactory() { - super(); - } - - @Override - public Socket createSocket(final HttpContext context) throws IOException { - return new Socket(); - } - - @Override - public Socket connectSocket( - final int connectTimeout, - final Socket socket, - final HttpHost host, - final InetSocketAddress remoteAddress, - final InetSocketAddress localAddress, - final HttpContext context) throws IOException { - final Socket sock = socket != null ? socket : createSocket(context); - if (localAddress != null) { - sock.bind(localAddress); - } - try { - sock.connect(remoteAddress, connectTimeout); - } catch (final IOException ex) { - try { - sock.close(); - } catch (final IOException ignore) { - } - throw ex; - } - return sock; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/socket/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/socket/package-info.java deleted file mode 100644 index 169c1714..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/socket/package-info.java +++ /dev/null @@ -1,31 +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 - * . - * - */ - -/** - * Client connection socket APIs. - */ -package com.tracelytics.ext.apache.http.conn.socket; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/AbstractVerifier.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/AbstractVerifier.java deleted file mode 100644 index 0fb60004..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/AbstractVerifier.java +++ /dev/null @@ -1,268 +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 com.tracelytics.ext.apache.http.conn.ssl; - -import java.io.IOException; -import java.io.InputStream; -import java.security.cert.Certificate; -import java.security.cert.X509Certificate; -import java.util.Arrays; -import java.util.List; -import java.util.Locale; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.net.ssl.SSLException; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocket; -import javax.security.auth.x500.X500Principal; - -import com.tracelytics.ext.apache.http.conn.util.InetAddressUtils; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Abstract base class for all standard {@link X509HostnameVerifier} - * implementations. - * - * @since 4.0 - * - * @deprecated (4.4) use an implementation of {@link javax.net.ssl.HostnameVerifier} or - * {@link DefaultHostnameVerifier}. - */ -@Deprecated -public abstract class AbstractVerifier implements X509HostnameVerifier { - - private final Logger log = Logger.getLogger(getClass().getName()); - - final static String[] BAD_COUNTRY_2LDS = - { "ac", "co", "com", "ed", "edu", "go", "gouv", "gov", "info", - "lg", "ne", "net", "or", "org" }; - - static { - // Just in case developer forgot to manually sort the array. :-) - Arrays.sort(BAD_COUNTRY_2LDS); - } - - @Override - public final void verify(final String host, final SSLSocket ssl) - throws IOException { - Args.notNull(host, "Host"); - SSLSession session = ssl.getSession(); - if(session == null) { - // In our experience this only happens under IBM 1.4.x when - // spurious (unrelated) certificates show up in the server' - // chain. Hopefully this will unearth the real problem: - final InputStream in = ssl.getInputStream(); - in.available(); - /* - If you're looking at the 2 lines of code above because - you're running into a problem, you probably have two - options: - - #1. Clean up the certificate chain that your server - is presenting (e.g. edit "/etc/apache2/server.crt" - or wherever it is your server's certificate chain - is defined). - - OR - - #2. Upgrade to an IBM 1.5.x or greater JVM, or switch - to a non-IBM JVM. - */ - - // If ssl.getInputStream().available() didn't cause an - // exception, maybe at least now the session is available? - session = ssl.getSession(); - if(session == null) { - // If it's still null, probably a startHandshake() will - // unearth the real problem. - ssl.startHandshake(); - - // Okay, if we still haven't managed to cause an exception, - // might as well go for the NPE. Or maybe we're okay now? - session = ssl.getSession(); - } - } - - final Certificate[] certs = session.getPeerCertificates(); - final X509Certificate x509 = (X509Certificate) certs[0]; - verify(host, x509); - } - - @Override - public final boolean verify(final String host, final SSLSession session) { - try { - final Certificate[] certs = session.getPeerCertificates(); - final X509Certificate x509 = (X509Certificate) certs[0]; - verify(host, x509); - return true; - } catch(final SSLException ex) { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, ex.getMessage(), ex); - } - return false; - } - } - - public final void verify( - final String host, final X509Certificate cert) throws SSLException { - final boolean ipv4 = InetAddressUtils.isIPv4Address(host); - final boolean ipv6 = InetAddressUtils.isIPv6Address(host); - final int subjectType = ipv4 || ipv6 ? DefaultHostnameVerifier.IP_ADDRESS_TYPE : DefaultHostnameVerifier.DNS_NAME_TYPE; - final List subjectAlts = DefaultHostnameVerifier.extractSubjectAlts(cert, subjectType); - final X500Principal subjectPrincipal = cert.getSubjectX500Principal(); - final String cn = DefaultHostnameVerifier.extractCN(subjectPrincipal.getName(X500Principal.RFC2253)); - verify(host, - cn != null ? new String[] {cn} : null, - subjectAlts != null && !subjectAlts.isEmpty() ? subjectAlts.toArray(new String[subjectAlts.size()]) : null); - } - - public final void verify(final String host, final String[] cns, - final String[] subjectAlts, - final boolean strictWithSubDomains) - throws SSLException { - - final String cn = cns != null && cns.length > 0 ? cns[0] : null; - final List subjectAltList = subjectAlts != null && subjectAlts.length > 0 ? Arrays.asList(subjectAlts) : null; - - final String normalizedHost = InetAddressUtils.isIPv6Address(host) ? - DefaultHostnameVerifier.normaliseAddress(host.toLowerCase(Locale.ROOT)) : host; - - if (subjectAltList != null) { - for (String subjectAlt: subjectAltList) { - final String normalizedAltSubject = InetAddressUtils.isIPv6Address(subjectAlt) ? - DefaultHostnameVerifier.normaliseAddress(subjectAlt) : subjectAlt; - if (matchIdentity(normalizedHost, normalizedAltSubject, strictWithSubDomains)) { - return; - } - } - throw new SSLException("Certificate for <" + host + "> doesn't match any " + - "of the subject alternative names: " + subjectAltList); - } else if (cn != null) { - final String normalizedCN = InetAddressUtils.isIPv6Address(cn) ? - DefaultHostnameVerifier.normaliseAddress(cn) : cn; - if (matchIdentity(normalizedHost, normalizedCN, strictWithSubDomains)) { - return; - } - throw new SSLException("Certificate for <" + host + "> doesn't match " + - "common name of the certificate subject: " + cn); - } else { - throw new SSLException("Certificate subject for <" + host + "> doesn't contain " + - "a common name and does not have alternative names"); - } - } - - private static boolean matchIdentity(final String host, final String identity, final boolean strict) { - if (host == null) { - return false; - } - final String normalizedHost = host.toLowerCase(Locale.ROOT); - final String normalizedIdentity = identity.toLowerCase(Locale.ROOT); - // The CN better have at least two dots if it wants wildcard - // action. It also can't be [*.co.uk] or [*.co.jp] or - // [*.org.uk], etc... - final String parts[] = normalizedIdentity.split("\\."); - final boolean doWildcard = parts.length >= 3 && parts[0].endsWith("*") && - (!strict || validCountryWildcard(parts)); - if (doWildcard) { - boolean match; - final String firstpart = parts[0]; - if (firstpart.length() > 1) { // e.g. server* - final String prefix = firstpart.substring(0, firstpart.length() - 1); // e.g. server - final String suffix = normalizedIdentity.substring(firstpart.length()); // skip wildcard part from cn - final String hostSuffix = normalizedHost.substring(prefix.length()); // skip wildcard part from normalizedHost - match = normalizedHost.startsWith(prefix) && hostSuffix.endsWith(suffix); - } else { - match = normalizedHost.endsWith(normalizedIdentity.substring(1)); - } - return match && (!strict || countDots(normalizedHost) == countDots(normalizedIdentity)); - } else { - return normalizedHost.equals(normalizedIdentity); - } - } - - private static boolean validCountryWildcard(final String parts[]) { - if (parts.length != 3 || parts[2].length() != 2) { - return true; // it's not an attempt to wildcard a 2TLD within a country code - } - return Arrays.binarySearch(BAD_COUNTRY_2LDS, parts[1]) < 0; - } - - public static boolean acceptableCountryWildcard(final String cn) { - return validCountryWildcard(cn.split("\\.")); - } - - public static String[] getCNs(final X509Certificate cert) { - final String subjectPrincipal = cert.getSubjectX500Principal().toString(); - try { - final String cn = DefaultHostnameVerifier.extractCN(subjectPrincipal); - return cn != null ? new String[] { cn } : null; - } catch (SSLException ex) { - return null; - } - } - - /** - * Extracts the array of SubjectAlt DNS names from an X509Certificate. - * Returns null if there aren't any. - *

- * Note: Java doesn't appear able to extract international characters - * from the SubjectAlts. It can only extract international characters - * from the CN field. - *

- *

- * (Or maybe the version of OpenSSL I'm using to test isn't storing the - * international characters correctly in the SubjectAlts?). - *

- * - * @param cert X509Certificate - * @return Array of SubjectALT DNS names stored in the certificate. - */ - public static String[] getDNSSubjectAlts(final X509Certificate cert) { - final List subjectAlts = DefaultHostnameVerifier.extractSubjectAlts( - cert, DefaultHostnameVerifier.DNS_NAME_TYPE); - return subjectAlts != null && !subjectAlts.isEmpty() ? - subjectAlts.toArray(new String[subjectAlts.size()]) : null; - } - - /** - * Counts the number of dots "." in a string. - * @param s string to count dots from - * @return number of dots - */ - public static int countDots(final String s) { - int count = 0; - for(int i = 0; i < s.length(); i++) { - if(s.charAt(i) == '.') { - count++; - } - } - return count; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/AllowAllHostnameVerifier.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/AllowAllHostnameVerifier.java deleted file mode 100644 index 5af479c7..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/AllowAllHostnameVerifier.java +++ /dev/null @@ -1,60 +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 com.tracelytics.ext.apache.http.conn.ssl; - -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * The ALLOW_ALL HostnameVerifier essentially turns hostname verification - * off. This implementation is a no-op, and never throws the SSLException. - * - * - * @since 4.0 - * - * @deprecated (4.4) Use {@link com.tracelytics.ext.apache.http.conn.ssl.NoopHostnameVerifier} - */ -@Deprecated -@Immutable -public class AllowAllHostnameVerifier extends AbstractVerifier { - - public static final AllowAllHostnameVerifier INSTANCE = new AllowAllHostnameVerifier(); - - @Override - public final void verify( - final String host, - final String[] cns, - final String[] subjectAlts) { - // Allow everything - so never blowup. - } - - @Override - public final String toString() { - return "ALLOW_ALL"; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/BrowserCompatHostnameVerifier.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/BrowserCompatHostnameVerifier.java deleted file mode 100644 index 8d4a3cab..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/BrowserCompatHostnameVerifier.java +++ /dev/null @@ -1,69 +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 com.tracelytics.ext.apache.http.conn.ssl; - -import javax.net.ssl.SSLException; - -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * The HostnameVerifier that works the same way as Curl and Firefox. - *

- * The hostname must match either the first CN, or any of the subject-alts. - * A wildcard can occur in the CN, and in any of the subject-alts. - *

- *

- * The only difference between BROWSER_COMPATIBLE and STRICT is that a wildcard - * (such as "*.foo.com") with BROWSER_COMPATIBLE matches all subdomains, - * including "a.b.foo.com". - *

- * - * @since 4.0 - * - * @deprecated (4.4) Use {@link com.tracelytics.ext.apache.http.conn.ssl.DefaultHostnameVerifier} - */ -@Immutable -@Deprecated -public class BrowserCompatHostnameVerifier extends AbstractVerifier { - - public static final BrowserCompatHostnameVerifier INSTANCE = new BrowserCompatHostnameVerifier(); - - @Override - public final void verify( - final String host, - final String[] cns, - final String[] subjectAlts) throws SSLException { - verify(host, cns, subjectAlts, false); - } - - @Override - public final String toString() { - return "BROWSER_COMPATIBLE"; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/DefaultHostnameVerifier.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/DefaultHostnameVerifier.java deleted file mode 100644 index 3f57b657..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/DefaultHostnameVerifier.java +++ /dev/null @@ -1,297 +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 com.tracelytics.ext.apache.http.conn.ssl; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.security.cert.Certificate; -import java.security.cert.CertificateParsingException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Locale; -import java.util.NoSuchElementException; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.naming.InvalidNameException; -import javax.naming.NamingException; -import javax.naming.directory.Attribute; -import javax.naming.directory.Attributes; -import javax.naming.ldap.LdapName; -import javax.naming.ldap.Rdn; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLException; -import javax.net.ssl.SSLSession; -import javax.security.auth.x500.X500Principal; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.conn.util.InetAddressUtils; -import com.tracelytics.ext.apache.http.conn.util.PublicSuffixMatcher; - -/** - * Default {@link javax.net.ssl.HostnameVerifier} implementation. - * - * @since 4.4 - */ -@Immutable -public final class DefaultHostnameVerifier implements HostnameVerifier { - - final static int DNS_NAME_TYPE = 2; - final static int IP_ADDRESS_TYPE = 7; - - private final Logger log = Logger.getLogger(getClass().getName()); - - private final PublicSuffixMatcher publicSuffixMatcher; - - public DefaultHostnameVerifier(final PublicSuffixMatcher publicSuffixMatcher) { - this.publicSuffixMatcher = publicSuffixMatcher; - } - - public DefaultHostnameVerifier() { - this(null); - } - - @Override - public final boolean verify(final String host, final SSLSession session) { - try { - final Certificate[] certs = session.getPeerCertificates(); - final X509Certificate x509 = (X509Certificate) certs[0]; - verify(host, x509); - return true; - } catch(final SSLException ex) { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, ex.getMessage(), ex); - } - return false; - } - } - - public final void verify( - final String host, final X509Certificate cert) throws SSLException { - final boolean ipv4 = InetAddressUtils.isIPv4Address(host); - final boolean ipv6 = InetAddressUtils.isIPv6Address(host); - final int subjectType = ipv4 || ipv6 ? IP_ADDRESS_TYPE : DNS_NAME_TYPE; - final List subjectAlts = extractSubjectAlts(cert, subjectType); - if (subjectAlts != null && !subjectAlts.isEmpty()) { - if (ipv4) { - matchIPAddress(host, subjectAlts); - } else if (ipv6) { - matchIPv6Address(host, subjectAlts); - } else { - matchDNSName(host, subjectAlts, this.publicSuffixMatcher); - } - } else { - // CN matching has been deprecated by rfc2818 and can be used - // as fallback only when no subjectAlts are available - final X500Principal subjectPrincipal = cert.getSubjectX500Principal(); - final String cn = extractCN(subjectPrincipal.getName(X500Principal.RFC2253)); - if (cn == null) { - throw new SSLException("Certificate subject for <" + host + "> doesn't contain " + - "a common name and does not have alternative names"); - } - matchCN(host, cn, this.publicSuffixMatcher); - } - } - - static void matchIPAddress(final String host, final List subjectAlts) throws SSLException { - for (int i = 0; i < subjectAlts.size(); i++) { - final String subjectAlt = subjectAlts.get(i); - if (host.equals(subjectAlt)) { - return; - } - } - throw new SSLException("Certificate for <" + host + "> doesn't match any " + - "of the subject alternative names: " + subjectAlts); - } - - static void matchIPv6Address(final String host, final List subjectAlts) throws SSLException { - final String normalisedHost = normaliseAddress(host); - for (int i = 0; i < subjectAlts.size(); i++) { - final String subjectAlt = subjectAlts.get(i); - final String normalizedSubjectAlt = normaliseAddress(subjectAlt); - if (normalisedHost.equals(normalizedSubjectAlt)) { - return; - } - } - throw new SSLException("Certificate for <" + host + "> doesn't match any " + - "of the subject alternative names: " + subjectAlts); - } - - static void matchDNSName(final String host, final List subjectAlts, - final PublicSuffixMatcher publicSuffixMatcher) throws SSLException { - final String normalizedHost = host.toLowerCase(Locale.ROOT); - for (int i = 0; i < subjectAlts.size(); i++) { - final String subjectAlt = subjectAlts.get(i); - final String normalizedSubjectAlt = subjectAlt.toLowerCase(Locale.ROOT); - if (matchIdentityStrict(normalizedHost, normalizedSubjectAlt, publicSuffixMatcher)) { - return; - } - } - throw new SSLException("Certificate for <" + host + "> doesn't match any " + - "of the subject alternative names: " + subjectAlts); - } - - static void matchCN(final String host, final String cn, - final PublicSuffixMatcher publicSuffixMatcher) throws SSLException { - if (!matchIdentityStrict(host, cn, publicSuffixMatcher)) { - throw new SSLException("Certificate for <" + host + "> doesn't match " + - "common name of the certificate subject: " + cn); - } - } - - static boolean matchDomainRoot(final String host, final String domainRoot) { - if (domainRoot == null) { - return false; - } - return host.endsWith(domainRoot) && (host.length() == domainRoot.length() - || host.charAt(host.length() - domainRoot.length() - 1) == '.'); - } - - private static boolean matchIdentity(final String host, final String identity, - final PublicSuffixMatcher publicSuffixMatcher, - final boolean strict) { - if (publicSuffixMatcher != null && host.contains(".")) { - if (!matchDomainRoot(host, publicSuffixMatcher.getDomainRoot(identity))) { - return false; - } - } - - // RFC 2818, 3.1. Server Identity - // "...Names may contain the wildcard - // character * which is considered to match any single domain name - // component or component fragment..." - // Based on this statement presuming only singular wildcard is legal - final int asteriskIdx = identity.indexOf('*'); - if (asteriskIdx != -1) { - final String prefix = identity.substring(0, asteriskIdx); - final String suffix = identity.substring(asteriskIdx + 1); - if (!prefix.isEmpty() && !host.startsWith(prefix)) { - return false; - } - if (!suffix.isEmpty() && !host.endsWith(suffix)) { - return false; - } - // Additional sanity checks on content selected by wildcard can be done here - if (strict) { - final String remainder = host.substring( - prefix.length(), host.length() - suffix.length()); - if (remainder.contains(".")) { - return false; - } - } - return true; - } - return host.equalsIgnoreCase(identity); - } - - static boolean matchIdentity(final String host, final String identity, - final PublicSuffixMatcher publicSuffixMatcher) { - return matchIdentity(host, identity, publicSuffixMatcher, false); - } - - static boolean matchIdentity(final String host, final String identity) { - return matchIdentity(host, identity, null, false); - } - - static boolean matchIdentityStrict(final String host, final String identity, - final PublicSuffixMatcher publicSuffixMatcher) { - return matchIdentity(host, identity, publicSuffixMatcher, true); - } - - static boolean matchIdentityStrict(final String host, final String identity) { - return matchIdentity(host, identity, null, true); - } - - static String extractCN(final String subjectPrincipal) throws SSLException { - if (subjectPrincipal == null) { - return null; - } - try { - final LdapName subjectDN = new LdapName(subjectPrincipal); - final List rdns = subjectDN.getRdns(); - for (int i = rdns.size() - 1; i >= 0; i--) { - final Rdn rds = rdns.get(i); - final Attributes attributes = rds.toAttributes(); - final Attribute cn = attributes.get("cn"); - if (cn != null) { - try { - final Object value = cn.get(); - if (value != null) { - return value.toString(); - } - } catch (NoSuchElementException ignore) { - } catch (NamingException ignore) { - } - } - } - return null; - } catch (InvalidNameException e) { - throw new SSLException(subjectPrincipal + " is not a valid X500 distinguished name"); - } - } - - static List extractSubjectAlts(final X509Certificate cert, final int subjectType) { - Collection> c = null; - try { - c = cert.getSubjectAlternativeNames(); - } catch(final CertificateParsingException ignore) { - } - List subjectAltList = null; - if (c != null) { - for (final List aC : c) { - final List list = aC; - final int type = ((Integer) list.get(0)).intValue(); - if (type == subjectType) { - final String s = (String) list.get(1); - if (subjectAltList == null) { - subjectAltList = new ArrayList(); - } - subjectAltList.add(s); - } - } - } - return subjectAltList; - } - - /* - * Normalize IPv6 or DNS name. - */ - static String normaliseAddress(final String hostname) { - if (hostname == null) { - return hostname; - } - try { - final InetAddress inetAddress = InetAddress.getByName(hostname); - return inetAddress.getHostAddress(); - } catch (final UnknownHostException unexpected) { // Should not happen, because we check for IPv6 address above - return hostname; - } - } -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/NoopHostnameVerifier.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/NoopHostnameVerifier.java deleted file mode 100644 index 57455c4b..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/NoopHostnameVerifier.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 com.tracelytics.ext.apache.http.conn.ssl; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLSession; - -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * The NO_OP HostnameVerifier essentially turns hostname verification - * off. This implementation is a no-op, and never throws the SSLException. - * - * @since 4.4 - */ -@Immutable -public class NoopHostnameVerifier implements HostnameVerifier { - - public static final NoopHostnameVerifier INSTANCE = new NoopHostnameVerifier(); - - @Override - public boolean verify(final String s, final SSLSession sslSession) { - return true; - } - - @Override - public final String toString() { - return "NO_OP"; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/SSLConnectionSocketFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/SSLConnectionSocketFactory.java deleted file mode 100644 index c68e3a44..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/SSLConnectionSocketFactory.java +++ /dev/null @@ -1,476 +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 com.tracelytics.ext.apache.http.conn.ssl; - -import java.io.IOException; -import java.io.InputStream; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.security.cert.Certificate; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.net.SocketFactory; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLHandshakeException; -import javax.net.ssl.SSLPeerUnverifiedException; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocket; -import javax.security.auth.x500.X500Principal; - -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.conn.socket.LayeredConnectionSocketFactory; -import com.tracelytics.ext.apache.http.conn.util.PublicSuffixMatcherLoader; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.ssl.SSLContexts; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.TextUtils; - -/** - * Layered socket factory for TLS/SSL connections. - *

- * SSLSocketFactory can be used to validate the identity of the HTTPS server against a list of - * trusted certificates and to authenticate to the HTTPS server using a private key. - *

- * SSLSocketFactory will enable server authentication when supplied with - * a {@link java.security.KeyStore trust-store} file containing one or several trusted certificates. The client - * secure socket will reject the connection during the SSL session handshake if the target HTTPS - * server attempts to authenticate itself with a non-trusted certificate. - *

- * Use JDK keytool utility to import a trusted certificate and generate a trust-store file: - *

- *     keytool -import -alias "my server cert" -file server.crt -keystore my.truststore
- *    
- *

- * In special cases the standard trust verification process can be bypassed by using a custom - * {@link com.tracelytics.ext.apache.http.conn.ssl.TrustStrategy}. This interface is primarily intended for allowing self-signed - * certificates to be accepted as trusted without having to add them to the trust-store file. - *

- * SSLSocketFactory will enable client authentication when supplied with - * a {@link java.security.KeyStore key-store} file containing a private key/public certificate - * pair. The client secure socket will use the private key to authenticate - * itself to the target HTTPS server during the SSL session handshake if - * requested to do so by the server. - * The target HTTPS server will in its turn verify the certificate presented - * by the client in order to establish client's authenticity. - *

- * Use the following sequence of actions to generate a key-store file - *

- *
    - *
  • - *

    - * Use JDK keytool utility to generate a new key - *

    - *
    keytool -genkey -v -alias "my client key" -validity 365 -keystore my.keystore
    - *

    - * For simplicity use the same password for the key as that of the key-store - *

    - *
  • - *
  • - *

    - * Issue a certificate signing request (CSR) - *

    - *
    keytool -certreq -alias "my client key" -file mycertreq.csr -keystore my.keystore
    - *
  • - *
  • - *

    - * Send the certificate request to the trusted Certificate Authority for signature. - * One may choose to act as her own CA and sign the certificate request using a PKI - * tool, such as OpenSSL. - *

    - *
  • - *
  • - *

    - * Import the trusted CA root certificate - *

    - *
    keytool -import -alias "my trusted ca" -file caroot.crt -keystore my.keystore
    - *
  • - *
  • - *

    - * Import the PKCS#7 file containing the complete certificate chain - *

    - *
    keytool -import -alias "my client key" -file mycert.p7 -keystore my.keystore
    - *
  • - *
  • - *

    - * Verify the content of the resultant keystore file - *

    - *
    keytool -list -v -keystore my.keystore
    - *
  • - *
- * - * @since 4.3 - */ -@ThreadSafe @SuppressWarnings("deprecation") -public class SSLConnectionSocketFactory implements LayeredConnectionSocketFactory { - - public static final String TLS = "TLS"; - public static final String SSL = "SSL"; - public static final String SSLV2 = "SSLv2"; - - @Deprecated - public static final X509HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER - = AllowAllHostnameVerifier.INSTANCE; - - @Deprecated - public static final X509HostnameVerifier BROWSER_COMPATIBLE_HOSTNAME_VERIFIER - = BrowserCompatHostnameVerifier.INSTANCE; - - @Deprecated - public static final X509HostnameVerifier STRICT_HOSTNAME_VERIFIER - = StrictHostnameVerifier.INSTANCE; - - private final Logger log = Logger.getLogger(getClass().getName()); - - /** - * @since 4.4 - */ - public static HostnameVerifier getDefaultHostnameVerifier() { - return new DefaultHostnameVerifier(PublicSuffixMatcherLoader.getDefault()); - } - - /** - * Obtains default SSL socket factory with an SSL context based on the standard JSSE - * trust material ({@code cacerts} file in the security properties directory). - * System properties are not taken into consideration. - * - * @return default SSL socket factory - */ - public static SSLConnectionSocketFactory getSocketFactory() throws SSLInitializationException { - return new SSLConnectionSocketFactory(SSLContexts.createDefault(), getDefaultHostnameVerifier()); - } - - private static String[] split(final String s) { - if (TextUtils.isBlank(s)) { - return null; - } - return s.split(" *, *"); - } - - /** - * Obtains default SSL socket factory with an SSL context based on system properties - * as described in - * - * Java™ Secure Socket Extension (JSSE) Reference Guide. - * - * @return default system SSL socket factory - */ - public static SSLConnectionSocketFactory getSystemSocketFactory() throws SSLInitializationException { - return new SSLConnectionSocketFactory( - (javax.net.ssl.SSLSocketFactory) javax.net.ssl.SSLSocketFactory.getDefault(), - split(System.getProperty("https.protocols")), - split(System.getProperty("https.cipherSuites")), - getDefaultHostnameVerifier()); - } - - private final javax.net.ssl.SSLSocketFactory socketfactory; - private final HostnameVerifier hostnameVerifier; - private final String[] supportedProtocols; - private final String[] supportedCipherSuites; - - public SSLConnectionSocketFactory(final SSLContext sslContext) { - this(sslContext, getDefaultHostnameVerifier()); - } - - /** - * @deprecated (4.4) Use {@link #SSLConnectionSocketFactory(javax.net.ssl.SSLContext, - * javax.net.ssl.HostnameVerifier)} - */ - @Deprecated - public SSLConnectionSocketFactory( - final SSLContext sslContext, final X509HostnameVerifier hostnameVerifier) { - this(Args.notNull(sslContext, "SSL context").getSocketFactory(), - null, null, hostnameVerifier); - } - - /** - * @deprecated (4.4) Use {@link #SSLConnectionSocketFactory(javax.net.ssl.SSLContext, - * String[], String[], javax.net.ssl.HostnameVerifier)} - */ - @Deprecated - public SSLConnectionSocketFactory( - final SSLContext sslContext, - final String[] supportedProtocols, - final String[] supportedCipherSuites, - final X509HostnameVerifier hostnameVerifier) { - this(Args.notNull(sslContext, "SSL context").getSocketFactory(), - supportedProtocols, supportedCipherSuites, hostnameVerifier); - } - - /** - * @deprecated (4.4) Use {@link #SSLConnectionSocketFactory(javax.net.ssl.SSLSocketFactory, - * javax.net.ssl.HostnameVerifier)} - */ - @Deprecated - public SSLConnectionSocketFactory( - final javax.net.ssl.SSLSocketFactory socketfactory, - final X509HostnameVerifier hostnameVerifier) { - this(socketfactory, null, null, hostnameVerifier); - } - - /** - * @deprecated (4.4) Use {@link #SSLConnectionSocketFactory(javax.net.ssl.SSLSocketFactory, - * String[], String[], javax.net.ssl.HostnameVerifier)} - */ - @Deprecated - public SSLConnectionSocketFactory( - final javax.net.ssl.SSLSocketFactory socketfactory, - final String[] supportedProtocols, - final String[] supportedCipherSuites, - final X509HostnameVerifier hostnameVerifier) { - this(socketfactory, supportedProtocols, supportedCipherSuites, (HostnameVerifier) hostnameVerifier); - } - - /** - * @since 4.4 - */ - public SSLConnectionSocketFactory( - final SSLContext sslContext, final HostnameVerifier hostnameVerifier) { - this(Args.notNull(sslContext, "SSL context").getSocketFactory(), - null, null, hostnameVerifier); - } - - /** - * @since 4.4 - */ - public SSLConnectionSocketFactory( - final SSLContext sslContext, - final String[] supportedProtocols, - final String[] supportedCipherSuites, - final HostnameVerifier hostnameVerifier) { - this(Args.notNull(sslContext, "SSL context").getSocketFactory(), - supportedProtocols, supportedCipherSuites, hostnameVerifier); - } - - /** - * @since 4.4 - */ - public SSLConnectionSocketFactory( - final javax.net.ssl.SSLSocketFactory socketfactory, - final HostnameVerifier hostnameVerifier) { - this(socketfactory, null, null, hostnameVerifier); - } - - /** - * @since 4.4 - */ - public SSLConnectionSocketFactory( - final javax.net.ssl.SSLSocketFactory socketfactory, - final String[] supportedProtocols, - final String[] supportedCipherSuites, - final HostnameVerifier hostnameVerifier) { - this.socketfactory = Args.notNull(socketfactory, "SSL socket factory"); - this.supportedProtocols = supportedProtocols; - this.supportedCipherSuites = supportedCipherSuites; - this.hostnameVerifier = hostnameVerifier != null ? hostnameVerifier : getDefaultHostnameVerifier(); - } - - /** - * Performs any custom initialization for a newly created SSLSocket - * (before the SSL handshake happens). - * - * The default implementation is a no-op, but could be overridden to, e.g., - * call {@link javax.net.ssl.SSLSocket#setEnabledCipherSuites(String[])}. - * @throws IOException may be thrown if overridden - */ - protected void prepareSocket(final SSLSocket socket) throws IOException { - } - - @Override - public Socket createSocket(final HttpContext context) throws IOException { - return SocketFactory.getDefault().createSocket(); - } - - @Override - public Socket connectSocket( - final int connectTimeout, - final Socket socket, - final HttpHost host, - final InetSocketAddress remoteAddress, - final InetSocketAddress localAddress, - final HttpContext context) throws IOException { - Args.notNull(host, "HTTP host"); - Args.notNull(remoteAddress, "Remote address"); - final Socket sock = socket != null ? socket : createSocket(context); - if (localAddress != null) { - sock.bind(localAddress); - } - try { - if (connectTimeout > 0 && sock.getSoTimeout() == 0) { - sock.setSoTimeout(connectTimeout); - } - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Connecting socket to " + remoteAddress + " with timeout " + connectTimeout); - } - sock.connect(remoteAddress, connectTimeout); - } catch (final IOException ex) { - try { - sock.close(); - } catch (final IOException ignore) { - } - throw ex; - } - // Setup SSL layering if necessary - if (sock instanceof SSLSocket) { - final SSLSocket sslsock = (SSLSocket) sock; - this.log.log(Level.FINE, "Starting handshake"); - sslsock.startHandshake(); - verifyHostname(sslsock, host.getHostName()); - return sock; - } else { - return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context); - } - } - - @Override - public Socket createLayeredSocket( - final Socket socket, - final String target, - final int port, - final HttpContext context) throws IOException { - final SSLSocket sslsock = (SSLSocket) this.socketfactory.createSocket( - socket, - target, - port, - true); - if (supportedProtocols != null) { - sslsock.setEnabledProtocols(supportedProtocols); - } else { - // If supported protocols are not explicitly set, remove all SSL protocol versions - final String[] allProtocols = sslsock.getEnabledProtocols(); - final List enabledProtocols = new ArrayList(allProtocols.length); - for (String protocol: allProtocols) { - if (!protocol.startsWith("SSL")) { - enabledProtocols.add(protocol); - } - } - if (!enabledProtocols.isEmpty()) { - sslsock.setEnabledProtocols(enabledProtocols.toArray(new String[enabledProtocols.size()])); - } - } - if (supportedCipherSuites != null) { - sslsock.setEnabledCipherSuites(supportedCipherSuites); - } - - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Enabled protocols: " + Arrays.asList(sslsock.getEnabledProtocols())); - this.log.log(Level.FINE, "Enabled cipher suites:" + Arrays.asList(sslsock.getEnabledCipherSuites())); - } - - prepareSocket(sslsock); - this.log.log(Level.FINE, "Starting handshake"); - sslsock.startHandshake(); - verifyHostname(sslsock, target); - return sslsock; - } - - private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException { - try { - SSLSession session = sslsock.getSession(); - if (session == null) { - // In our experience this only happens under IBM 1.4.x when - // spurious (unrelated) certificates show up in the server' - // chain. Hopefully this will unearth the real problem: - final InputStream in = sslsock.getInputStream(); - in.available(); - // If ssl.getInputStream().available() didn't cause an - // exception, maybe at least now the session is available? - session = sslsock.getSession(); - if (session == null) { - // If it's still null, probably a startHandshake() will - // unearth the real problem. - sslsock.startHandshake(); - session = sslsock.getSession(); - } - } - if (session == null) { - throw new SSLHandshakeException("SSL session not available"); - } - - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Secure session established"); - this.log.log(Level.FINE, " negotiated protocol: " + session.getProtocol()); - this.log.log(Level.FINE, " negotiated cipher suite: " + session.getCipherSuite()); - - try { - - final Certificate[] certs = session.getPeerCertificates(); - final X509Certificate x509 = (X509Certificate) certs[0]; - final X500Principal peer = x509.getSubjectX500Principal(); - - this.log.log(Level.FINE, " peer principal: " + peer.toString()); - final Collection> altNames1 = x509.getSubjectAlternativeNames(); - if (altNames1 != null) { - final List altNames = new ArrayList(); - for (final List aC : altNames1) { - if (!aC.isEmpty()) { - altNames.add((String) aC.get(1)); - } - } - this.log.log(Level.FINE, " peer alternative names: " + altNames); - } - - final X500Principal issuer = x509.getIssuerX500Principal(); - this.log.log(Level.FINE, " issuer principal: " + issuer.toString()); - final Collection> altNames2 = x509.getIssuerAlternativeNames(); - if (altNames2 != null) { - final List altNames = new ArrayList(); - for (final List aC : altNames2) { - if (!aC.isEmpty()) { - altNames.add((String) aC.get(1)); - } - } - this.log.log(Level.FINE, " issuer alternative names: " + altNames); - } - } catch (Exception ignore) { - } - } - - if (!this.hostnameVerifier.verify(hostname, session)) { - final Certificate[] certs = session.getPeerCertificates(); - final X509Certificate x509 = (X509Certificate) certs[0]; - final X500Principal x500Principal = x509.getSubjectX500Principal(); - throw new SSLPeerUnverifiedException("Host name '" + hostname + "' does not match " + - "the certificate subject provided by the peer (" + x500Principal.toString() + ")"); - } - // verifyHostName() didn't blowup - good! - } catch (final IOException iox) { - // close the socket before re-throwing the exception - try { sslsock.close(); } catch (final Exception x) { /*ignore*/ } - throw iox; - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/SSLInitializationException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/SSLInitializationException.java deleted file mode 100644 index 3be2e263..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/SSLInitializationException.java +++ /dev/null @@ -1,37 +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 com.tracelytics.ext.apache.http.conn.ssl; - -public class SSLInitializationException extends IllegalStateException { - - private static final long serialVersionUID = -8243587425648536702L; - - public SSLInitializationException(final String message, final Throwable cause) { - super(message, cause); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/StrictHostnameVerifier.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/StrictHostnameVerifier.java deleted file mode 100644 index 0be950e5..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/StrictHostnameVerifier.java +++ /dev/null @@ -1,75 +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 com.tracelytics.ext.apache.http.conn.ssl; - -import javax.net.ssl.SSLException; - -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * The Strict HostnameVerifier works the same way as Sun Java 1.4, Sun - * Java 5, Sun Java 6. It's also pretty close to IE6. This implementation - * appears to be compliant with RFC 2818 for dealing with wildcards. - *

- * The hostname must match either the first CN, or any of the subject-alts. - * A wildcard can occur in the CN, and in any of the subject-alts. The - * one divergence from IE6 is how we only check the first CN. IE6 allows - * a match against any of the CNs present. We decided to follow in - * Sun Java 1.4's footsteps and only check the first CN. (If you need - * to check all the CN's, feel free to write your own implementation!). - *

- *

- * A wildcard such as "*.foo.com" matches only subdomains in the same - * level, for example "a.foo.com". It does not match deeper subdomains - * such as "a.b.foo.com". - *

- * - * @since 4.0 - * - * @deprecated (4.4) Use {@link com.tracelytics.ext.apache.http.conn.ssl.DefaultHostnameVerifier} - */ -@Immutable -@Deprecated -public class StrictHostnameVerifier extends AbstractVerifier { - - public static final StrictHostnameVerifier INSTANCE = new StrictHostnameVerifier(); - - @Override - public final void verify( - final String host, - final String[] cns, - final String[] subjectAlts) throws SSLException { - verify(host, cns, subjectAlts, true); - } - - @Override - public final String toString() { - return "STRICT"; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/TrustSelfSignedStrategy.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/TrustSelfSignedStrategy.java deleted file mode 100644 index 8f80eb51..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/TrustSelfSignedStrategy.java +++ /dev/null @@ -1,48 +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 com.tracelytics.ext.apache.http.conn.ssl; - -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - -/** - * A trust strategy that accepts self-signed certificates as trusted. Verification of all other - * certificates is done by the trust manager configured in the SSL context. - * - * @since 4.1 - */ -public class TrustSelfSignedStrategy implements TrustStrategy { - - public static final TrustSelfSignedStrategy INSTANCE = new TrustSelfSignedStrategy(); - - @Override - public boolean isTrusted( - final X509Certificate[] chain, final String authType) throws CertificateException { - return chain.length == 1; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/TrustStrategy.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/TrustStrategy.java deleted file mode 100644 index 0a8bfc2b..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/TrustStrategy.java +++ /dev/null @@ -1,38 +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 com.tracelytics.ext.apache.http.conn.ssl; - -/** - * A strategy to establish trustworthiness of certificates without consulting the trust manager - * configured in the actual SSL context. This interface can be used to override the standard - * JSSE certificate verification process. - * - * @since 4.1 - */ -public interface TrustStrategy extends com.tracelytics.ext.apache.http.ssl.TrustStrategy { - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/X509HostnameVerifier.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/X509HostnameVerifier.java deleted file mode 100644 index 82b5b01c..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/X509HostnameVerifier.java +++ /dev/null @@ -1,88 +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 com.tracelytics.ext.apache.http.conn.ssl; - -import java.io.IOException; -import java.security.cert.X509Certificate; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLException; -import javax.net.ssl.SSLSocket; - -/** - * Interface for checking if a hostname matches the names stored inside the - * server's X.509 certificate. This interface extends - * {@link javax.net.ssl.HostnameVerifier}, but it is recommended to use - * methods added by X509HostnameVerifier. - * - * @since 4.0 - * - * @deprecated (4.4) Use {@link javax.net.ssl.HostnameVerifier}. - */ -@Deprecated -public interface X509HostnameVerifier extends HostnameVerifier { - - /** - * Verifies that the host name is an acceptable match with the server's - * authentication scheme based on the given {@link SSLSocket}. - * - * @param host the host. - * @param ssl the SSL socket. - * @throws IOException if an I/O error occurs or the verification process - * fails. - */ - void verify(String host, SSLSocket ssl) throws IOException; - - /** - * Verifies that the host name is an acceptable match with the server's - * authentication scheme based on the given {@link X509Certificate}. - * - * @param host the host. - * @param cert the certificate. - * @throws SSLException if the verification process fails. - */ - void verify(String host, X509Certificate cert) throws SSLException; - - /** - * Checks to see if the supplied hostname matches any of the supplied CNs - * or "DNS" Subject-Alts. Most implementations only look at the first CN, - * and ignore any additional CNs. Most implementations do look at all of - * the "DNS" Subject-Alts. The CNs or Subject-Alts may contain wildcards - * according to RFC 2818. - * - * @param cns CN fields, in order, as extracted from the X.509 - * certificate. - * @param subjectAlts Subject-Alt fields of type 2 ("DNS"), as extracted - * from the X.509 certificate. - * @param host The hostname to verify. - * @throws SSLException if the verification process fails. - */ - void verify(String host, String[] cns, String[] subjectAlts) - throws SSLException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/package-info.java deleted file mode 100644 index 2431fa74..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/ssl/package-info.java +++ /dev/null @@ -1,31 +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 - * . - * - */ - -/** - * Client TLS/SSL support. - */ -package com.tracelytics.ext.apache.http.conn.ssl; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/util/InetAddressUtils.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/util/InetAddressUtils.java deleted file mode 100644 index 777cf0ec..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/util/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 com.tracelytics.ext.apache.http.conn.util; - -import java.util.regex.Pattern; - -import com.tracelytics.ext.apache.http.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/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/util/PublicSuffixList.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/util/PublicSuffixList.java deleted file mode 100644 index b57856a3..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/util/PublicSuffixList.java +++ /dev/null @@ -1,63 +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 com.tracelytics.ext.apache.http.conn.util; - -import java.util.Collections; -import java.util.List; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Public suffix is a set of DNS names or wildcards concatenated with dots. It represents - * the part of a domain name which is not under the control of the individual registrant - *

- * An up-to-date list of suffixes can be obtained from - * publicsuffix.org - * - * @since 4.4 - */ -@Immutable -public final class PublicSuffixList { - - private final List rules; - private final List exceptions; - - public PublicSuffixList(final List rules, final List exceptions) { - this.rules = Collections.unmodifiableList(Args.notNull(rules, "Domain suffix rules")); - this.exceptions = Collections.unmodifiableList(Args.notNull(exceptions, "Domain suffix exceptions")); - } - - public List getRules() { - return rules; - } - - public List getExceptions() { - return exceptions; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/util/PublicSuffixListParser.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/util/PublicSuffixListParser.java deleted file mode 100644 index e173bbb4..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/util/PublicSuffixListParser.java +++ /dev/null @@ -1,114 +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 com.tracelytics.ext.apache.http.conn.util; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.Reader; -import java.util.ArrayList; -import java.util.List; - -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * Parses the list from publicsuffix.org - * and configures a PublicSuffixFilter. - * - * @since 4.4 - */ -@Immutable -public final class PublicSuffixListParser { - - private static final int MAX_LINE_LEN = 256; - - public PublicSuffixListParser() { - } - - /** - * Parses the public suffix list format. When creating the reader from the file, make sure to - * use the correct encoding (the original list is in UTF-8). - * - * @param reader the data reader. The caller is responsible for closing the reader. - * @throws java.io.IOException on error while reading from list - */ - public PublicSuffixList parse(final Reader reader) throws IOException { - final List rules = new ArrayList(); - final List exceptions = new ArrayList(); - final BufferedReader r = new BufferedReader(reader); - final StringBuilder sb = new StringBuilder(256); - boolean more = true; - while (more) { - more = readLine(r, sb); - String line = sb.toString(); - if (line.isEmpty()) { - continue; - } - if (line.startsWith("//")) { - continue; //entire lines can also be commented using // - } - if (line.startsWith(".")) { - line = line.substring(1); // A leading dot is optional - } - // An exclamation mark (!) at the start of a rule marks an exception to a previous wildcard rule - final boolean isException = line.startsWith("!"); - if (isException) { - line = line.substring(1); - } - - if (isException) { - exceptions.add(line); - } else { - rules.add(line); - } - } - return new PublicSuffixList(rules, exceptions); - } - - private boolean readLine(final Reader r, final StringBuilder sb) throws IOException { - sb.setLength(0); - int b; - boolean hitWhitespace = false; - while ((b = r.read()) != -1) { - final char c = (char) b; - if (c == '\n') { - break; - } - // Each line is only read up to the first whitespace - if (Character.isWhitespace(c)) { - hitWhitespace = true; - } - if (!hitWhitespace) { - sb.append(c); - } - if (sb.length() > MAX_LINE_LEN) { - return false; // prevent excess memory usage - } - } - return (b != -1); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/util/PublicSuffixMatcher.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/util/PublicSuffixMatcher.java deleted file mode 100644 index 3cad5503..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/util/PublicSuffixMatcher.java +++ /dev/null @@ -1,121 +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 com.tracelytics.ext.apache.http.conn.util; - -import java.net.IDN; -import java.util.Collection; -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Utility class that can test if DNS names match the content of the Public Suffix List. - *

- * An up-to-date list of suffixes can be obtained from - * publicsuffix.org - * - * @see com.tracelytics.ext.apache.http.conn.util.PublicSuffixList - * - * @since 4.4 - */ -@ThreadSafe -public final class PublicSuffixMatcher { - - private final Map rules; - private final Map exceptions; - - public PublicSuffixMatcher(final Collection rules, final Collection exceptions) { - Args.notNull(rules, "Domain suffix rules"); - this.rules = new ConcurrentHashMap(rules.size()); - for (String rule: rules) { - this.rules.put(rule, rule); - } - if (exceptions != null) { - this.exceptions = new ConcurrentHashMap(exceptions.size()); - for (String exception: exceptions) { - this.exceptions.put(exception, exception); - } - } else { - this.exceptions = null; - } - } - - /** - * Returns registrable part of the domain for the given domain name of {@code null} - * if given domain represents a public suffix. - * - * @param domain - * @return domain root - */ - public String getDomainRoot(final String domain) { - if (domain == null) { - return null; - } - if (domain.startsWith(".")) { - return null; - } - String domainName = null; - String segment = domain.toLowerCase(Locale.ROOT); - while (segment != null) { - - // An exception rule takes priority over any other matching rule. - if (this.exceptions != null && this.exceptions.containsKey(IDN.toUnicode(segment))) { - return segment; - } - - if (this.rules.containsKey(IDN.toUnicode(segment))) { - break; - } - - final int nextdot = segment.indexOf('.'); - final String nextSegment = nextdot != -1 ? segment.substring(nextdot + 1) : null; - - if (nextSegment != null) { - if (this.rules.containsKey("*." + IDN.toUnicode(nextSegment))) { - break; - } - } - if (nextdot != -1) { - domainName = segment; - } - segment = nextSegment; - } - return domainName; - } - - public boolean matches(final String domain) { - if (domain == null) { - return false; - } - final String domainRoot = getDomainRoot(domain.startsWith(".") ? domain.substring(1) : domain); - return domainRoot == null; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/util/PublicSuffixMatcherLoader.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/util/PublicSuffixMatcherLoader.java deleted file mode 100644 index c3c4bc42..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/util/PublicSuffixMatcherLoader.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 com.tracelytics.ext.apache.http.conn.util; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URL; -import java.util.Arrays; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.tracelytics.ext.apache.http.Consts; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * {@link com.tracelytics.ext.apache.http.conn.util.PublicSuffixMatcher} loader. - * - * @since 4.4 - */ -@ThreadSafe -public final class PublicSuffixMatcherLoader { - - private static PublicSuffixMatcher load(final InputStream in) throws IOException { - final PublicSuffixList list = new PublicSuffixListParser().parse( - new InputStreamReader(in, Consts.UTF_8)); - return new PublicSuffixMatcher(list.getRules(), list.getExceptions()); - } - - public static PublicSuffixMatcher load(final URL url) throws IOException { - Args.notNull(url, "URL"); - final InputStream in = url.openStream(); - try { - return load(in); - } finally { - in.close(); - } - } - - public static PublicSuffixMatcher load(final File file) throws IOException { - Args.notNull(file, "File"); - final InputStream in = new FileInputStream(file); - try { - return load(in); - } finally { - in.close(); - } - } - - private static volatile PublicSuffixMatcher DEFAULT_INSTANCE; - - public static PublicSuffixMatcher getDefault() { - if (DEFAULT_INSTANCE == null) { - synchronized (PublicSuffixMatcherLoader.class) { - if (DEFAULT_INSTANCE == null){ - final URL url = PublicSuffixMatcherLoader.class.getResource( - "/mozilla/public-suffix-list.txt"); - if (url != null) { - try { - DEFAULT_INSTANCE = load(url); - } catch (IOException ex) { - // Should never happen - final Logger log = Logger.getLogger(PublicSuffixMatcherLoader.class.getName()); - if (log.isLoggable(Level.WARNING)) { - log.log(Level.WARNING, "Failure loading public suffix list from default resource", ex); - } - } - } else { - DEFAULT_INSTANCE = new PublicSuffixMatcher(Arrays.asList("com"), null); - } - } - } - } - return DEFAULT_INSTANCE; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/util/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/util/package-info.java deleted file mode 100644 index 118b5ca1..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/conn/util/package-info.java +++ /dev/null @@ -1,31 +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 - * . - * - */ - -/** - * Connection utility classes. - */ -package com.tracelytics.ext.apache.http.conn.util; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/ClientCookie.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/ClientCookie.java deleted file mode 100644 index 6f54588d..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/ClientCookie.java +++ /dev/null @@ -1,69 +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 com.tracelytics.ext.apache.http.cookie; - -import com.tracelytics.ext.apache.http.annotation.Obsolete; - -/** - * ClientCookie extends the standard {@link Cookie} interface with - * additional client specific functionality such ability to retrieve - * original cookie attributes exactly as they were specified by the - * origin server. This is important for generating the {@code Cookie} - * header because some cookie specifications require that the - * {@code Cookie} header should include certain attributes only if - * they were specified in the {@code Set-Cookie} header. - *

- * Please do not use attributes marked as @Obsolete. They have been rendered - * obsolete by RFC 6265. - * - * @since 4.0 - */ -public interface ClientCookie extends Cookie { - - @Obsolete - public static final String VERSION_ATTR = "version"; - public static final String PATH_ATTR = "path"; - public static final String DOMAIN_ATTR = "domain"; - public static final String MAX_AGE_ATTR = "max-age"; - public static final String SECURE_ATTR = "secure"; - @Obsolete - public static final String COMMENT_ATTR = "comment"; - public static final String EXPIRES_ATTR = "expires"; - - @Obsolete - public static final String PORT_ATTR = "port"; - @Obsolete - public static final String COMMENTURL_ATTR = "commenturl"; - @Obsolete - public static final String DISCARD_ATTR = "discard"; - - String getAttribute(String name); - - boolean containsAttribute(String name); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CommonCookieAttributeHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CommonCookieAttributeHandler.java deleted file mode 100644 index 3b9cd043..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CommonCookieAttributeHandler.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 com.tracelytics.ext.apache.http.cookie; - -/** - * Extension of {@link com.tracelytics.ext.apache.http.cookie.CookieAttributeHandler} intended - * to handle one specific common attribute whose name is returned with - * {@link #getAttributeName()} method. - * - * @since 4.4 - */ -public interface CommonCookieAttributeHandler extends CookieAttributeHandler { - - String getAttributeName(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/Cookie.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/Cookie.java deleted file mode 100644 index d02269e4..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/Cookie.java +++ /dev/null @@ -1,148 +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 com.tracelytics.ext.apache.http.cookie; - -import java.util.Date; - -import com.tracelytics.ext.apache.http.annotation.Obsolete; - -/** - * Cookie interface represents a token or short packet of state information - * (also referred to as "magic-cookie") that the HTTP agent and the target - * server can exchange to maintain a session. In its simples form an HTTP - * cookie is merely a name / value pair. - *

- * Please do not use attributes marked as @Obsolete. They have been rendered - * obsolete by RFC 6265. - * - * @since 4.0 - */ -public interface Cookie { - - /** - * Returns the name. - * - * @return String name The name - */ - String getName(); - - /** - * Returns the value. - * - * @return String value The current value. - */ - String getValue(); - - /** - * Returns the comment describing the purpose of this cookie, or - * {@code null} if no such comment has been defined. - * - * @return comment - */ - @Obsolete - String getComment(); - - /** - * If a user agent (web browser) presents this cookie to a user, the - * cookie's purpose will be described by the information at this URL. - */ - @Obsolete - String getCommentURL(); - - /** - * Returns the expiration {@link Date} of the cookie, or {@code null} - * if none exists. - *

Note: the object returned by this method is - * considered immutable. Changing it (e.g. using setTime()) could result - * in undefined behaviour. Do so at your peril.

- * @return Expiration {@link Date}, or {@code null}. - */ - Date getExpiryDate(); - - /** - * Returns {@code false} if the cookie should be discarded at the end - * of the "session"; {@code true} otherwise. - * - * @return {@code false} if the cookie should be discarded at the end - * of the "session"; {@code true} otherwise - */ - boolean isPersistent(); - - /** - * Returns domain attribute of the cookie. The value of the Domain - * attribute specifies the domain for which the cookie is valid. - * - * @return the value of the domain attribute. - */ - String getDomain(); - - /** - * Returns the path attribute of the cookie. The value of the Path - * attribute specifies the subset of URLs on the origin server to which - * this cookie applies. - * - * @return The value of the path attribute. - */ - String getPath(); - - /** - * Get the Port attribute. It restricts the ports to which a cookie - * may be returned in a Cookie request header. - */ - @Obsolete - int[] getPorts(); - - /** - * Indicates whether this cookie requires a secure connection. - * - * @return {@code true} if this cookie should only be sent - * over secure connections, {@code false} otherwise. - */ - boolean isSecure(); - - /** - * Returns the version of the cookie specification to which this - * cookie conforms. - * - * @return the version of the cookie. - */ - @Obsolete - int getVersion(); - - /** - * Returns true if this cookie has expired. - * @param date Current time - * - * @return {@code true} if the cookie has expired. - */ - boolean isExpired(final Date date); - - //TODO: RFC 6265 requires cookies to track their creation time; add #getCreationDate() - -} - diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieAttributeHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieAttributeHandler.java deleted file mode 100644 index 7292bf84..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieAttributeHandler.java +++ /dev/null @@ -1,73 +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 com.tracelytics.ext.apache.http.cookie; - -/** - * This interface represents a cookie attribute handler responsible - * for parsing, validating, and matching a specific cookie attribute, - * such as path, domain, port, etc. - * - * Different cookie specifications can provide a specific - * implementation for this class based on their cookie handling - * rules. - * - * - * @since 4.0 - */ -public interface CookieAttributeHandler { - - /** - * Parse the given cookie attribute value and update the corresponding - * {@link com.tracelytics.ext.apache.http.cookie.Cookie} property. - * - * @param cookie {@link com.tracelytics.ext.apache.http.cookie.Cookie} to be updated - * @param value cookie attribute value from the cookie response header - */ - void parse(SetCookie cookie, String value) - throws MalformedCookieException; - - /** - * Peforms cookie validation for the given attribute value. - * - * @param cookie {@link com.tracelytics.ext.apache.http.cookie.Cookie} to validate - * @param origin the cookie source to validate against - * @throws MalformedCookieException if cookie validation fails for this attribute - */ - void validate(Cookie cookie, CookieOrigin origin) - throws MalformedCookieException; - - /** - * Matches the given value (property of the destination host where request is being - * submitted) with the corresponding cookie attribute. - * - * @param cookie {@link com.tracelytics.ext.apache.http.cookie.Cookie} to match - * @param origin the cookie source to match against - * @return {@code true} if the match is successful; {@code false} otherwise - */ - boolean match(Cookie cookie, CookieOrigin origin); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieIdentityComparator.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieIdentityComparator.java deleted file mode 100644 index 347486c0..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieIdentityComparator.java +++ /dev/null @@ -1,81 +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 com.tracelytics.ext.apache.http.cookie; - -import java.io.Serializable; -import java.util.Comparator; - -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * This cookie comparator can be used to compare identity of cookies. - *

- * Cookies are considered identical if their names are equal and - * their domain attributes match ignoring case. - * - * @since 4.0 - */ -@Immutable -public class CookieIdentityComparator implements Serializable, Comparator { - - private static final long serialVersionUID = 4466565437490631532L; - - @Override - public int compare(final Cookie c1, final Cookie c2) { - int res = c1.getName().compareTo(c2.getName()); - if (res == 0) { - // do not differentiate empty and null domains - String d1 = c1.getDomain(); - if (d1 == null) { - d1 = ""; - } else if (d1.indexOf('.') == -1) { - d1 = d1 + ".local"; - } - String d2 = c2.getDomain(); - if (d2 == null) { - d2 = ""; - } else if (d2.indexOf('.') == -1) { - d2 = d2 + ".local"; - } - res = d1.compareToIgnoreCase(d2); - } - if (res == 0) { - String p1 = c1.getPath(); - if (p1 == null) { - p1 = "/"; - } - String p2 = c2.getPath(); - if (p2 == null) { - p2 = "/"; - } - res = p1.compareTo(p2); - } - return res; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieOrigin.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieOrigin.java deleted file mode 100644 index 5083ed83..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieOrigin.java +++ /dev/null @@ -1,95 +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 com.tracelytics.ext.apache.http.cookie; - -import java.util.Locale; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.TextUtils; - -/** - * CookieOrigin class encapsulates details of an origin server that - * are relevant when parsing, validating or matching HTTP cookies. - * - * @since 4.0 - */ -@Immutable -public final class CookieOrigin { - - private final String host; - private final int port; - private final String path; - private final boolean secure; - - public CookieOrigin(final String host, final int port, final String path, final boolean secure) { - super(); - Args.notBlank(host, "Host"); - Args.notNegative(port, "Port"); - Args.notNull(path, "Path"); - this.host = host.toLowerCase(Locale.ROOT); - this.port = port; - if (!TextUtils.isBlank(path)) { - this.path = path; - } else { - this.path = "/"; - } - this.secure = secure; - } - - public String getHost() { - return this.host; - } - - public String getPath() { - return this.path; - } - - public int getPort() { - return this.port; - } - - public boolean isSecure() { - return this.secure; - } - - @Override - public String toString() { - final StringBuilder buffer = new StringBuilder(); - buffer.append('['); - if (this.secure) { - buffer.append("(secure)"); - } - buffer.append(this.host); - buffer.append(':'); - buffer.append(Integer.toString(this.port)); - buffer.append(this.path); - buffer.append(']'); - return buffer.toString(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookiePathComparator.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookiePathComparator.java deleted file mode 100644 index bab856f2..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookiePathComparator.java +++ /dev/null @@ -1,84 +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 com.tracelytics.ext.apache.http.cookie; - -import java.io.Serializable; -import java.util.Comparator; - -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * This cookie comparator ensures that multiple cookies satisfying - * a common criteria are ordered in the {@code Cookie} header such - * that those with more specific Path attributes precede those with - * less specific. - * - *

- * This comparator assumes that Path attributes of two cookies - * path-match a commmon request-URI. Otherwise, the result of the - * comparison is undefined. - *

- * - * - * @since 4.0 - */ -@Immutable -public class CookiePathComparator implements Serializable, Comparator { - - public static final CookiePathComparator INSTANCE = new CookiePathComparator(); - - private static final long serialVersionUID = 7523645369616405818L; - - private String normalizePath(final Cookie cookie) { - String path = cookie.getPath(); - if (path == null) { - path = "/"; - } - if (!path.endsWith("/")) { - path = path + '/'; - } - return path; - } - - @Override - public int compare(final Cookie c1, final Cookie c2) { - final String path1 = normalizePath(c1); - final String path2 = normalizePath(c2); - if (path1.equals(path2)) { - return 0; - } else if (path1.startsWith(path2)) { - return -1; - } else if (path2.startsWith(path1)) { - return 1; - } else { - // Does not really matter - return 0; - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookiePriorityComparator.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookiePriorityComparator.java deleted file mode 100644 index f66c62e7..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookiePriorityComparator.java +++ /dev/null @@ -1,70 +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 com.tracelytics.ext.apache.http.cookie; - -import java.util.Comparator; -import java.util.Date; - -import com.tracelytics.ext.apache.http.annotation.Immutable; - -import com.tracelytics.ext.apache.http.impl.cookie.BasicClientCookie; - -/** - * This cookie comparator ensures that cookies with longer paths take precedence over - * cookies with shorter path. Among cookies with equal path length cookies with ealier - * creation time take precedence over cookies with later creation time - * - * @since 4.4 - */ -@Immutable -public class CookiePriorityComparator implements Comparator { - - public static final CookiePriorityComparator INSTANCE = new CookiePriorityComparator(); - - private int getPathLength(final Cookie cookie) { - final String path = cookie.getPath(); - return path != null ? path.length() : 1; - } - - @Override - public int compare(final Cookie c1, final Cookie c2) { - final int l1 = getPathLength(c1); - final int l2 = getPathLength(c2); - //TODO: update this class once Cookie interface has been expended with #getCreationTime method - final int result = l2 - l1; - if (result == 0 && c1 instanceof BasicClientCookie && c2 instanceof BasicClientCookie) { - final Date d1 = ((BasicClientCookie) c1).getCreationDate(); - final Date d2 = ((BasicClientCookie) c2).getCreationDate(); - if (d1 != null && d2 != null) { - return (int) (d1.getTime() - d2.getTime()); - } - } - return result; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieRestrictionViolationException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieRestrictionViolationException.java deleted file mode 100644 index 1e7e593c..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieRestrictionViolationException.java +++ /dev/null @@ -1,61 +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 com.tracelytics.ext.apache.http.cookie; - -import com.tracelytics.ext.apache.http.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; - - /** - * Creates a new CookeFormatViolationException with a {@code null} detail - * message. - */ - public CookieRestrictionViolationException() { - super(); - } - - /** - * Creates a new CookeRestrictionViolationException with a specified - * message string. - * - * @param message The exception detail message - */ - public CookieRestrictionViolationException(final String message) { - super(message); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieSpec.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieSpec.java deleted file mode 100644 index 9620322a..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieSpec.java +++ /dev/null @@ -1,114 +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 com.tracelytics.ext.apache.http.cookie; - -import java.util.List; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.annotation.Obsolete; - -/** - * Defines the cookie management specification. - *

Cookie management specification must define - *

    - *
  • rules of parsing "Set-Cookie" header - *
  • rules of validation of parsed cookies - *
  • formatting of "Cookie" header - *
- * for a given host, port and path of origin - *

- * Please do not use methods marked as @Obsolete. They have been rendered - * obsolete by RFC 6265. - * - * @since 4.0 - */ -public interface CookieSpec { - - /** - * Returns version of the state management this cookie specification - * conforms to. - * - * @return version of the state management specification - */ - @Obsolete - int getVersion(); - - /** - * Parse the {@code "Set-Cookie"} Header into an array of Cookies. - * - *

This method will not perform the validation of the resultant - * {@link Cookie}s

- * - * @see #validate - * - * @param header the {@code Set-Cookie} received from the server - * @param origin details of the cookie origin - * @return an array of {@code Cookie}s parsed from the header - * @throws MalformedCookieException if an exception occurs during parsing - */ - List parse(Header header, CookieOrigin origin) throws MalformedCookieException; - - /** - * Validate the cookie according to validation rules defined by the - * cookie specification. - * - * @param cookie the Cookie to validate - * @param origin details of the cookie origin - * @throws MalformedCookieException if the cookie is invalid - */ - void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException; - - /** - * Determines if a Cookie matches the target location. - * - * @param cookie the Cookie to be matched - * @param origin the target to test against - * - * @return {@code true} if the cookie should be submitted with a request - * with given attributes, {@code false} otherwise. - */ - boolean match(Cookie cookie, CookieOrigin origin); - - /** - * Create {@code "Cookie"} headers for an array of Cookies. - * - * @param cookies the Cookies format into a Cookie header - * @return a Header for the given Cookies. - * @throws IllegalArgumentException if an input parameter is illegal - */ - List
formatCookies(List cookies); - - /** - * Returns a request header identifying what version of the state management - * specification is understood. May be {@code null} if the cookie - * specification does not support {@code Cookie2} header. - */ - @Obsolete - Header getVersionHeader(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieSpecFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieSpecFactory.java deleted file mode 100644 index 7d862472..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieSpecFactory.java +++ /dev/null @@ -1,51 +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 com.tracelytics.ext.apache.http.cookie; - -import com.tracelytics.ext.apache.http.params.HttpParams; - -/** - * Factory for {@link CookieSpec} implementations. - * - * @since 4.0 - * - * @deprecated (4.3) use {@link CookieSpecProvider} - */ -@Deprecated -public interface CookieSpecFactory { - - /** - * Creates an instance of {@link CookieSpec} using given HTTP parameters. - * - * @param params HTTP parameters. - * - * @return cookie spec. - */ - CookieSpec newInstance(HttpParams params); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieSpecProvider.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieSpecProvider.java deleted file mode 100644 index cc397a84..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieSpecProvider.java +++ /dev/null @@ -1,46 +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 com.tracelytics.ext.apache.http.cookie; - -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -/** - * Factory for {@link CookieSpec} implementations. - * - * @since 4.3 - */ -public interface CookieSpecProvider { - - /** - * Creates an instance of {@link CookieSpec}. - * - * @return auth scheme. - */ - CookieSpec create(HttpContext context); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieSpecRegistry.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieSpecRegistry.java deleted file mode 100644 index 758a5ee3..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/CookieSpecRegistry.java +++ /dev/null @@ -1,169 +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 com.tracelytics.ext.apache.http.cookie; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.config.Lookup; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.protocol.ExecutionContext; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Cookie specification registry that can be used to obtain the corresponding - * cookie specification implementation for a given type of type or version of - * cookie. - * - * @since 4.0 - * - * @deprecated (4.3) use {@link com.tracelytics.ext.apache.http.config.Registry}. - */ -@ThreadSafe -@Deprecated -public final class CookieSpecRegistry implements Lookup { - - private final ConcurrentHashMap registeredSpecs; - - public CookieSpecRegistry() { - super(); - this.registeredSpecs = new ConcurrentHashMap(); - } - - /** - * Registers a {@link CookieSpecFactory} with the given identifier. - * If a specification with the given name already exists it will be overridden. - * This nameis the same one used to retrieve the {@link CookieSpecFactory} - * from {@link #getCookieSpec(String)}. - * - * @param name the identifier for this specification - * @param factory the {@link CookieSpecFactory} class to register - * - * @see #getCookieSpec(String) - */ - public void register(final String name, final CookieSpecFactory factory) { - Args.notNull(name, "Name"); - Args.notNull(factory, "Cookie spec factory"); - registeredSpecs.put(name.toLowerCase(Locale.ENGLISH), factory); - } - - /** - * Unregisters the {@link CookieSpecFactory} with the given ID. - * - * @param id the identifier of the {@link CookieSpec cookie specification} to unregister - */ - public void unregister(final String id) { - Args.notNull(id, "Id"); - registeredSpecs.remove(id.toLowerCase(Locale.ENGLISH)); - } - - /** - * Gets the {@link CookieSpec cookie specification} with the given ID. - * - * @param name the {@link CookieSpec cookie specification} identifier - * @param params the {@link HttpParams HTTP parameters} for the cookie - * specification. - * - * @return {@link CookieSpec cookie specification} - * - * @throws IllegalStateException if a policy with the given name cannot be found - */ - public CookieSpec getCookieSpec(final String name, final HttpParams params) - throws IllegalStateException { - - Args.notNull(name, "Name"); - final CookieSpecFactory factory = registeredSpecs.get(name.toLowerCase(Locale.ENGLISH)); - if (factory != null) { - return factory.newInstance(params); - } else { - throw new IllegalStateException("Unsupported cookie spec: " + name); - } - } - - /** - * Gets the {@link CookieSpec cookie specification} with the given name. - * - * @param name the {@link CookieSpec cookie specification} identifier - * - * @return {@link CookieSpec cookie specification} - * - * @throws IllegalStateException if a policy with the given name cannot be found - */ - public CookieSpec getCookieSpec(final String name) - throws IllegalStateException { - return getCookieSpec(name, null); - } - - /** - * Obtains a list containing the names of all registered {@link CookieSpec cookie - * specs}. - * - * Note that the DEFAULT policy (if present) is likely to be the same - * as one of the other policies, but does not have to be. - * - * @return list of registered cookie spec names - */ - public List getSpecNames(){ - return new ArrayList(registeredSpecs.keySet()); - } - - /** - * Populates the internal collection of registered {@link CookieSpec cookie - * specs} with the content of the map passed as a parameter. - * - * @param map cookie specs - */ - public void setItems(final Map map) { - if (map == null) { - return; - } - registeredSpecs.clear(); - registeredSpecs.putAll(map); - } - - @Override - public CookieSpecProvider lookup(final String name) { - return new CookieSpecProvider() { - - @Override - public CookieSpec create(final HttpContext context) { - final HttpRequest request = (HttpRequest) context.getAttribute( - ExecutionContext.HTTP_REQUEST); - return getCookieSpec(name, request.getParams()); - } - - }; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/MalformedCookieException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/MalformedCookieException.java deleted file mode 100644 index 258a1685..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/MalformedCookieException.java +++ /dev/null @@ -1,71 +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 com.tracelytics.ext.apache.http.cookie; - -import com.tracelytics.ext.apache.http.ProtocolException; -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * Signals that a cookie is in some way invalid or illegal in a given - * context - * - * - * @since 4.0 - */ -@Immutable -public class MalformedCookieException extends ProtocolException { - - private static final long serialVersionUID = -6695462944287282185L; - - /** - * Creates a new MalformedCookieException with a {@code null} detail message. - */ - public MalformedCookieException() { - super(); - } - - /** - * Creates a new MalformedCookieException with a specified message string. - * - * @param message The exception detail message - */ - public MalformedCookieException(final String message) { - super(message); - } - - /** - * Creates a new MalformedCookieException with the specified detail message and cause. - * - * @param message the exception detail message - * @param cause the {@code Throwable} that caused this exception, or {@code null} - * if the cause is unavailable, unknown, or not a {@code Throwable} - */ - public MalformedCookieException(final String message, final Throwable cause) { - super(message, cause); - } -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/SM.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/SM.java deleted file mode 100644 index ae63f382..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/SM.java +++ /dev/null @@ -1,43 +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 com.tracelytics.ext.apache.http.cookie; - -/** - * Constants and static helpers related to the HTTP state management. - * - * - * @since 4.0 - */ -public interface SM { - - public static final String COOKIE = "Cookie"; - public static final String COOKIE2 = "Cookie2"; - public static final String SET_COOKIE = "Set-Cookie"; - public static final String SET_COOKIE2 = "Set-Cookie2"; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/SetCookie.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/SetCookie.java deleted file mode 100644 index 628ac9e7..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/SetCookie.java +++ /dev/null @@ -1,116 +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 com.tracelytics.ext.apache.http.cookie; - -import java.util.Date; - -import com.tracelytics.ext.apache.http.annotation.Obsolete; - -/** - * This interface represents a {@code Set-Cookie} response header sent by the - * origin server to the HTTP agent in order to maintain a conversational state. - *

- * Please do not use methods marked as @Obsolete. They have been rendered - * obsolete by RFC 6265 - * - * @since 4.0 - */ -public interface SetCookie extends Cookie { - - void setValue(String value); - - /** - * If a user agent (web browser) presents this cookie to a user, the - * cookie's purpose will be described using this comment. - * - * @param comment - * - * @see #getComment() - */ - @Obsolete - void setComment(String comment); - - /** - * Sets expiration date. - *

Note: the object returned by this method is considered - * immutable. Changing it (e.g. using setTime()) could result in undefined - * behaviour. Do so at your peril.

- * - * @param expiryDate the {@link Date} after which this cookie is no longer valid. - * - * @see Cookie#getExpiryDate - * - */ - void setExpiryDate (Date expiryDate); - - /** - * Sets the domain attribute. - * - * @param domain The value of the domain attribute - * - * @see Cookie#getDomain - */ - void setDomain(String domain); - - /** - * Sets the path attribute. - * - * @param path The value of the path attribute - * - * @see Cookie#getPath - * - */ - void setPath(String path); - - /** - * Sets the secure attribute of the cookie. - *

- * When {@code true} the cookie should only be sent - * using a secure protocol (https). This should only be set when - * the cookie's originating server used a secure protocol to set the - * cookie's value. - * - * @param secure The value of the secure attribute - * - * @see #isSecure() - */ - void setSecure (boolean secure); - - /** - * Sets the version of the cookie specification to which this - * cookie conforms. - * - * @param version the version of the cookie. - * - * @see Cookie#getVersion - */ - @Obsolete - void setVersion(int version); - -} - diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/SetCookie2.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/SetCookie2.java deleted file mode 100644 index 61a5e39d..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/SetCookie2.java +++ /dev/null @@ -1,68 +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 com.tracelytics.ext.apache.http.cookie; - -import com.tracelytics.ext.apache.http.annotation.Obsolete; - -/** - * This interface represents a {@code Set-Cookie2} response header sent by the - * origin server to the HTTP agent in order to maintain a conversational state. - *

- * Please do not use methods marked as @Obsolete. They have been rendered - * obsolete by RFC 6265 - * - * @since 4.0 - */ -public interface SetCookie2 extends SetCookie { - - /** - * If a user agent (web browser) presents this cookie to a user, the - * cookie's purpose will be described by the information at this URL. - */ - @Obsolete - void setCommentURL(String commentURL); - - /** - * Sets the Port attribute. It restricts the ports to which a cookie - * may be returned in a Cookie request header. - */ - @Obsolete - void setPorts(int[] ports); - - /** - * Set the Discard attribute. - * - * Note: {@code Discard} attribute overrides {@code Max-age}. - * - * @see #isPersistent() - */ - @Obsolete - void setDiscard(boolean discard); - -} - diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/package-info.java deleted file mode 100644 index 3f16815f..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/package-info.java +++ /dev/null @@ -1,31 +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 - * . - * - */ - -/** - * Client HTTP state management APIs. - */ -package com.tracelytics.ext.apache.http.cookie; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/params/CookieSpecPNames.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/params/CookieSpecPNames.java deleted file mode 100644 index 9b8032a0..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/params/CookieSpecPNames.java +++ /dev/null @@ -1,65 +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 com.tracelytics.ext.apache.http.cookie.params; - -/** - * Parameter names for HTTP cookie management classes. - * - * @since 4.0 - * - * @deprecated (4.3) use constructor parameters of {@link - * com.tracelytics.ext.apache.http.cookie.CookieSpecProvider}s. - */ -@Deprecated -public interface CookieSpecPNames { - - /** - * Defines valid date patterns to be used for parsing non-standard - * {@code expires} attribute. Only required for compatibility - * with non-compliant servers that still use {@code expires} - * defined in the Netscape draft instead of the standard - * {@code max-age} attribute. - *

- * This parameter expects a value of type {@link java.util.Collection}. - * The collection elements must be of type {@link String} compatible - * with the syntax of {@link java.text.SimpleDateFormat}. - *

- */ - public static final String DATE_PATTERNS = "http.protocol.cookie-datepatterns"; - - /** - * Defines whether cookies should be forced into a single - * {@code Cookie} request header. Otherwise, each cookie is formatted - * as a separate {@code Cookie} header. - *

- * This parameter expects a value of type {@link Boolean}. - *

- */ - public static final String SINGLE_COOKIE_HEADER = "http.protocol.single-cookie-header"; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/params/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/params/package-info.java deleted file mode 100644 index 1ea610b7..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/cookie/params/package-info.java +++ /dev/null @@ -1,32 +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 - * . - * - */ - -/** - * Deprecated. - * @deprecated (4.3). - */ -package com.tracelytics.ext.apache.http.cookie.params; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/AbstractHttpEntity.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/AbstractHttpEntity.java deleted file mode 100644 index bcc807cb..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/AbstractHttpEntity.java +++ /dev/null @@ -1,221 +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 com.tracelytics.ext.apache.http.entity; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.message.BasicHeader; -import com.tracelytics.ext.apache.http.protocol.HTTP; - -/** - * Abstract base class for entities. - * Provides the commonly used attributes for streamed and self-contained - * implementations of {@link HttpEntity HttpEntity}. - * - * @since 4.0 - */ -@NotThreadSafe -public abstract class AbstractHttpEntity implements HttpEntity { - - /** - * Buffer size for output stream processing. - * - * @since 4.3 - */ - protected static final int OUTPUT_BUFFER_SIZE = 4096; - - protected Header contentType; - protected Header contentEncoding; - protected boolean chunked; - - /** - * Protected default constructor. - * The contentType, contentEncoding and chunked attributes of the created object are set to - * {@code null}, {@code null} and {@code false}, respectively. - */ - protected AbstractHttpEntity() { - super(); - } - - - /** - * Obtains the Content-Type header. - * The default implementation returns the value of the - * {@link #contentType contentType} attribute. - * - * @return the Content-Type header, or {@code null} - */ - @Override - public Header getContentType() { - return this.contentType; - } - - - /** - * Obtains the Content-Encoding header. - * The default implementation returns the value of the - * {@link #contentEncoding contentEncoding} attribute. - * - * @return the Content-Encoding header, or {@code null} - */ - @Override - public Header getContentEncoding() { - return this.contentEncoding; - } - - /** - * Obtains the 'chunked' flag. - * The default implementation returns the value of the - * {@link #chunked chunked} attribute. - * - * @return the 'chunked' flag - */ - @Override - public boolean isChunked() { - return this.chunked; - } - - - /** - * Specifies the Content-Type header. - * The default implementation sets the value of the - * {@link #contentType contentType} attribute. - * - * @param contentType the new Content-Encoding header, or - * {@code null} to unset - */ - public void setContentType(final Header contentType) { - this.contentType = contentType; - } - - /** - * Specifies the Content-Type header, as a string. - * The default implementation calls - * {@link #setContentType(Header) setContentType(Header)}. - * - * @param ctString the new Content-Type header, or - * {@code null} to unset - */ - public void setContentType(final String ctString) { - Header h = null; - if (ctString != null) { - h = new BasicHeader(HTTP.CONTENT_TYPE, ctString); - } - setContentType(h); - } - - - /** - * Specifies the Content-Encoding header. - * The default implementation sets the value of the - * {@link #contentEncoding contentEncoding} attribute. - * - * @param contentEncoding the new Content-Encoding header, or - * {@code null} to unset - */ - public void setContentEncoding(final Header contentEncoding) { - this.contentEncoding = contentEncoding; - } - - /** - * Specifies the Content-Encoding header, as a string. - * The default implementation calls - * {@link #setContentEncoding(Header) setContentEncoding(Header)}. - * - * @param ceString the new Content-Encoding header, or - * {@code null} to unset - */ - public void setContentEncoding(final String ceString) { - Header h = null; - if (ceString != null) { - h = new BasicHeader(HTTP.CONTENT_ENCODING, ceString); - } - setContentEncoding(h); - } - - - /** - * Specifies the 'chunked' flag. - *

- * Note that the chunked setting is a hint only. - * If using HTTP/1.0, chunking is never performed. - * Otherwise, even if chunked is false, HttpClient must - * use chunk coding if the entity content length is - * unknown (-1). - *

- * The default implementation sets the value of the - * {@link #chunked chunked} attribute. - * - * @param b the new 'chunked' flag - */ - public void setChunked(final boolean b) { - this.chunked = b; - } - - - /** - * The default implementation does not consume anything. - * - * @deprecated (4.1) Either use {@link #getContent()} and call {@link java.io.InputStream#close()} on that; - * otherwise call {@link #writeTo(java.io.OutputStream)} which is required to free the resources. - */ - @Override - @Deprecated - public void consumeContent() throws IOException { - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - sb.append('['); - if (contentType != null) { - sb.append("Content-Type: "); - sb.append(contentType.getValue()); - sb.append(','); - } - if (contentEncoding != null) { - sb.append("Content-Encoding: "); - sb.append(contentEncoding.getValue()); - sb.append(','); - } - final long len = getContentLength(); - if (len >= 0) { - sb.append("Content-Length: "); - sb.append(len); - sb.append(','); - } - sb.append("Chunked: "); - sb.append(chunked); - sb.append(']'); - return sb.toString(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/BasicHttpEntity.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/BasicHttpEntity.java deleted file mode 100644 index 8b796f8a..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/BasicHttpEntity.java +++ /dev/null @@ -1,131 +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 com.tracelytics.ext.apache.http.entity; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.impl.io.EmptyInputStream; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.Asserts; - -/** - * A generic streamed, non-repeatable entity that obtains its content - * from an {@link InputStream}. - * - * @since 4.0 - */ -@NotThreadSafe -public class BasicHttpEntity extends AbstractHttpEntity { - - private InputStream content; - private long length; - - /** - * Creates a new basic entity. - * The content is initially missing, the content length - * is set to a negative number. - */ - public BasicHttpEntity() { - super(); - this.length = -1; - } - - @Override - public long getContentLength() { - return this.length; - } - - /** - * Obtains the content, once only. - * - * @return the content, if this is the first call to this method - * since {@link #setContent setContent} has been called - * - * @throws IllegalStateException - * if the content has not been provided - */ - @Override - public InputStream getContent() throws IllegalStateException { - Asserts.check(this.content != null, "Content has not been provided"); - return this.content; - } - - /** - * Tells that this entity is not repeatable. - * - * @return {@code false} - */ - @Override - public boolean isRepeatable() { - return false; - } - - /** - * Specifies the length of the content. - * - * @param len the number of bytes in the content, or - * a negative number to indicate an unknown length - */ - public void setContentLength(final long len) { - this.length = len; - } - - /** - * Specifies the content. - * - * @param instream the stream to return with the next call to - * {@link #getContent getContent} - */ - public void setContent(final InputStream instream) { - this.content = instream; - } - - @Override - public void writeTo(final OutputStream outstream) throws IOException { - Args.notNull(outstream, "Output stream"); - final InputStream instream = getContent(); - try { - int l; - final byte[] tmp = new byte[OUTPUT_BUFFER_SIZE]; - while ((l = instream.read(tmp)) != -1) { - outstream.write(tmp, 0, l); - } - } finally { - instream.close(); - } - } - - @Override - public boolean isStreaming() { - return this.content != null && this.content != EmptyInputStream.INSTANCE; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/BufferedHttpEntity.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/BufferedHttpEntity.java deleted file mode 100644 index f3ff7953..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/BufferedHttpEntity.java +++ /dev/null @@ -1,125 +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 com.tracelytics.ext.apache.http.entity; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.EntityUtils; - -/** - * A wrapping entity that buffers it content if necessary. - * The buffered entity is always repeatable. - * If the wrapped entity is repeatable itself, calls are passed through. - * If the wrapped entity is not repeatable, the content is read into a - * buffer once and provided from there as often as required. - * - * @since 4.0 - */ -@NotThreadSafe -public class BufferedHttpEntity extends HttpEntityWrapper { - - private final byte[] buffer; - - /** - * Creates a new buffered entity wrapper. - * - * @param entity the entity to wrap, not null - * @throws IllegalArgumentException if wrapped is null - */ - public BufferedHttpEntity(final HttpEntity entity) throws IOException { - super(entity); - if (!entity.isRepeatable() || entity.getContentLength() < 0) { - this.buffer = EntityUtils.toByteArray(entity); - } else { - this.buffer = null; - } - } - - @Override - public long getContentLength() { - if (this.buffer != null) { - return this.buffer.length; - } else { - return super.getContentLength(); - } - } - - @Override - public InputStream getContent() throws IOException { - if (this.buffer != null) { - return new ByteArrayInputStream(this.buffer); - } else { - return super.getContent(); - } - } - - /** - * Tells that this entity does not have to be chunked. - * - * @return {@code false} - */ - @Override - public boolean isChunked() { - return (buffer == null) && super.isChunked(); - } - - /** - * Tells that this entity is repeatable. - * - * @return {@code true} - */ - @Override - public boolean isRepeatable() { - return true; - } - - - @Override - public void writeTo(final OutputStream outstream) throws IOException { - Args.notNull(outstream, "Output stream"); - if (this.buffer != null) { - outstream.write(this.buffer); - } else { - super.writeTo(outstream); - } - } - - - // non-javadoc, see interface HttpEntity - @Override - public boolean isStreaming() { - return (buffer == null) && super.isStreaming(); - } - -} // class BufferedHttpEntity diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/ByteArrayEntity.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/ByteArrayEntity.java deleted file mode 100644 index 4f9c0125..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/ByteArrayEntity.java +++ /dev/null @@ -1,136 +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 com.tracelytics.ext.apache.http.entity; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * A self contained, repeatable entity that obtains its content from a byte array. - * - * @since 4.0 - */ -@NotThreadSafe -public class ByteArrayEntity extends AbstractHttpEntity implements Cloneable { - - /** - * @deprecated (4.2) - */ - @Deprecated - protected final byte[] content; - private final byte[] b; - private final int off, len; - - /** - * @since 4.2 - */ - @SuppressWarnings("deprecation") - public ByteArrayEntity(final byte[] b, final ContentType contentType) { - super(); - Args.notNull(b, "Source byte array"); - this.content = b; - this.b = b; - this.off = 0; - this.len = this.b.length; - if (contentType != null) { - setContentType(contentType.toString()); - } - } - - /** - * @since 4.2 - */ - @SuppressWarnings("deprecation") - public ByteArrayEntity(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.content = b; - this.b = b; - this.off = off; - this.len = len; - if (contentType != null) { - setContentType(contentType.toString()); - } - } - - public ByteArrayEntity(final byte[] b) { - this(b, null); - } - - public ByteArrayEntity(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(); - } - - - /** - * Tells that this entity is not streaming. - * - * @return {@code false} - */ - @Override - public boolean isStreaming() { - return false; - } - - @Override - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } - -} // class ByteArrayEntity diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/ContentLengthStrategy.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/ContentLengthStrategy.java deleted file mode 100644 index 64a943d1..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/ContentLengthStrategy.java +++ /dev/null @@ -1,57 +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 com.tracelytics.ext.apache.http.entity; - -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpMessage; - -/** - * Represents a strategy to determine length of the enclosed content entity - * based on properties of the HTTP message. - * - * @since 4.0 - */ -public interface ContentLengthStrategy { - - public static final int IDENTITY = -1; - public static final int CHUNKED = -2; - - /** - * Returns length of the given message in bytes. The returned value - * must be a non-negative number, {@link #IDENTITY} if the end of the - * message will be delimited by the end of connection, or {@link #CHUNKED} - * if the message is chunk coded - * - * @param message HTTP message - * @return content length, {@link #IDENTITY}, or {@link #CHUNKED} - * - * @throws HttpException in case of HTTP protocol violation - */ - long determineLength(HttpMessage message) throws HttpException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/ContentProducer.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/ContentProducer.java deleted file mode 100644 index 41ceefff..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/ContentProducer.java +++ /dev/null @@ -1,44 +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 com.tracelytics.ext.apache.http.entity; - -import java.io.IOException; -import java.io.OutputStream; - -/** - * An abstract entity content producer. - *

Content producers are expected to be able to produce their - * content multiple times

- * - * @since 4.0 - */ -public interface ContentProducer { - - void writeTo(OutputStream outstream) throws IOException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/ContentType.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/ContentType.java deleted file mode 100644 index 6513b843..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/ContentType.java +++ /dev/null @@ -1,419 +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 com.tracelytics.ext.apache.http.entity; - -import java.io.Serializable; -import java.nio.charset.Charset; -import java.nio.charset.UnsupportedCharsetException; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import com.tracelytics.ext.apache.http.Consts; -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HeaderElement; -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.NameValuePair; -import com.tracelytics.ext.apache.http.ParseException; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.message.BasicHeaderValueFormatter; -import com.tracelytics.ext.apache.http.message.BasicHeaderValueParser; -import com.tracelytics.ext.apache.http.message.BasicNameValuePair; -import com.tracelytics.ext.apache.http.message.ParserCursor; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; -import com.tracelytics.ext.apache.http.util.TextUtils; - -/** - * Content type information consisting of a MIME type and an optional charset. - *

- * This class makes no attempts to verify validity of the MIME type. - * The input parameters of the {@link #create(String, String)} method, however, may not - * contain characters {@code <">, <;>, <,>} reserved by the HTTP specification. - * - * @since 4.2 - */ -@Immutable -public final class ContentType implements Serializable { - - private static final long serialVersionUID = -7768694718232371896L; - - // constants - public static final ContentType APPLICATION_ATOM_XML = create( - "application/atom+xml", Consts.ISO_8859_1); - public static final ContentType APPLICATION_FORM_URLENCODED = create( - "application/x-www-form-urlencoded", Consts.ISO_8859_1); - public static final ContentType APPLICATION_JSON = create( - "application/json", Consts.UTF_8); - public static final ContentType APPLICATION_OCTET_STREAM = create( - "application/octet-stream", (Charset) null); - public static final ContentType APPLICATION_SVG_XML = create( - "application/svg+xml", Consts.ISO_8859_1); - public static final ContentType APPLICATION_XHTML_XML = create( - "application/xhtml+xml", Consts.ISO_8859_1); - public static final ContentType APPLICATION_XML = create( - "application/xml", Consts.ISO_8859_1); - public static final ContentType MULTIPART_FORM_DATA = create( - "multipart/form-data", Consts.ISO_8859_1); - public static final ContentType TEXT_HTML = create( - "text/html", Consts.ISO_8859_1); - public static final ContentType TEXT_PLAIN = create( - "text/plain", Consts.ISO_8859_1); - public static final ContentType TEXT_XML = create( - "text/xml", Consts.ISO_8859_1); - public static final ContentType WILDCARD = create( - "*/*", (Charset) null); - - // defaults - public static final ContentType DEFAULT_TEXT = TEXT_PLAIN; - public static final ContentType DEFAULT_BINARY = APPLICATION_OCTET_STREAM; - - private final String mimeType; - private final Charset charset; - private final NameValuePair[] params; - - ContentType( - final String mimeType, - final Charset charset) { - this.mimeType = mimeType; - this.charset = charset; - this.params = null; - } - - ContentType( - final String mimeType, - final Charset charset, - final NameValuePair[] params) { - this.mimeType = mimeType; - this.charset = charset; - this.params = params; - } - - public String getMimeType() { - return this.mimeType; - } - - public Charset getCharset() { - return this.charset; - } - - /** - * @since 4.3 - */ - public String getParameter(final String name) { - Args.notEmpty(name, "Parameter name"); - if (this.params == null) { - return null; - } - for (final NameValuePair param: this.params) { - if (param.getName().equalsIgnoreCase(name)) { - return param.getValue(); - } - } - return null; - } - - /** - * Generates textual representation of this content type which can be used as the value - * of a {@code Content-Type} header. - */ - @Override - public String toString() { - final CharArrayBuffer buf = new CharArrayBuffer(64); - buf.append(this.mimeType); - if (this.params != null) { - buf.append("; "); - BasicHeaderValueFormatter.INSTANCE.formatParameters(buf, this.params, false); - } else if (this.charset != null) { - buf.append("; charset="); - buf.append(this.charset.name()); - } - return buf.toString(); - } - - private static boolean valid(final String s) { - for (int i = 0; i < s.length(); i++) { - final char ch = s.charAt(i); - if (ch == '"' || ch == ',' || ch == ';') { - return false; - } - } - return true; - } - - /** - * Creates a new instance of {@link ContentType}. - * - * @param mimeType MIME type. It may not be {@code null} or empty. It may not contain - * characters {@code <">, <;>, <,>} reserved by the HTTP specification. - * @param charset charset. - * @return content type - */ - public static ContentType create(final String mimeType, final Charset charset) { - final String type = Args.notBlank(mimeType, "MIME type").toLowerCase(Locale.ROOT); - Args.check(valid(type), "MIME type may not contain reserved characters"); - return new ContentType(type, charset); - } - - /** - * Creates a new instance of {@link ContentType} without a charset. - * - * @param mimeType MIME type. It may not be {@code null} or empty. It may not contain - * characters {@code <">, <;>, <,>} reserved by the HTTP specification. - * @return content type - */ - public static ContentType create(final String mimeType) { - return new ContentType(mimeType, (Charset) null); - } - - /** - * Creates a new instance of {@link ContentType}. - * - * @param mimeType MIME type. It may not be {@code null} or empty. It may not contain - * characters {@code <">, <;>, <,>} reserved by the HTTP specification. - * @param charset charset. It may not contain characters {@code <">, <;>, <,>} reserved by the HTTP - * specification. This parameter is optional. - * @return content type - * @throws UnsupportedCharsetException Thrown when the named charset is not available in - * this instance of the Java virtual machine - */ - public static ContentType create( - final String mimeType, final String charset) throws UnsupportedCharsetException { - return create(mimeType, !TextUtils.isBlank(charset) ? Charset.forName(charset) : null); - } - - private static ContentType create(final HeaderElement helem, final boolean strict) { - return create(helem.getName(), helem.getParameters(), strict); - } - - private static ContentType create(final String mimeType, final NameValuePair[] params, final boolean strict) { - Charset charset = null; - for (final NameValuePair param: params) { - if (param.getName().equalsIgnoreCase("charset")) { - final String s = param.getValue(); - if (!TextUtils.isBlank(s)) { - try { - charset = Charset.forName(s); - } catch (UnsupportedCharsetException ex) { - if (strict) { - throw ex; - } - } - } - break; - } - } - return new ContentType(mimeType, charset, params != null && params.length > 0 ? params : null); - } - - /** - * Creates a new instance of {@link ContentType} with the given parameters. - * - * @param mimeType MIME type. It may not be {@code null} or empty. It may not contain - * characters {@code <">, <;>, <,>} reserved by the HTTP specification. - * @param params parameters. - * @return content type - * - * @since 4.4 - */ - public static ContentType create( - final String mimeType, final NameValuePair... params) throws UnsupportedCharsetException { - final String type = Args.notBlank(mimeType, "MIME type").toLowerCase(Locale.ROOT); - Args.check(valid(type), "MIME type may not contain reserved characters"); - return create(mimeType, params, true); - } - - /** - * Parses textual representation of {@code Content-Type} value. - * - * @param s text - * @return content type - * @throws ParseException if the given text does not represent a valid - * {@code Content-Type} value. - * @throws UnsupportedCharsetException Thrown when the named charset is not available in - * this instance of the Java virtual machine - */ - public static ContentType parse( - final String s) throws ParseException, UnsupportedCharsetException { - Args.notNull(s, "Content type"); - final CharArrayBuffer buf = new CharArrayBuffer(s.length()); - buf.append(s); - final ParserCursor cursor = new ParserCursor(0, s.length()); - final HeaderElement[] elements = BasicHeaderValueParser.INSTANCE.parseElements(buf, cursor); - if (elements.length > 0) { - return create(elements[0], true); - } else { - throw new ParseException("Invalid content type: " + s); - } - } - - /** - * Extracts {@code Content-Type} value from {@link HttpEntity} exactly as - * specified by the {@code Content-Type} header of the entity. Returns {@code null} - * if not specified. - * - * @param entity HTTP entity - * @return content type - * @throws ParseException if the given text does not represent a valid - * {@code Content-Type} value. - * @throws UnsupportedCharsetException Thrown when the named charset is not available in - * this instance of the Java virtual machine - */ - public static ContentType get( - final HttpEntity entity) throws ParseException, UnsupportedCharsetException { - if (entity == null) { - return null; - } - final Header header = entity.getContentType(); - if (header != null) { - final HeaderElement[] elements = header.getElements(); - if (elements.length > 0) { - return create(elements[0], true); - } - } - return null; - } - - /** - * Extracts {@code Content-Type} value from {@link HttpEntity}. Returns {@code null} - * if not specified or incorrect (could not be parsed).. - * - * @param entity HTTP entity - * @return content type - * - * @since 4.4 - * - */ - public static ContentType getLenient(final HttpEntity entity) { - if (entity == null) { - return null; - } - final Header header = entity.getContentType(); - if (header != null) { - try { - final HeaderElement[] elements = header.getElements(); - if (elements.length > 0) { - return create(elements[0], false); - } - } catch (ParseException ex) { - return null; - } - } - return null; - } - - /** - * Extracts {@code Content-Type} value from {@link HttpEntity} or returns the default value - * {@link #DEFAULT_TEXT} if not explicitly specified. - * - * @param entity HTTP entity - * @return content type - * @throws ParseException if the given text does not represent a valid - * {@code Content-Type} value. - * @throws UnsupportedCharsetException Thrown when the named charset is not available in - * this instance of the Java virtual machine - */ - public static ContentType getOrDefault( - final HttpEntity entity) throws ParseException, UnsupportedCharsetException { - final ContentType contentType = get(entity); - return contentType != null ? contentType : DEFAULT_TEXT; - } - - /** - * Extracts {@code Content-Type} value from {@link HttpEntity} or returns the default value - * {@link #DEFAULT_TEXT} if not explicitly specified or incorrect (could not be parsed). - * - * @param entity HTTP entity - * @return content type - * - * @since 4.4 - */ - public static ContentType getLenientOrDefault( - final HttpEntity entity) throws ParseException, UnsupportedCharsetException { - final ContentType contentType = get(entity); - return contentType != null ? contentType : DEFAULT_TEXT; - } - - /** - * Creates a new instance with this MIME type and the given Charset. - * - * @param charset charset - * @return a new instance with this MIME type and the given Charset. - * @since 4.3 - */ - public ContentType withCharset(final Charset charset) { - return create(this.getMimeType(), charset); - } - - /** - * Creates a new instance with this MIME type and the given Charset name. - * - * @param charset name - * @return a new instance with this MIME type and the given Charset name. - * @throws UnsupportedCharsetException Thrown when the named charset is not available in - * this instance of the Java virtual machine - * @since 4.3 - */ - public ContentType withCharset(final String charset) { - return create(this.getMimeType(), charset); - } - - /** - * Creates a new instance with this MIME type and the given parameters. - * - * @param params - * @return a new instance with this MIME type and the given parameters. - * @since 4.4 - */ - public ContentType withParameters( - final NameValuePair... params) throws UnsupportedCharsetException { - if (params.length == 0) { - return this; - } - final Map paramMap = new LinkedHashMap(); - if (this.params != null) { - for (NameValuePair param: this.params) { - paramMap.put(param.getName(), param.getValue()); - } - } - for (NameValuePair param: params) { - paramMap.put(param.getName(), param.getValue()); - } - final List newParams = new ArrayList(paramMap.size() + 1); - if (this.charset != null && !paramMap.containsKey("charset")) { - newParams.add(new BasicNameValuePair("charset", this.charset.name())); - } - for (Map.Entry entry: paramMap.entrySet()) { - newParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); - } - return create(this.getMimeType(), newParams.toArray(new NameValuePair[newParams.size()]), true); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/EntityTemplate.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/EntityTemplate.java deleted file mode 100644 index c323de03..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/EntityTemplate.java +++ /dev/null @@ -1,81 +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 com.tracelytics.ext.apache.http.entity; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Entity that delegates the process of content generation - * to a {@link ContentProducer}. - * - * @since 4.0 - */ -public class EntityTemplate extends AbstractHttpEntity { - - private final ContentProducer contentproducer; - - public EntityTemplate(final ContentProducer contentproducer) { - super(); - this.contentproducer = Args.notNull(contentproducer, "Content producer"); - } - - @Override - public long getContentLength() { - return -1; - } - - @Override - public InputStream getContent() throws IOException { - final ByteArrayOutputStream buf = new ByteArrayOutputStream(); - writeTo(buf); - return new ByteArrayInputStream(buf.toByteArray()); - } - - @Override - public boolean isRepeatable() { - return true; - } - - @Override - public void writeTo(final OutputStream outstream) throws IOException { - Args.notNull(outstream, "Output stream"); - this.contentproducer.writeTo(outstream); - } - - @Override - public boolean isStreaming() { - return false; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/FileEntity.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/FileEntity.java deleted file mode 100644 index 29acbaa4..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/FileEntity.java +++ /dev/null @@ -1,126 +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 com.tracelytics.ext.apache.http.entity; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * A self contained, repeatable entity that obtains its content from a file. - * - * @since 4.0 - */ -@NotThreadSafe -public class FileEntity extends AbstractHttpEntity implements Cloneable { - - protected final File file; - - /** - * @deprecated (4.1.3) {@link #FileEntity(File, ContentType)} - */ - @Deprecated - public FileEntity(final File file, final String contentType) { - super(); - this.file = Args.notNull(file, "File"); - setContentType(contentType); - } - - /** - * @since 4.2 - */ - public FileEntity(final File file, final ContentType contentType) { - super(); - this.file = Args.notNull(file, "File"); - if (contentType != null) { - setContentType(contentType.toString()); - } - } - - /** - * @since 4.2 - */ - public FileEntity(final File file) { - super(); - this.file = Args.notNull(file, "File"); - } - - @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"); - final InputStream instream = new FileInputStream(this.file); - try { - final byte[] tmp = new byte[OUTPUT_BUFFER_SIZE]; - int l; - while ((l = instream.read(tmp)) != -1) { - outstream.write(tmp, 0, l); - } - outstream.flush(); - } finally { - instream.close(); - } - } - - /** - * Tells that this entity is not streaming. - * - * @return {@code false} - */ - @Override - public boolean isStreaming() { - return false; - } - - @Override - public Object clone() throws CloneNotSupportedException { - // File instance is considered immutable - // No need to make a copy of it - return super.clone(); - } - -} // class FileEntity diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/HttpEntityWrapper.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/HttpEntityWrapper.java deleted file mode 100644 index 9ded31e0..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/HttpEntityWrapper.java +++ /dev/null @@ -1,114 +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 com.tracelytics.ext.apache.http.entity; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Base class for wrapping entities. - * Keeps a {@link #wrappedEntity wrappedEntity} and delegates all - * calls to it. Implementations of wrapping entities can derive - * from this class and need to override only those methods that - * should not be delegated to the wrapped entity. - * - * @since 4.0 - */ -@NotThreadSafe -public class HttpEntityWrapper implements HttpEntity { - - /** The wrapped entity. */ - protected HttpEntity wrappedEntity; - - /** - * Creates a new entity wrapper. - */ - public HttpEntityWrapper(final HttpEntity wrappedEntity) { - super(); - this.wrappedEntity = Args.notNull(wrappedEntity, "Wrapped entity"); - } // constructor - - @Override - public boolean isRepeatable() { - return wrappedEntity.isRepeatable(); - } - - @Override - public boolean isChunked() { - return wrappedEntity.isChunked(); - } - - @Override - public long getContentLength() { - return wrappedEntity.getContentLength(); - } - - @Override - public Header getContentType() { - return wrappedEntity.getContentType(); - } - - @Override - public Header getContentEncoding() { - return wrappedEntity.getContentEncoding(); - } - - @Override - public InputStream getContent() - throws IOException { - return wrappedEntity.getContent(); - } - - @Override - public void writeTo(final OutputStream outstream) - throws IOException { - wrappedEntity.writeTo(outstream); - } - - @Override - public boolean isStreaming() { - return wrappedEntity.isStreaming(); - } - - /** - * @deprecated (4.1) Either use {@link #getContent()} and call {@link java.io.InputStream#close()} on that; - * otherwise call {@link #writeTo(OutputStream)} which is required to free the resources. - */ - @Override - @Deprecated - public void consumeContent() throws IOException { - wrappedEntity.consumeContent(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/InputStreamEntity.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/InputStreamEntity.java deleted file mode 100644 index 4561dc6b..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/InputStreamEntity.java +++ /dev/null @@ -1,160 +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 com.tracelytics.ext.apache.http.entity; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * A streamed, non-repeatable entity that obtains its content from - * an {@link InputStream}. - * - * @since 4.0 - */ -@NotThreadSafe -public class InputStreamEntity extends AbstractHttpEntity { - - private final InputStream content; - private final long length; - - /** - * Creates an entity with an unknown length. - * Equivalent to {@code new InputStreamEntity(instream, -1)}. - * - * @param instream input stream - * @throws IllegalArgumentException if {@code instream} is {@code null} - * @since 4.3 - */ - public InputStreamEntity(final InputStream instream) { - this(instream, -1); - } - - /** - * Creates an entity with a specified content length. - * - * @param instream input stream - * @param length of the input stream, {@code -1} if unknown - * @throws IllegalArgumentException if {@code instream} is {@code null} - */ - public InputStreamEntity(final InputStream instream, final long length) { - this(instream, length, null); - } - - /** - * Creates an entity with a content type and unknown length. - * Equivalent to {@code new InputStreamEntity(instream, -1, contentType)}. - * - * @param instream input stream - * @param contentType content type - * @throws IllegalArgumentException if {@code instream} is {@code null} - * @since 4.3 - */ - public InputStreamEntity(final InputStream instream, final ContentType contentType) { - this(instream, -1, contentType); - } - - /** - * @param instream input stream - * @param length of the input stream, {@code -1} if unknown - * @param contentType for specifying the {@code Content-Type} header, may be {@code null} - * @throws IllegalArgumentException if {@code instream} is {@code null} - * @since 4.2 - */ - public InputStreamEntity(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; - } - - /** - * @return the content length or {@code -1} if unknown - */ - @Override - public long getContentLength() { - return this.length; - } - - @Override - public InputStream getContent() throws IOException { - return this.content; - } - - /** - * Writes bytes from the {@code InputStream} this entity was constructed - * with to an {@code OutputStream}. The content length - * determines how many bytes are written. If the length is unknown ({@code -1}), the - * stream will be completely consumed (to the end of the stream). - * - */ - @Override - public void writeTo(final OutputStream outstream) throws IOException { - Args.notNull(outstream, "Output stream"); - final InputStream instream = this.content; - try { - final byte[] buffer = new byte[OUTPUT_BUFFER_SIZE]; - 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(OUTPUT_BUFFER_SIZE, remaining)); - if (l == -1) { - break; - } - outstream.write(buffer, 0, l); - remaining -= l; - } - } - } finally { - instream.close(); - } - } - - @Override - public boolean isStreaming() { - return true; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/SerializableEntity.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/SerializableEntity.java deleted file mode 100644 index 092b2ef1..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/SerializableEntity.java +++ /dev/null @@ -1,131 +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 com.tracelytics.ext.apache.http.entity; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.ObjectOutputStream; -import java.io.OutputStream; -import java.io.Serializable; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * A streamed entity that obtains its content from a {@link Serializable}. - * The content obtained from the {@link Serializable} instance can - * optionally be buffered in a byte array in order to make the - * entity self-contained and repeatable. - * - * @since 4.0 - */ -@NotThreadSafe -public class SerializableEntity extends AbstractHttpEntity { - - private byte[] objSer; - - private Serializable objRef; - - /** - * Creates new instance of this class. - * - * @param ser input - * @param bufferize tells whether the content should be - * stored in an internal buffer - * @throws IOException in case of an I/O error - */ - public SerializableEntity(final Serializable ser, final boolean bufferize) throws IOException { - super(); - Args.notNull(ser, "Source object"); - if (bufferize) { - createBytes(ser); - } else { - this.objRef = ser; - } - } - - /** - * @since 4.3 - */ - public SerializableEntity(final Serializable ser) { - super(); - Args.notNull(ser, "Source object"); - this.objRef = ser; - } - - private void createBytes(final Serializable ser) throws IOException { - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - final ObjectOutputStream out = new ObjectOutputStream(baos); - out.writeObject(ser); - out.flush(); - this.objSer = baos.toByteArray(); - } - - @Override - public InputStream getContent() throws IOException, IllegalStateException { - if (this.objSer == null) { - createBytes(this.objRef); - } - return new ByteArrayInputStream(this.objSer); - } - - @Override - public long getContentLength() { - if (this.objSer == null) { - return -1; - } else { - return this.objSer.length; - } - } - - @Override - public boolean isRepeatable() { - return true; - } - - @Override - public boolean isStreaming() { - return this.objSer == null; - } - - @Override - public void writeTo(final OutputStream outstream) throws IOException { - Args.notNull(outstream, "Output stream"); - if (this.objSer == null) { - final ObjectOutputStream out = new ObjectOutputStream(outstream); - out.writeObject(this.objRef); - out.flush(); - } else { - outstream.write(this.objSer); - outstream.flush(); - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/StringEntity.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/StringEntity.java deleted file mode 100644 index 5eb3e81c..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/StringEntity.java +++ /dev/null @@ -1,188 +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 com.tracelytics.ext.apache.http.entity; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.nio.charset.Charset; -import java.nio.charset.UnsupportedCharsetException; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.protocol.HTTP; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * A self contained, repeatable entity that obtains its content from - * a {@link String}. - * - * @since 4.0 - */ -@NotThreadSafe -public class StringEntity extends AbstractHttpEntity implements Cloneable { - - protected final byte[] content; - - /** - * Creates a StringEntity with the specified content and content type. - * - * @param string content to be used. Not {@code null}. - * @param contentType content type to be used. May be {@code null}, in which case the default - * MIME type {@link ContentType#TEXT_PLAIN} is assumed. - * - * @throws IllegalArgumentException if the string parameter is null - * @throws UnsupportedCharsetException Thrown when the named charset is not available in - * this instance of the Java virtual machine - * @since 4.2 - */ - public StringEntity(final String string, final ContentType contentType) throws UnsupportedCharsetException { - super(); - Args.notNull(string, "Source string"); - Charset charset = contentType != null ? contentType.getCharset() : null; - if (charset == null) { - charset = HTTP.DEF_CONTENT_CHARSET; - } - this.content = string.getBytes(charset); - if (contentType != null) { - setContentType(contentType.toString()); - } - } - - /** - * Creates a StringEntity with the specified content, MIME type and charset - * - * @param string content to be used. Not {@code null}. - * @param mimeType MIME type to be used. May be {@code null}, in which case the default - * is {@link HTTP#PLAIN_TEXT_TYPE} i.e. "text/plain" - * @param charset character set to be used. May be {@code null}, in which case the default - * is {@link HTTP#DEF_CONTENT_CHARSET} i.e. "ISO-8859-1" - * @throws UnsupportedEncodingException If the named charset is not supported. - * - * @since 4.1 - * @throws IllegalArgumentException if the string parameter is null - * - * @deprecated (4.1.3) use {@link #StringEntity(String, ContentType)} - */ - @Deprecated - public StringEntity( - final String string, final String mimeType, final String charset) throws UnsupportedEncodingException { - super(); - Args.notNull(string, "Source string"); - final String mt = mimeType != null ? mimeType : HTTP.PLAIN_TEXT_TYPE; - final String cs = charset != null ? charset :HTTP.DEFAULT_CONTENT_CHARSET; - this.content = string.getBytes(cs); - setContentType(mt + HTTP.CHARSET_PARAM + cs); - } - - /** - * Creates a StringEntity with the specified content and charset. The MIME type defaults - * to "text/plain". - * - * @param string content to be used. Not {@code null}. - * @param charset character set to be used. May be {@code null}, in which case the default - * is {@link HTTP#DEF_CONTENT_CHARSET} is assumed - * - * @throws IllegalArgumentException if the string parameter is null - * @throws UnsupportedCharsetException Thrown when the named charset is not available in - * this instance of the Java virtual machine - */ - public StringEntity(final String string, final String charset) - throws UnsupportedCharsetException { - this(string, ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), charset)); - } - - /** - * Creates a StringEntity with the specified content and charset. The MIME type defaults - * to "text/plain". - * - * @param string content to be used. Not {@code null}. - * @param charset character set to be used. May be {@code null}, in which case the default - * is {@link HTTP#DEF_CONTENT_CHARSET} is assumed - * - * @throws IllegalArgumentException if the string parameter is null - * - * @since 4.2 - */ - public StringEntity(final String string, final Charset charset) { - this(string, ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), charset)); - } - - /** - * Creates a StringEntity with the specified content. The content type defaults to - * {@link ContentType#TEXT_PLAIN}. - * - * @param string content to be used. Not {@code null}. - * - * @throws IllegalArgumentException if the string parameter is null - * @throws UnsupportedEncodingException if the default HTTP charset is not supported. - */ - public StringEntity(final String string) - throws UnsupportedEncodingException { - this(string, ContentType.DEFAULT_TEXT); - } - - @Override - public boolean isRepeatable() { - return true; - } - - @Override - public long getContentLength() { - return this.content.length; - } - - @Override - public InputStream getContent() throws IOException { - return new ByteArrayInputStream(this.content); - } - - @Override - public void writeTo(final OutputStream outstream) throws IOException { - Args.notNull(outstream, "Output stream"); - outstream.write(this.content); - outstream.flush(); - } - - /** - * Tells that this entity is not streaming. - * - * @return {@code false} - */ - @Override - public boolean isStreaming() { - return false; - } - - @Override - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } - -} // class StringEntity diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/package-info.java deleted file mode 100644 index 9e950341..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/entity/package-info.java +++ /dev/null @@ -1,31 +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 - * . - * - */ - -/** - * Core HTTP entity implementations. - */ -package com.tracelytics.ext.apache.http.entity; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/AbstractHttpClientConnection.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/AbstractHttpClientConnection.java deleted file mode 100644 index dbbc6aa0..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/AbstractHttpClientConnection.java +++ /dev/null @@ -1,324 +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 com.tracelytics.ext.apache.http.impl; - -import java.io.IOException; -import java.net.SocketTimeoutException; - -import com.tracelytics.ext.apache.http.HttpClientConnection; -import com.tracelytics.ext.apache.http.HttpConnectionMetrics; -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpEntityEnclosingRequest; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.HttpResponseFactory; -import com.tracelytics.ext.apache.http.HttpStatus; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.impl.entity.LaxContentLengthStrategy; -import com.tracelytics.ext.apache.http.impl.entity.StrictContentLengthStrategy; -import com.tracelytics.ext.apache.http.impl.io.DefaultHttpResponseParser; -import com.tracelytics.ext.apache.http.io.EofSensor; -import com.tracelytics.ext.apache.http.io.HttpMessageParser; -import com.tracelytics.ext.apache.http.io.HttpMessageWriter; -import com.tracelytics.ext.apache.http.io.HttpTransportMetrics; -import com.tracelytics.ext.apache.http.io.SessionInputBuffer; -import com.tracelytics.ext.apache.http.io.SessionOutputBuffer; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.impl.entity.EntityDeserializer; -import com.tracelytics.ext.apache.http.impl.entity.EntitySerializer; -import com.tracelytics.ext.apache.http.impl.io.HttpRequestWriter; - -/** - * Abstract client-side HTTP connection capable of transmitting and receiving - * data using arbitrary {@link SessionInputBuffer} and - * {@link SessionOutputBuffer} implementations. - *

- * The following parameters can be used to customize the behavior of this - * class: - *

    - *
  • {@link com.tracelytics.ext.apache.http.params.CoreProtocolPNames#STRICT_TRANSFER_ENCODING}
  • - *
  • {@link com.tracelytics.ext.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}
  • - *
  • {@link com.tracelytics.ext.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}
  • - *
- * - * @since 4.0 - * - * @deprecated (4.3) use {@link DefaultBHttpClientConnection} - */ -@NotThreadSafe -@Deprecated -public abstract class AbstractHttpClientConnection implements HttpClientConnection { - - private final EntitySerializer entityserializer; - private final EntityDeserializer entitydeserializer; - - private SessionInputBuffer inbuffer = null; - private SessionOutputBuffer outbuffer = null; - private EofSensor eofSensor = null; - private HttpMessageParser responseParser = null; - private HttpMessageWriter requestWriter = null; - private HttpConnectionMetricsImpl metrics = null; - - /** - * Creates an instance of this class. - *

- * This constructor will invoke {@link #createEntityDeserializer()} - * and {@link #createEntitySerializer()} methods in order to initialize - * HTTP entity serializer and deserializer implementations for this - * connection. - */ - public AbstractHttpClientConnection() { - super(); - this.entityserializer = createEntitySerializer(); - this.entitydeserializer = createEntityDeserializer(); - } - - /** - * Asserts if the connection is open. - * - * @throws IllegalStateException if the connection is not open. - */ - protected abstract void assertOpen() throws IllegalStateException; - - /** - * Creates an instance of {@link EntityDeserializer} with the - * {@link LaxContentLengthStrategy} implementation to be used for - * de-serializing entities received over this connection. - *

- * This method can be overridden in a super class in order to create - * instances of {@link EntityDeserializer} using a custom - * {@link com.tracelytics.ext.apache.http.entity.ContentLengthStrategy}. - * - * @return HTTP entity deserializer - */ - protected EntityDeserializer createEntityDeserializer() { - return new EntityDeserializer(new LaxContentLengthStrategy()); - } - - /** - * Creates an instance of {@link EntitySerializer} with the - * {@link StrictContentLengthStrategy} implementation to be used for - * serializing HTTP entities sent over this connection. - *

- * This method can be overridden in a super class in order to create - * instances of {@link EntitySerializer} using a custom - * {@link com.tracelytics.ext.apache.http.entity.ContentLengthStrategy}. - * - * @return HTTP entity serialzier. - */ - protected EntitySerializer createEntitySerializer() { - return new EntitySerializer(new StrictContentLengthStrategy()); - } - - /** - * Creates an instance of {@link DefaultHttpResponseFactory} to be used - * for creating {@link HttpResponse} objects received by over this - * connection. - *

- * This method can be overridden in a super class in order to provide - * a different implementation of the {@link HttpResponseFactory} interface. - * - * @return HTTP response factory. - */ - protected HttpResponseFactory createHttpResponseFactory() { - return DefaultHttpResponseFactory.INSTANCE; - } - - /** - * Creates an instance of {@link HttpMessageParser} to be used for parsing - * HTTP responses received over this connection. - *

- * This method can be overridden in a super class in order to provide - * a different implementation of the {@link HttpMessageParser} interface or - * to pass a different implementation of the - * {@link com.tracelytics.ext.apache.http.message.LineParser} to the the - * {@link DefaultHttpResponseParser} constructor. - * - * @param buffer the session input buffer. - * @param responseFactory the HTTP response factory. - * @param params HTTP parameters. - * @return HTTP message parser. - */ - protected HttpMessageParser createResponseParser( - final SessionInputBuffer buffer, - final HttpResponseFactory responseFactory, - final HttpParams params) { - return new DefaultHttpResponseParser(buffer, null, responseFactory, params); - } - - /** - * Creates an instance of {@link HttpMessageWriter} to be used for - * writing out HTTP requests sent over this connection. - *

- * This method can be overridden in a super class in order to provide - * a different implementation of the {@link HttpMessageWriter} interface or - * to pass a different implementation of - * {@link com.tracelytics.ext.apache.http.message.LineFormatter} to the the default implementation - * {@link HttpRequestWriter}. - * - * @param buffer the session output buffer - * @param params HTTP parameters - * @return HTTP message writer - */ - protected HttpMessageWriter createRequestWriter( - final SessionOutputBuffer buffer, - final HttpParams params) { - return new HttpRequestWriter(buffer, null, params); - } - - /** - * @since 4.1 - */ - protected HttpConnectionMetricsImpl createConnectionMetrics( - final HttpTransportMetrics inTransportMetric, - final HttpTransportMetrics outTransportMetric) { - return new HttpConnectionMetricsImpl(inTransportMetric, outTransportMetric); - } - - /** - * Initializes this connection object with {@link SessionInputBuffer} and - * {@link SessionOutputBuffer} instances to be used for sending and - * receiving data. These session buffers can be bound to any arbitrary - * physical output medium. - *

- * This method will invoke {@link #createHttpResponseFactory()}, - * {@link #createRequestWriter(SessionOutputBuffer, HttpParams)} - * and {@link #createResponseParser(SessionInputBuffer, HttpResponseFactory, HttpParams)} - * methods to initialize HTTP request writer and response parser for this - * connection. - * - * @param inbuffer the session input buffer. - * @param outbuffer the session output buffer. - * @param params HTTP parameters. - */ - protected void init( - final SessionInputBuffer inbuffer, - final SessionOutputBuffer outbuffer, - final HttpParams params) { - this.inbuffer = Args.notNull(inbuffer, "Input session buffer"); - this.outbuffer = Args.notNull(outbuffer, "Output session buffer"); - if (inbuffer instanceof EofSensor) { - this.eofSensor = (EofSensor) inbuffer; - } - this.responseParser = createResponseParser( - inbuffer, - createHttpResponseFactory(), - params); - this.requestWriter = createRequestWriter( - outbuffer, params); - this.metrics = createConnectionMetrics( - inbuffer.getMetrics(), - outbuffer.getMetrics()); - } - - public boolean isResponseAvailable(final int timeout) throws IOException { - assertOpen(); - try { - return this.inbuffer.isDataAvailable(timeout); - } catch (final SocketTimeoutException ex) { - return false; - } - } - - public void sendRequestHeader(final HttpRequest request) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - assertOpen(); - this.requestWriter.write(request); - this.metrics.incrementRequestCount(); - } - - public void sendRequestEntity(final HttpEntityEnclosingRequest request) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - assertOpen(); - if (request.getEntity() == null) { - return; - } - this.entityserializer.serialize( - this.outbuffer, - request, - request.getEntity()); - } - - protected void doFlush() throws IOException { - this.outbuffer.flush(); - } - - public void flush() throws IOException { - assertOpen(); - doFlush(); - } - - public HttpResponse receiveResponseHeader() - throws HttpException, IOException { - assertOpen(); - final HttpResponse response = this.responseParser.parse(); - if (response.getStatusLine().getStatusCode() >= HttpStatus.SC_OK) { - this.metrics.incrementResponseCount(); - } - return response; - } - - public void receiveResponseEntity(final HttpResponse response) - throws HttpException, IOException { - Args.notNull(response, "HTTP response"); - assertOpen(); - final HttpEntity entity = this.entitydeserializer.deserialize(this.inbuffer, response); - response.setEntity(entity); - } - - protected boolean isEof() { - return this.eofSensor != null && this.eofSensor.isEof(); - } - - public boolean isStale() { - if (!isOpen()) { - return true; - } - if (isEof()) { - return true; - } - try { - this.inbuffer.isDataAvailable(1); - return isEof(); - } catch (final SocketTimeoutException ex) { - return false; - } catch (final IOException ex) { - return true; - } - } - - public HttpConnectionMetrics getMetrics() { - return this.metrics; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/AbstractHttpServerConnection.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/AbstractHttpServerConnection.java deleted file mode 100644 index 77987a14..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/AbstractHttpServerConnection.java +++ /dev/null @@ -1,311 +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 com.tracelytics.ext.apache.http.impl; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.HttpConnectionMetrics; -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpEntityEnclosingRequest; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpRequestFactory; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.HttpServerConnection; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.impl.entity.DisallowIdentityContentLengthStrategy; -import com.tracelytics.ext.apache.http.impl.entity.LaxContentLengthStrategy; -import com.tracelytics.ext.apache.http.impl.entity.StrictContentLengthStrategy; -import com.tracelytics.ext.apache.http.impl.io.DefaultHttpRequestParser; -import com.tracelytics.ext.apache.http.io.EofSensor; -import com.tracelytics.ext.apache.http.io.HttpMessageParser; -import com.tracelytics.ext.apache.http.io.HttpMessageWriter; -import com.tracelytics.ext.apache.http.io.HttpTransportMetrics; -import com.tracelytics.ext.apache.http.io.SessionInputBuffer; -import com.tracelytics.ext.apache.http.io.SessionOutputBuffer; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.impl.entity.EntityDeserializer; -import com.tracelytics.ext.apache.http.impl.entity.EntitySerializer; -import com.tracelytics.ext.apache.http.impl.io.HttpResponseWriter; - -/** - * Abstract server-side HTTP connection capable of transmitting and receiving - * data using arbitrary {@link SessionInputBuffer} and - * {@link SessionOutputBuffer} implementations. - *

- * The following parameters can be used to customize the behavior of this - * class: - *

    - *
  • {@link com.tracelytics.ext.apache.http.params.CoreProtocolPNames#STRICT_TRANSFER_ENCODING}
  • - *
  • {@link com.tracelytics.ext.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}
  • - *
  • {@link com.tracelytics.ext.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}
  • - *
- * - * @since 4.0 - * - * @deprecated (4.3) use {@link DefaultBHttpServerConnection} - */ -@NotThreadSafe -@Deprecated -public abstract class AbstractHttpServerConnection implements HttpServerConnection { - - private final EntitySerializer entityserializer; - private final EntityDeserializer entitydeserializer; - - private SessionInputBuffer inbuffer = null; - private SessionOutputBuffer outbuffer = null; - private EofSensor eofSensor = null; - private HttpMessageParser requestParser = null; - private HttpMessageWriter responseWriter = null; - private HttpConnectionMetricsImpl metrics = null; - - /** - * Creates an instance of this class. - *

- * This constructor will invoke {@link #createEntityDeserializer()} - * and {@link #createEntitySerializer()} methods in order to initialize - * HTTP entity serializer and deserializer implementations for this - * connection. - */ - public AbstractHttpServerConnection() { - super(); - this.entityserializer = createEntitySerializer(); - this.entitydeserializer = createEntityDeserializer(); - } - - /** - * Asserts if the connection is open. - * - * @throws IllegalStateException if the connection is not open. - */ - protected abstract void assertOpen() throws IllegalStateException; - - /** - * Creates an instance of {@link EntityDeserializer} with the - * {@link LaxContentLengthStrategy} implementation to be used for - * de-serializing entities received over this connection. - *

- * This method can be overridden in a super class in order to create - * instances of {@link EntityDeserializer} using a custom - * {@link com.tracelytics.ext.apache.http.entity.ContentLengthStrategy}. - * - * @return HTTP entity deserializer - */ - protected EntityDeserializer createEntityDeserializer() { - return new EntityDeserializer(new DisallowIdentityContentLengthStrategy( - new LaxContentLengthStrategy(0))); - } - - /** - * Creates an instance of {@link EntitySerializer} with the - * {@link StrictContentLengthStrategy} implementation to be used for - * serializing HTTP entities sent over this connection. - *

- * This method can be overridden in a super class in order to create - * instances of {@link EntitySerializer} using a custom - * {@link com.tracelytics.ext.apache.http.entity.ContentLengthStrategy}. - * - * @return HTTP entity serialzier. - */ - protected EntitySerializer createEntitySerializer() { - return new EntitySerializer(new StrictContentLengthStrategy()); - } - - /** - * Creates an instance of {@link DefaultHttpRequestFactory} to be used - * for creating {@link HttpRequest} objects received by over this - * connection. - *

- * This method can be overridden in a super class in order to provide - * a different implementation of the {@link HttpRequestFactory} interface. - * - * @return HTTP request factory. - */ - protected HttpRequestFactory createHttpRequestFactory() { - return DefaultHttpRequestFactory.INSTANCE; - } - - /** - * Creates an instance of {@link HttpMessageParser} to be used for parsing - * HTTP requests received over this connection. - *

- * This method can be overridden in a super class in order to provide - * a different implementation of the {@link HttpMessageParser} interface or - * to pass a different implementation of the - * {@link com.tracelytics.ext.apache.http.message.LineParser} to the - * {@link DefaultHttpRequestParser} constructor. - * - * @param buffer the session input buffer. - * @param requestFactory the HTTP request factory. - * @param params HTTP parameters. - * @return HTTP message parser. - */ - protected HttpMessageParser createRequestParser( - final SessionInputBuffer buffer, - final HttpRequestFactory requestFactory, - final HttpParams params) { - return new DefaultHttpRequestParser(buffer, null, requestFactory, params); - } - - /** - * Creates an instance of {@link HttpMessageWriter} to be used for - * writing out HTTP responses sent over this connection. - *

- * This method can be overridden in a super class in order to provide - * a different implementation of the {@link HttpMessageWriter} interface or - * to pass a different implementation of - * {@link com.tracelytics.ext.apache.http.message.LineFormatter} to the the default - * implementation {@link HttpResponseWriter}. - * - * @param buffer the session output buffer - * @param params HTTP parameters - * @return HTTP message writer - */ - protected HttpMessageWriter createResponseWriter( - final SessionOutputBuffer buffer, - final HttpParams params) { - return new HttpResponseWriter(buffer, null, params); - } - - /** - * @since 4.1 - */ - protected HttpConnectionMetricsImpl createConnectionMetrics( - final HttpTransportMetrics inTransportMetric, - final HttpTransportMetrics outTransportMetric) { - return new HttpConnectionMetricsImpl(inTransportMetric, outTransportMetric); - } - - /** - * Initializes this connection object with {@link SessionInputBuffer} and - * {@link SessionOutputBuffer} instances to be used for sending and - * receiving data. These session buffers can be bound to any arbitrary - * physical output medium. - *

- * This method will invoke {@link #createHttpRequestFactory}, - * {@link #createRequestParser(SessionInputBuffer, HttpRequestFactory, HttpParams)} - * and {@link #createResponseWriter(SessionOutputBuffer, HttpParams)} - * methods to initialize HTTP request parser and response writer for this - * connection. - * - * @param inbuffer the session input buffer. - * @param outbuffer the session output buffer. - * @param params HTTP parameters. - */ - protected void init( - final SessionInputBuffer inbuffer, - final SessionOutputBuffer outbuffer, - final HttpParams params) { - this.inbuffer = Args.notNull(inbuffer, "Input session buffer"); - this.outbuffer = Args.notNull(outbuffer, "Output session buffer"); - if (inbuffer instanceof EofSensor) { - this.eofSensor = (EofSensor) inbuffer; - } - this.requestParser = createRequestParser( - inbuffer, - createHttpRequestFactory(), - params); - this.responseWriter = createResponseWriter( - outbuffer, params); - this.metrics = createConnectionMetrics( - inbuffer.getMetrics(), - outbuffer.getMetrics()); - } - - public HttpRequest receiveRequestHeader() - throws HttpException, IOException { - assertOpen(); - final HttpRequest request = this.requestParser.parse(); - this.metrics.incrementRequestCount(); - return request; - } - - public void receiveRequestEntity(final HttpEntityEnclosingRequest request) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - assertOpen(); - final HttpEntity entity = this.entitydeserializer.deserialize(this.inbuffer, request); - request.setEntity(entity); - } - - protected void doFlush() throws IOException { - this.outbuffer.flush(); - } - - public void flush() throws IOException { - assertOpen(); - doFlush(); - } - - public void sendResponseHeader(final HttpResponse response) - throws HttpException, IOException { - Args.notNull(response, "HTTP response"); - assertOpen(); - this.responseWriter.write(response); - if (response.getStatusLine().getStatusCode() >= 200) { - this.metrics.incrementResponseCount(); - } - } - - public void sendResponseEntity(final HttpResponse response) - throws HttpException, IOException { - if (response.getEntity() == null) { - return; - } - this.entityserializer.serialize( - this.outbuffer, - response, - response.getEntity()); - } - - protected boolean isEof() { - return this.eofSensor != null && this.eofSensor.isEof(); - } - - public boolean isStale() { - if (!isOpen()) { - return true; - } - if (isEof()) { - return true; - } - try { - this.inbuffer.isDataAvailable(1); - return isEof(); - } catch (final IOException ex) { - return true; - } - } - - public HttpConnectionMetrics getMetrics() { - return this.metrics; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/BHttpConnectionBase.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/BHttpConnectionBase.java deleted file mode 100644 index fc1095d1..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/BHttpConnectionBase.java +++ /dev/null @@ -1,404 +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 com.tracelytics.ext.apache.http.impl; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.InetAddress; -import java.net.Socket; -import java.net.SocketAddress; -import java.net.SocketException; -import java.net.SocketTimeoutException; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CharsetEncoder; -import java.util.concurrent.atomic.AtomicReference; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpConnection; -import com.tracelytics.ext.apache.http.HttpConnectionMetrics; -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpInetConnection; -import com.tracelytics.ext.apache.http.HttpMessage; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.config.MessageConstraints; -import com.tracelytics.ext.apache.http.entity.BasicHttpEntity; -import com.tracelytics.ext.apache.http.entity.ContentLengthStrategy; -import com.tracelytics.ext.apache.http.impl.entity.LaxContentLengthStrategy; -import com.tracelytics.ext.apache.http.impl.entity.StrictContentLengthStrategy; -import com.tracelytics.ext.apache.http.impl.io.ChunkedInputStream; -import com.tracelytics.ext.apache.http.impl.io.ChunkedOutputStream; -import com.tracelytics.ext.apache.http.impl.io.ContentLengthInputStream; -import com.tracelytics.ext.apache.http.impl.io.ContentLengthOutputStream; -import com.tracelytics.ext.apache.http.impl.io.EmptyInputStream; -import com.tracelytics.ext.apache.http.impl.io.HttpTransportMetricsImpl; -import com.tracelytics.ext.apache.http.impl.io.IdentityInputStream; -import com.tracelytics.ext.apache.http.impl.io.IdentityOutputStream; -import com.tracelytics.ext.apache.http.impl.io.SessionInputBufferImpl; -import com.tracelytics.ext.apache.http.impl.io.SessionOutputBufferImpl; -import com.tracelytics.ext.apache.http.io.SessionInputBuffer; -import com.tracelytics.ext.apache.http.io.SessionOutputBuffer; -import com.tracelytics.ext.apache.http.protocol.HTTP; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.Asserts; -import com.tracelytics.ext.apache.http.util.NetUtils; - -/** - * This class serves as a base for all {@link HttpConnection} implementations and provides - * functionality common to both client and server HTTP connections. - * - * @since 4.0 - */ -@NotThreadSafe -public class BHttpConnectionBase implements HttpConnection, HttpInetConnection { - - private final SessionInputBufferImpl inbuffer; - private final SessionOutputBufferImpl outbuffer; - private final MessageConstraints messageConstraints; - private final HttpConnectionMetricsImpl connMetrics; - private final ContentLengthStrategy incomingContentStrategy; - private final ContentLengthStrategy outgoingContentStrategy; - private final AtomicReference socketHolder; - - /** - * Creates new instance of BHttpConnectionBase. - * - * @param buffersize buffer size. Must be a positive number. - * @param fragmentSizeHint fragment size hint. - * @param chardecoder decoder to be used for decoding HTTP protocol elements. - * If {@code null} simple type cast will be used for byte to char conversion. - * @param charencoder encoder to be used for encoding HTTP protocol elements. - * If {@code null} simple type cast will be used for char to byte conversion. - * @param messageConstraints Message constraints. If {@code null} - * {@link MessageConstraints#DEFAULT} will be used. - * @param incomingContentStrategy incoming content length strategy. If {@code null} - * {@link LaxContentLengthStrategy#INSTANCE} will be used. - * @param outgoingContentStrategy outgoing content length strategy. If {@code null} - * {@link StrictContentLengthStrategy#INSTANCE} will be used. - */ - protected BHttpConnectionBase( - final int buffersize, - final int fragmentSizeHint, - final CharsetDecoder chardecoder, - final CharsetEncoder charencoder, - final MessageConstraints messageConstraints, - final ContentLengthStrategy incomingContentStrategy, - final ContentLengthStrategy outgoingContentStrategy) { - super(); - Args.positive(buffersize, "Buffer size"); - final HttpTransportMetricsImpl inTransportMetrics = new HttpTransportMetricsImpl(); - final HttpTransportMetricsImpl outTransportMetrics = new HttpTransportMetricsImpl(); - this.inbuffer = new SessionInputBufferImpl(inTransportMetrics, buffersize, -1, - messageConstraints != null ? messageConstraints : MessageConstraints.DEFAULT, chardecoder); - this.outbuffer = new SessionOutputBufferImpl(outTransportMetrics, buffersize, fragmentSizeHint, - charencoder); - this.messageConstraints = messageConstraints; - this.connMetrics = new HttpConnectionMetricsImpl(inTransportMetrics, outTransportMetrics); - this.incomingContentStrategy = incomingContentStrategy != null ? incomingContentStrategy : - LaxContentLengthStrategy.INSTANCE; - this.outgoingContentStrategy = outgoingContentStrategy != null ? outgoingContentStrategy : - StrictContentLengthStrategy.INSTANCE; - this.socketHolder = new AtomicReference(); - } - - protected void ensureOpen() throws IOException { - final Socket socket = this.socketHolder.get(); - Asserts.check(socket != null, "Connection is not open"); - if (!this.inbuffer.isBound()) { - this.inbuffer.bind(getSocketInputStream(socket)); - } - if (!this.outbuffer.isBound()) { - this.outbuffer.bind(getSocketOutputStream(socket)); - } - } - - protected InputStream getSocketInputStream(final Socket socket) throws IOException { - return socket.getInputStream(); - } - - protected OutputStream getSocketOutputStream(final Socket socket) throws IOException { - return socket.getOutputStream(); - } - - /** - * Binds this connection to the given {@link Socket}. This socket will be - * used by the connection to send and receive data. - *

- * After this method's execution the connection status will be reported - * as open and the {@link #isOpen()} will return {@code true}. - * - * @param socket the socket. - * @throws IOException in case of an I/O error. - */ - protected void bind(final Socket socket) throws IOException { - Args.notNull(socket, "Socket"); - this.socketHolder.set(socket); - this.inbuffer.bind(null); - this.outbuffer.bind(null); - } - - protected SessionInputBuffer getSessionInputBuffer() { - return this.inbuffer; - } - - protected SessionOutputBuffer getSessionOutputBuffer() { - return this.outbuffer; - } - - protected void doFlush() throws IOException { - this.outbuffer.flush(); - } - - @Override - public boolean isOpen() { - return this.socketHolder.get() != null; - } - - protected Socket getSocket() { - return this.socketHolder.get(); - } - - protected OutputStream createOutputStream( - final long len, - final SessionOutputBuffer outbuffer) { - if (len == ContentLengthStrategy.CHUNKED) { - return new ChunkedOutputStream(2048, outbuffer); - } else if (len == ContentLengthStrategy.IDENTITY) { - return new IdentityOutputStream(outbuffer); - } else { - return new ContentLengthOutputStream(outbuffer, len); - } - } - - protected OutputStream prepareOutput(final HttpMessage message) throws HttpException { - final long len = this.outgoingContentStrategy.determineLength(message); - return createOutputStream(len, this.outbuffer); - } - - protected InputStream createInputStream( - final long len, - final SessionInputBuffer inbuffer) { - if (len == ContentLengthStrategy.CHUNKED) { - return new ChunkedInputStream(inbuffer, this.messageConstraints); - } else if (len == ContentLengthStrategy.IDENTITY) { - return new IdentityInputStream(inbuffer); - } else if (len == 0L) { - return EmptyInputStream.INSTANCE; - } else { - return new ContentLengthInputStream(inbuffer, len); - } - } - - protected HttpEntity prepareInput(final HttpMessage message) throws HttpException { - final BasicHttpEntity entity = new BasicHttpEntity(); - - final long len = this.incomingContentStrategy.determineLength(message); - final InputStream instream = createInputStream(len, this.inbuffer); - if (len == ContentLengthStrategy.CHUNKED) { - entity.setChunked(true); - entity.setContentLength(-1); - entity.setContent(instream); - } else if (len == ContentLengthStrategy.IDENTITY) { - entity.setChunked(false); - entity.setContentLength(-1); - entity.setContent(instream); - } else { - entity.setChunked(false); - entity.setContentLength(len); - entity.setContent(instream); - } - - final Header contentTypeHeader = message.getFirstHeader(HTTP.CONTENT_TYPE); - if (contentTypeHeader != null) { - entity.setContentType(contentTypeHeader); - } - final Header contentEncodingHeader = message.getFirstHeader(HTTP.CONTENT_ENCODING); - if (contentEncodingHeader != null) { - entity.setContentEncoding(contentEncodingHeader); - } - return entity; - } - - @Override - public InetAddress getLocalAddress() { - final Socket socket = this.socketHolder.get(); - return socket != null ? socket.getLocalAddress() : null; - } - - @Override - public int getLocalPort() { - final Socket socket = this.socketHolder.get(); - return socket != null ? socket.getLocalPort() : -1; - } - - @Override - public InetAddress getRemoteAddress() { - final Socket socket = this.socketHolder.get(); - return socket != null ? socket.getInetAddress() : null; - } - - @Override - public int getRemotePort() { - final Socket socket = this.socketHolder.get(); - return socket != null ? socket.getPort() : -1; - } - - @Override - public void setSocketTimeout(final int timeout) { - final Socket socket = this.socketHolder.get(); - if (socket != null) { - try { - socket.setSoTimeout(timeout); - } catch (final SocketException ignore) { - // It is not quite clear from the Sun's documentation if there are any - // other legitimate cases for a socket exception to be thrown when setting - // SO_TIMEOUT besides the socket being already closed - } - } - } - - @Override - public int getSocketTimeout() { - final Socket socket = this.socketHolder.get(); - if (socket != null) { - try { - return socket.getSoTimeout(); - } catch (final SocketException ignore) { - return -1; - } - } else { - return -1; - } - } - - @Override - public void shutdown() throws IOException { - final Socket socket = this.socketHolder.getAndSet(null); - if (socket != null) { - // force abortive close (RST) - try { - socket.setSoLinger(true, 0); - } catch (IOException ex) { - } finally { - socket.close(); - } - } - } - - @Override - public void close() throws IOException { - final Socket socket = this.socketHolder.getAndSet(null); - if (socket != null) { - try { - this.inbuffer.clear(); - this.outbuffer.flush(); - try { - try { - socket.shutdownOutput(); - } catch (final IOException ignore) { - } - try { - socket.shutdownInput(); - } catch (final IOException ignore) { - } - } catch (final UnsupportedOperationException ignore) { - // if one isn't supported, the other one isn't either - } - } finally { - socket.close(); - } - } - } - - private int fillInputBuffer(final int timeout) throws IOException { - final Socket socket = this.socketHolder.get(); - final int oldtimeout = socket.getSoTimeout(); - try { - socket.setSoTimeout(timeout); - return this.inbuffer.fillBuffer(); - } finally { - socket.setSoTimeout(oldtimeout); - } - } - - protected boolean awaitInput(final int timeout) throws IOException { - if (this.inbuffer.hasBufferedData()) { - return true; - } - fillInputBuffer(timeout); - return this.inbuffer.hasBufferedData(); - } - - @Override - public boolean isStale() { - if (!isOpen()) { - return true; - } - try { - final int bytesRead = fillInputBuffer(1); - return bytesRead < 0; - } catch (final SocketTimeoutException ex) { - return false; - } catch (final IOException ex) { - return true; - } - } - - protected void incrementRequestCount() { - this.connMetrics.incrementRequestCount(); - } - - protected void incrementResponseCount() { - this.connMetrics.incrementResponseCount(); - } - - @Override - public HttpConnectionMetrics getMetrics() { - return this.connMetrics; - } - - @Override - public String toString() { - final Socket socket = this.socketHolder.get(); - if (socket != null) { - final StringBuilder buffer = new StringBuilder(); - final SocketAddress remoteAddress = socket.getRemoteSocketAddress(); - final SocketAddress localAddress = socket.getLocalSocketAddress(); - if (remoteAddress != null && localAddress != null) { - NetUtils.formatAddress(buffer, localAddress); - buffer.append("<->"); - NetUtils.formatAddress(buffer, remoteAddress); - } - return buffer.toString(); - } else { - return "[Not bound]"; - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/ConnSupport.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/ConnSupport.java deleted file mode 100644 index cbb33741..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/ConnSupport.java +++ /dev/null @@ -1,75 +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 com.tracelytics.ext.apache.http.impl; - -import com.tracelytics.ext.apache.http.config.ConnectionConfig; - -import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CharsetEncoder; -import java.nio.charset.CodingErrorAction; - -/** - * Connection support methods. - * - * @since 4.3 - */ -public final class ConnSupport { - - public static CharsetDecoder createDecoder(final ConnectionConfig cconfig) { - if (cconfig == null) { - return null; - } - final Charset charset = cconfig.getCharset(); - final CodingErrorAction malformed = cconfig.getMalformedInputAction(); - final CodingErrorAction unmappable = cconfig.getUnmappableInputAction(); - if (charset != null) { - return charset.newDecoder() - .onMalformedInput(malformed != null ? malformed : CodingErrorAction.REPORT) - .onUnmappableCharacter(unmappable != null ? unmappable: CodingErrorAction.REPORT); - } else { - return null; - } - } - - public static CharsetEncoder createEncoder(final ConnectionConfig cconfig) { - if (cconfig == null) { - return null; - } - final Charset charset = cconfig.getCharset(); - if (charset != null) { - final CodingErrorAction malformed = cconfig.getMalformedInputAction(); - final CodingErrorAction unmappable = cconfig.getUnmappableInputAction(); - return charset.newEncoder() - .onMalformedInput(malformed != null ? malformed : CodingErrorAction.REPORT) - .onUnmappableCharacter(unmappable != null ? unmappable: CodingErrorAction.REPORT); - } else { - return null; - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultBHttpClientConnection.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultBHttpClientConnection.java deleted file mode 100644 index 8b82c944..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultBHttpClientConnection.java +++ /dev/null @@ -1,188 +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 com.tracelytics.ext.apache.http.impl; - -import java.io.IOException; -import java.io.OutputStream; -import java.net.Socket; -import java.net.SocketTimeoutException; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CharsetEncoder; - -import com.tracelytics.ext.apache.http.HttpClientConnection; -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpEntityEnclosingRequest; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.HttpStatus; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.config.MessageConstraints; -import com.tracelytics.ext.apache.http.entity.ContentLengthStrategy; -import com.tracelytics.ext.apache.http.impl.io.DefaultHttpRequestWriterFactory; -import com.tracelytics.ext.apache.http.impl.io.DefaultHttpResponseParserFactory; -import com.tracelytics.ext.apache.http.io.HttpMessageParser; -import com.tracelytics.ext.apache.http.io.HttpMessageParserFactory; -import com.tracelytics.ext.apache.http.io.HttpMessageWriter; -import com.tracelytics.ext.apache.http.io.HttpMessageWriterFactory; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Default implementation of {@link HttpClientConnection}. - * - * @since 4.3 - */ -@NotThreadSafe -public class DefaultBHttpClientConnection extends BHttpConnectionBase - implements HttpClientConnection { - - private final HttpMessageParser responseParser; - private final HttpMessageWriter requestWriter; - - /** - * Creates new instance of DefaultBHttpClientConnection. - * - * @param buffersize buffer size. Must be a positive number. - * @param fragmentSizeHint fragment size hint. - * @param chardecoder decoder to be used for decoding HTTP protocol elements. - * If {@code null} simple type cast will be used for byte to char conversion. - * @param charencoder encoder to be used for encoding HTTP protocol elements. - * If {@code null} simple type cast will be used for char to byte conversion. - * @param constraints Message constraints. If {@code null} - * {@link MessageConstraints#DEFAULT} will be used. - * @param incomingContentStrategy incoming content length strategy. If {@code null} - * {@link com.tracelytics.ext.apache.http.impl.entity.LaxContentLengthStrategy#INSTANCE} will be used. - * @param outgoingContentStrategy outgoing content length strategy. If {@code null} - * {@link com.tracelytics.ext.apache.http.impl.entity.StrictContentLengthStrategy#INSTANCE} will be used. - * @param requestWriterFactory request writer factory. If {@code null} - * {@link DefaultHttpRequestWriterFactory#INSTANCE} will be used. - * @param responseParserFactory response parser factory. If {@code null} - * {@link DefaultHttpResponseParserFactory#INSTANCE} will be used. - */ - public DefaultBHttpClientConnection( - final int buffersize, - final int fragmentSizeHint, - final CharsetDecoder chardecoder, - final CharsetEncoder charencoder, - final MessageConstraints constraints, - final ContentLengthStrategy incomingContentStrategy, - final ContentLengthStrategy outgoingContentStrategy, - final HttpMessageWriterFactory requestWriterFactory, - final HttpMessageParserFactory responseParserFactory) { - super(buffersize, fragmentSizeHint, chardecoder, charencoder, - constraints, incomingContentStrategy, outgoingContentStrategy); - this.requestWriter = (requestWriterFactory != null ? requestWriterFactory : - DefaultHttpRequestWriterFactory.INSTANCE).create(getSessionOutputBuffer()); - this.responseParser = (responseParserFactory != null ? responseParserFactory : - DefaultHttpResponseParserFactory.INSTANCE).create(getSessionInputBuffer(), constraints); - } - - public DefaultBHttpClientConnection( - final int buffersize, - final CharsetDecoder chardecoder, - final CharsetEncoder charencoder, - final MessageConstraints constraints) { - this(buffersize, buffersize, chardecoder, charencoder, constraints, null, null, null, null); - } - - public DefaultBHttpClientConnection(final int buffersize) { - this(buffersize, buffersize, null, null, null, null, null, null, null); - } - - protected void onResponseReceived(final HttpResponse response) { - } - - protected void onRequestSubmitted(final HttpRequest request) { - } - - @Override - public void bind(final Socket socket) throws IOException { - super.bind(socket); - } - - @Override - public boolean isResponseAvailable(final int timeout) throws IOException { - ensureOpen(); - try { - return awaitInput(timeout); - } catch (final SocketTimeoutException ex) { - return false; - } - } - - @Override - public void sendRequestHeader(final HttpRequest request) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - ensureOpen(); - this.requestWriter.write(request); - onRequestSubmitted(request); - incrementRequestCount(); - } - - @Override - public void sendRequestEntity(final HttpEntityEnclosingRequest request) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - ensureOpen(); - final HttpEntity entity = request.getEntity(); - if (entity == null) { - return; - } - final OutputStream outstream = prepareOutput(request); - entity.writeTo(outstream); - outstream.close(); - } - - @Override - public HttpResponse receiveResponseHeader() throws HttpException, IOException { - ensureOpen(); - final HttpResponse response = this.responseParser.parse(); - onResponseReceived(response); - if (response.getStatusLine().getStatusCode() >= HttpStatus.SC_OK) { - incrementResponseCount(); - } - return response; - } - - @Override - public void receiveResponseEntity( - final HttpResponse response) throws HttpException, IOException { - Args.notNull(response, "HTTP response"); - ensureOpen(); - final HttpEntity entity = prepareInput(response); - response.setEntity(entity); - } - - @Override - public void flush() throws IOException { - ensureOpen(); - doFlush(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultBHttpClientConnectionFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultBHttpClientConnectionFactory.java deleted file mode 100644 index d6b88a58..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultBHttpClientConnectionFactory.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 com.tracelytics.ext.apache.http.impl; - -import com.tracelytics.ext.apache.http.HttpConnectionFactory; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.config.ConnectionConfig; -import com.tracelytics.ext.apache.http.entity.ContentLengthStrategy; -import com.tracelytics.ext.apache.http.io.HttpMessageParserFactory; -import com.tracelytics.ext.apache.http.io.HttpMessageWriterFactory; - -import java.io.IOException; -import java.net.Socket; - -/** - * Default factory for {@link com.tracelytics.ext.apache.http.HttpClientConnection}s. - * - * @since 4.3 - */ -@Immutable -public class DefaultBHttpClientConnectionFactory - implements HttpConnectionFactory { - - public static final DefaultBHttpClientConnectionFactory INSTANCE = new DefaultBHttpClientConnectionFactory(); - - private final ConnectionConfig cconfig; - private final ContentLengthStrategy incomingContentStrategy; - private final ContentLengthStrategy outgoingContentStrategy; - private final HttpMessageWriterFactory requestWriterFactory; - private final HttpMessageParserFactory responseParserFactory; - - public DefaultBHttpClientConnectionFactory( - final ConnectionConfig cconfig, - final ContentLengthStrategy incomingContentStrategy, - final ContentLengthStrategy outgoingContentStrategy, - final HttpMessageWriterFactory requestWriterFactory, - final HttpMessageParserFactory responseParserFactory) { - super(); - this.cconfig = cconfig != null ? cconfig : ConnectionConfig.DEFAULT; - this.incomingContentStrategy = incomingContentStrategy; - this.outgoingContentStrategy = outgoingContentStrategy; - this.requestWriterFactory = requestWriterFactory; - this.responseParserFactory = responseParserFactory; - } - - public DefaultBHttpClientConnectionFactory( - final ConnectionConfig cconfig, - final HttpMessageWriterFactory requestWriterFactory, - final HttpMessageParserFactory responseParserFactory) { - this(cconfig, null, null, requestWriterFactory, responseParserFactory); - } - - public DefaultBHttpClientConnectionFactory(final ConnectionConfig cconfig) { - this(cconfig, null, null, null, null); - } - - public DefaultBHttpClientConnectionFactory() { - this(null, null, null, null, null); - } - - @Override - public DefaultBHttpClientConnection createConnection(final Socket socket) throws IOException { - final DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection( - this.cconfig.getBufferSize(), - this.cconfig.getFragmentSizeHint(), - ConnSupport.createDecoder(this.cconfig), - ConnSupport.createEncoder(this.cconfig), - this.cconfig.getMessageConstraints(), - this.incomingContentStrategy, - this.outgoingContentStrategy, - this.requestWriterFactory, - this.responseParserFactory); - conn.bind(socket); - return conn; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultBHttpServerConnection.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultBHttpServerConnection.java deleted file mode 100644 index 1dd29174..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultBHttpServerConnection.java +++ /dev/null @@ -1,179 +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 com.tracelytics.ext.apache.http.impl; - -import java.io.IOException; -import java.io.OutputStream; -import java.net.Socket; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CharsetEncoder; - -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpEntityEnclosingRequest; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.HttpServerConnection; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.config.MessageConstraints; -import com.tracelytics.ext.apache.http.entity.ContentLengthStrategy; -import com.tracelytics.ext.apache.http.impl.entity.DisallowIdentityContentLengthStrategy; -import com.tracelytics.ext.apache.http.impl.io.DefaultHttpRequestParserFactory; -import com.tracelytics.ext.apache.http.impl.io.DefaultHttpResponseWriterFactory; -import com.tracelytics.ext.apache.http.io.HttpMessageParser; -import com.tracelytics.ext.apache.http.io.HttpMessageParserFactory; -import com.tracelytics.ext.apache.http.io.HttpMessageWriter; -import com.tracelytics.ext.apache.http.io.HttpMessageWriterFactory; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Default implementation of {@link HttpServerConnection}. - * - * @since 4.3 - */ -@NotThreadSafe -public class DefaultBHttpServerConnection extends BHttpConnectionBase - implements HttpServerConnection { - - private final HttpMessageParser requestParser; - private final HttpMessageWriter responseWriter; - - /** - * Creates new instance of DefaultBHttpServerConnection. - * - * @param buffersize buffer size. Must be a positive number. - * @param fragmentSizeHint fragment size hint. - * @param chardecoder decoder to be used for decoding HTTP protocol elements. - * If {@code null} simple type cast will be used for byte to char conversion. - * @param charencoder encoder to be used for encoding HTTP protocol elements. - * If {@code null} simple type cast will be used for char to byte conversion. - * @param constraints Message constraints. If {@code null} - * {@link MessageConstraints#DEFAULT} will be used. - * @param incomingContentStrategy incoming content length strategy. If {@code null} - * {@link DisallowIdentityContentLengthStrategy#INSTANCE} will be used. - * @param outgoingContentStrategy outgoing content length strategy. If {@code null} - * {@link com.tracelytics.ext.apache.http.impl.entity.StrictContentLengthStrategy#INSTANCE} will be used. - * @param requestParserFactory request parser factory. If {@code null} - * {@link DefaultHttpRequestParserFactory#INSTANCE} will be used. - * @param responseWriterFactory response writer factory. If {@code null} - * {@link DefaultHttpResponseWriterFactory#INSTANCE} will be used. - */ - public DefaultBHttpServerConnection( - final int buffersize, - final int fragmentSizeHint, - final CharsetDecoder chardecoder, - final CharsetEncoder charencoder, - final MessageConstraints constraints, - final ContentLengthStrategy incomingContentStrategy, - final ContentLengthStrategy outgoingContentStrategy, - final HttpMessageParserFactory requestParserFactory, - final HttpMessageWriterFactory responseWriterFactory) { - super(buffersize, fragmentSizeHint, chardecoder, charencoder, constraints, - incomingContentStrategy != null ? incomingContentStrategy : - DisallowIdentityContentLengthStrategy.INSTANCE, outgoingContentStrategy); - this.requestParser = (requestParserFactory != null ? requestParserFactory : - DefaultHttpRequestParserFactory.INSTANCE).create(getSessionInputBuffer(), constraints); - this.responseWriter = (responseWriterFactory != null ? responseWriterFactory : - DefaultHttpResponseWriterFactory.INSTANCE).create(getSessionOutputBuffer()); - } - - public DefaultBHttpServerConnection( - final int buffersize, - final CharsetDecoder chardecoder, - final CharsetEncoder charencoder, - final MessageConstraints constraints) { - this(buffersize, buffersize, chardecoder, charencoder, constraints, null, null, null, null); - } - - public DefaultBHttpServerConnection(final int buffersize) { - this(buffersize, buffersize, null, null, null, null, null, null, null); - } - - protected void onRequestReceived(final HttpRequest request) { - } - - protected void onResponseSubmitted(final HttpResponse response) { - } - - @Override - public void bind(final Socket socket) throws IOException { - super.bind(socket); - } - - @Override - public HttpRequest receiveRequestHeader() - throws HttpException, IOException { - ensureOpen(); - final HttpRequest request = this.requestParser.parse(); - onRequestReceived(request); - incrementRequestCount(); - return request; - } - - @Override - public void receiveRequestEntity(final HttpEntityEnclosingRequest request) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - ensureOpen(); - final HttpEntity entity = prepareInput(request); - request.setEntity(entity); - } - - @Override - public void sendResponseHeader(final HttpResponse response) - throws HttpException, IOException { - Args.notNull(response, "HTTP response"); - ensureOpen(); - this.responseWriter.write(response); - onResponseSubmitted(response); - if (response.getStatusLine().getStatusCode() >= 200) { - incrementResponseCount(); - } - } - - @Override - public void sendResponseEntity(final HttpResponse response) - throws HttpException, IOException { - Args.notNull(response, "HTTP response"); - ensureOpen(); - final HttpEntity entity = response.getEntity(); - if (entity == null) { - return; - } - final OutputStream outstream = prepareOutput(response); - entity.writeTo(outstream); - outstream.close(); - } - - @Override - public void flush() throws IOException { - ensureOpen(); - doFlush(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultBHttpServerConnectionFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultBHttpServerConnectionFactory.java deleted file mode 100644 index b98aa5aa..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultBHttpServerConnectionFactory.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 com.tracelytics.ext.apache.http.impl; - -import com.tracelytics.ext.apache.http.HttpConnectionFactory; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.config.ConnectionConfig; -import com.tracelytics.ext.apache.http.entity.ContentLengthStrategy; -import com.tracelytics.ext.apache.http.io.HttpMessageParserFactory; -import com.tracelytics.ext.apache.http.io.HttpMessageWriterFactory; - -import java.io.IOException; -import java.net.Socket; - -/** - * Default factory for {@link com.tracelytics.ext.apache.http.HttpServerConnection}s. - * - * @since 4.3 - */ -@Immutable -public class DefaultBHttpServerConnectionFactory - implements HttpConnectionFactory { - - public static final DefaultBHttpServerConnectionFactory INSTANCE = new DefaultBHttpServerConnectionFactory(); - - private final ConnectionConfig cconfig; - private final ContentLengthStrategy incomingContentStrategy; - private final ContentLengthStrategy outgoingContentStrategy; - private final HttpMessageParserFactory requestParserFactory; - private final HttpMessageWriterFactory responseWriterFactory; - - public DefaultBHttpServerConnectionFactory( - final ConnectionConfig cconfig, - final ContentLengthStrategy incomingContentStrategy, - final ContentLengthStrategy outgoingContentStrategy, - final HttpMessageParserFactory requestParserFactory, - final HttpMessageWriterFactory responseWriterFactory) { - super(); - this.cconfig = cconfig != null ? cconfig : ConnectionConfig.DEFAULT; - this.incomingContentStrategy = incomingContentStrategy; - this.outgoingContentStrategy = outgoingContentStrategy; - this.requestParserFactory = requestParserFactory; - this.responseWriterFactory = responseWriterFactory; - } - - public DefaultBHttpServerConnectionFactory( - final ConnectionConfig cconfig, - final HttpMessageParserFactory requestParserFactory, - final HttpMessageWriterFactory responseWriterFactory) { - this(cconfig, null, null, requestParserFactory, responseWriterFactory); - } - - public DefaultBHttpServerConnectionFactory(final ConnectionConfig cconfig) { - this(cconfig, null, null, null, null); - } - - public DefaultBHttpServerConnectionFactory() { - this(null, null, null, null, null); - } - - @Override - public DefaultBHttpServerConnection createConnection(final Socket socket) throws IOException { - final DefaultBHttpServerConnection conn = new DefaultBHttpServerConnection( - this.cconfig.getBufferSize(), - this.cconfig.getFragmentSizeHint(), - ConnSupport.createDecoder(this.cconfig), - ConnSupport.createEncoder(this.cconfig), - this.cconfig.getMessageConstraints(), - this.incomingContentStrategy, - this.outgoingContentStrategy, - this.requestParserFactory, - this.responseWriterFactory); - conn.bind(socket); - return conn; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultConnectionReuseStrategy.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultConnectionReuseStrategy.java deleted file mode 100644 index de459be7..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultConnectionReuseStrategy.java +++ /dev/null @@ -1,190 +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 com.tracelytics.ext.apache.http.impl; - -import com.tracelytics.ext.apache.http.ConnectionReuseStrategy; -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HeaderIterator; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.HttpStatus; -import com.tracelytics.ext.apache.http.HttpVersion; -import com.tracelytics.ext.apache.http.ParseException; -import com.tracelytics.ext.apache.http.ProtocolVersion; -import com.tracelytics.ext.apache.http.TokenIterator; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.message.BasicTokenIterator; -import com.tracelytics.ext.apache.http.protocol.HTTP; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Default implementation of a strategy deciding about connection re-use. - * The default implementation first checks some basics, for example - * whether the connection is still open or whether the end of the - * request entity can be determined without closing the connection. - * If these checks pass, the tokens in the {@code Connection} header will - * be examined. In the absence of a {@code Connection} header, the - * non-standard but commonly used {@code Proxy-Connection} header takes - * it's role. A token {@code close} indicates that the connection cannot - * be reused. If there is no such token, a token {@code keep-alive} - * indicates that the connection should be re-used. If neither token is found, - * or if there are no {@code Connection} headers, the default policy for - * the HTTP version is applied. Since {@code HTTP/1.1}, connections are - * re-used by default. Up until {@code HTTP/1.0}, connections are not - * re-used by default. - * - * @since 4.0 - */ -@Immutable -public class DefaultConnectionReuseStrategy implements ConnectionReuseStrategy { - - public static final DefaultConnectionReuseStrategy INSTANCE = new DefaultConnectionReuseStrategy(); - - public DefaultConnectionReuseStrategy() { - super(); - } - - // see interface ConnectionReuseStrategy - @Override - public boolean keepAlive(final HttpResponse response, - final HttpContext context) { - Args.notNull(response, "HTTP response"); - Args.notNull(context, "HTTP context"); - - // Check for a self-terminating entity. If the end of the entity will - // be indicated by closing the connection, there is no keep-alive. - final ProtocolVersion ver = response.getStatusLine().getProtocolVersion(); - final Header teh = response.getFirstHeader(HTTP.TRANSFER_ENCODING); - if (teh != null) { - if (!HTTP.CHUNK_CODING.equalsIgnoreCase(teh.getValue())) { - return false; - } - } else { - if (canResponseHaveBody(response)) { - final Header[] clhs = response.getHeaders(HTTP.CONTENT_LEN); - // Do not reuse if not properly content-length delimited - if (clhs.length == 1) { - final Header clh = clhs[0]; - try { - final int contentLen = Integer.parseInt(clh.getValue()); - if (contentLen < 0) { - return false; - } - } catch (final NumberFormatException ex) { - return false; - } - } else { - return false; - } - } - } - - // Check for the "Connection" header. If that is absent, check for - // the "Proxy-Connection" header. The latter is an unspecified and - // broken but unfortunately common extension of HTTP. - HeaderIterator hit = response.headerIterator(HTTP.CONN_DIRECTIVE); - if (!hit.hasNext()) { - hit = response.headerIterator("Proxy-Connection"); - } - - // Experimental usage of the "Connection" header in HTTP/1.0 is - // documented in RFC 2068, section 19.7.1. A token "keep-alive" is - // used to indicate that the connection should be persistent. - // Note that the final specification of HTTP/1.1 in RFC 2616 does not - // include this information. Neither is the "Connection" header - // mentioned in RFC 1945, which informally describes HTTP/1.0. - // - // RFC 2616 specifies "close" as the only connection token with a - // specific meaning: it disables persistent connections. - // - // The "Proxy-Connection" header is not formally specified anywhere, - // but is commonly used to carry one token, "close" or "keep-alive". - // The "Connection" header, on the other hand, is defined as a - // sequence of tokens, where each token is a header name, and the - // token "close" has the above-mentioned additional meaning. - // - // To get through this mess, we treat the "Proxy-Connection" header - // in exactly the same way as the "Connection" header, but only if - // the latter is missing. We scan the sequence of tokens for both - // "close" and "keep-alive". As "close" is specified by RFC 2068, - // it takes precedence and indicates a non-persistent connection. - // If there is no "close" but a "keep-alive", we take the hint. - - if (hit.hasNext()) { - try { - final TokenIterator ti = createTokenIterator(hit); - boolean keepalive = false; - while (ti.hasNext()) { - final String token = ti.nextToken(); - if (HTTP.CONN_CLOSE.equalsIgnoreCase(token)) { - return false; - } else if (HTTP.CONN_KEEP_ALIVE.equalsIgnoreCase(token)) { - // continue the loop, there may be a "close" afterwards - keepalive = true; - } - } - if (keepalive) - { - return true; - // neither "close" nor "keep-alive", use default policy - } - - } catch (final ParseException px) { - // invalid connection header means no persistent connection - // we don't have logging in HttpCore, so the exception is lost - return false; - } - } - - // default since HTTP/1.1 is persistent, before it was non-persistent - return !ver.lessEquals(HttpVersion.HTTP_1_0); - } - - - /** - * Creates a token iterator from a header iterator. - * This method can be overridden to replace the implementation of - * the token iterator. - * - * @param hit the header iterator - * - * @return the token iterator - */ - protected TokenIterator createTokenIterator(final HeaderIterator hit) { - return new BasicTokenIterator(hit); - } - - private boolean canResponseHaveBody(final HttpResponse response) { - final int status = response.getStatusLine().getStatusCode(); - return status >= HttpStatus.SC_OK - && status != HttpStatus.SC_NO_CONTENT - && status != HttpStatus.SC_NOT_MODIFIED - && status != HttpStatus.SC_RESET_CONTENT; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultHttpClientConnection.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultHttpClientConnection.java deleted file mode 100644 index 7a8ac71e..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultHttpClientConnection.java +++ /dev/null @@ -1,70 +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 com.tracelytics.ext.apache.http.impl; - -import java.io.IOException; -import java.net.Socket; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.params.CoreConnectionPNames; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Default implementation of a client-side HTTP connection. - * - * @since 4.0 - * - * @deprecated (4.3) use {@link DefaultBHttpClientConnection} - */ -@NotThreadSafe -@Deprecated -public class DefaultHttpClientConnection extends SocketHttpClientConnection { - - public DefaultHttpClientConnection() { - super(); - } - - @Override - public void bind( - final Socket socket, - final HttpParams params) throws IOException { - Args.notNull(socket, "Socket"); - Args.notNull(params, "HTTP parameters"); - assertNotOpen(); - socket.setTcpNoDelay(params.getBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)); - socket.setSoTimeout(params.getIntParameter(CoreConnectionPNames.SO_TIMEOUT, 0)); - socket.setKeepAlive(params.getBooleanParameter(CoreConnectionPNames.SO_KEEPALIVE, false)); - final int linger = params.getIntParameter(CoreConnectionPNames.SO_LINGER, -1); - if (linger >= 0) { - socket.setSoLinger(linger > 0, linger); - } - super.bind(socket, params); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultHttpRequestFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultHttpRequestFactory.java deleted file mode 100644 index d8a2edf4..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultHttpRequestFactory.java +++ /dev/null @@ -1,111 +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 com.tracelytics.ext.apache.http.impl; - -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpRequestFactory; -import com.tracelytics.ext.apache.http.MethodNotSupportedException; -import com.tracelytics.ext.apache.http.RequestLine; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.message.BasicHttpEntityEnclosingRequest; -import com.tracelytics.ext.apache.http.message.BasicHttpRequest; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Default factory for creating {@link HttpRequest} objects. - * - * @since 4.0 - */ -@Immutable -public class DefaultHttpRequestFactory implements HttpRequestFactory { - - public static final DefaultHttpRequestFactory INSTANCE = new DefaultHttpRequestFactory(); - - private static final String[] RFC2616_COMMON_METHODS = { - "GET" - }; - - private static final String[] RFC2616_ENTITY_ENC_METHODS = { - "POST", - "PUT" - }; - - private static final String[] RFC2616_SPECIAL_METHODS = { - "HEAD", - "OPTIONS", - "DELETE", - "TRACE", - "CONNECT" - }; - - - public DefaultHttpRequestFactory() { - super(); - } - - private static boolean isOneOf(final String[] methods, final String method) { - for (final String method2 : methods) { - if (method2.equalsIgnoreCase(method)) { - return true; - } - } - return false; - } - - @Override - public HttpRequest newHttpRequest(final RequestLine requestline) - throws MethodNotSupportedException { - Args.notNull(requestline, "Request line"); - final String method = requestline.getMethod(); - if (isOneOf(RFC2616_COMMON_METHODS, method)) { - return new BasicHttpRequest(requestline); - } else if (isOneOf(RFC2616_ENTITY_ENC_METHODS, method)) { - return new BasicHttpEntityEnclosingRequest(requestline); - } else if (isOneOf(RFC2616_SPECIAL_METHODS, method)) { - return new BasicHttpRequest(requestline); - } else { - throw new MethodNotSupportedException(method + " method not supported"); - } - } - - @Override - public HttpRequest newHttpRequest(final String method, final String uri) - throws MethodNotSupportedException { - if (isOneOf(RFC2616_COMMON_METHODS, method)) { - return new BasicHttpRequest(method, uri); - } else if (isOneOf(RFC2616_ENTITY_ENC_METHODS, method)) { - return new BasicHttpEntityEnclosingRequest(method, uri); - } else if (isOneOf(RFC2616_SPECIAL_METHODS, method)) { - return new BasicHttpRequest(method, uri); - } else { - throw new MethodNotSupportedException(method - + " method not supported"); - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultHttpResponseFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultHttpResponseFactory.java deleted file mode 100644 index deef2006..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultHttpResponseFactory.java +++ /dev/null @@ -1,111 +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 com.tracelytics.ext.apache.http.impl; - -import java.util.Locale; - -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.HttpResponseFactory; -import com.tracelytics.ext.apache.http.ProtocolVersion; -import com.tracelytics.ext.apache.http.ReasonPhraseCatalog; -import com.tracelytics.ext.apache.http.StatusLine; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.message.BasicHttpResponse; -import com.tracelytics.ext.apache.http.message.BasicStatusLine; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Default factory for creating {@link HttpResponse} objects. - * - * @since 4.0 - */ -@Immutable -public class DefaultHttpResponseFactory implements HttpResponseFactory { - - public static final DefaultHttpResponseFactory INSTANCE = new DefaultHttpResponseFactory(); - - /** The catalog for looking up reason phrases. */ - protected final ReasonPhraseCatalog reasonCatalog; - - - /** - * Creates a new response factory with the given catalog. - * - * @param catalog the catalog of reason phrases - */ - public DefaultHttpResponseFactory(final ReasonPhraseCatalog catalog) { - this.reasonCatalog = Args.notNull(catalog, "Reason phrase catalog"); - } - - /** - * Creates a new response factory with the default catalog. - * The default catalog is {@link EnglishReasonPhraseCatalog}. - */ - public DefaultHttpResponseFactory() { - this(EnglishReasonPhraseCatalog.INSTANCE); - } - - - // non-javadoc, see interface HttpResponseFactory - @Override - public HttpResponse newHttpResponse( - final ProtocolVersion ver, - final int status, - final HttpContext context) { - Args.notNull(ver, "HTTP version"); - final Locale loc = determineLocale(context); - final String reason = this.reasonCatalog.getReason(status, loc); - final StatusLine statusline = new BasicStatusLine(ver, status, reason); - return new BasicHttpResponse(statusline, this.reasonCatalog, loc); - } - - - // non-javadoc, see interface HttpResponseFactory - @Override - public HttpResponse newHttpResponse( - final StatusLine statusline, - final HttpContext context) { - Args.notNull(statusline, "Status line"); - return new BasicHttpResponse(statusline, this.reasonCatalog, determineLocale(context)); - } - - /** - * Determines the locale of the response. - * The implementation in this class always returns the default locale. - * - * @param context the context from which to determine the locale, or - * {@code null} to use the default locale - * - * @return the locale for the response, never {@code null} - */ - protected Locale determineLocale(final HttpContext context) { - return Locale.getDefault(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultHttpServerConnection.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultHttpServerConnection.java deleted file mode 100644 index 50ba14a9..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/DefaultHttpServerConnection.java +++ /dev/null @@ -1,71 +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 com.tracelytics.ext.apache.http.impl; - -import java.io.IOException; -import java.net.Socket; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.params.CoreConnectionPNames; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Default implementation of a server-side HTTP connection. - * - * @since 4.0 - * - * @deprecated (4.3) use {@link DefaultBHttpServerConnection} - */ -@NotThreadSafe -@Deprecated -public class DefaultHttpServerConnection extends SocketHttpServerConnection { - - public DefaultHttpServerConnection() { - super(); - } - - @Override - public void bind(final Socket socket, final HttpParams params) throws IOException { - Args.notNull(socket, "Socket"); - Args.notNull(params, "HTTP parameters"); - assertNotOpen(); - socket.setTcpNoDelay(params.getBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)); - socket.setSoTimeout(params.getIntParameter(CoreConnectionPNames.SO_TIMEOUT, 0)); - socket.setKeepAlive(params.getBooleanParameter(CoreConnectionPNames.SO_KEEPALIVE, false)); - final int linger = params.getIntParameter(CoreConnectionPNames.SO_LINGER, -1); - if (linger >= 0) { - socket.setSoLinger(linger > 0, linger); - } - if (linger >= 0) { - socket.setSoLinger(linger > 0, linger); - } - super.bind(socket, params); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/EnglishReasonPhraseCatalog.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/EnglishReasonPhraseCatalog.java deleted file mode 100644 index 3f2e2654..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/EnglishReasonPhraseCatalog.java +++ /dev/null @@ -1,225 +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 com.tracelytics.ext.apache.http.impl; - -import java.util.Locale; - -import com.tracelytics.ext.apache.http.HttpStatus; -import com.tracelytics.ext.apache.http.ReasonPhraseCatalog; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * English reason phrases for HTTP status codes. - * All status codes defined in RFC1945 (HTTP/1.0), RFC2616 (HTTP/1.1), and - * RFC2518 (WebDAV) are supported. - * - * @since 4.0 - */ -@Immutable -public class EnglishReasonPhraseCatalog implements ReasonPhraseCatalog { - - // static array with english reason phrases defined below - - /** - * The default instance of this catalog. - * This catalog is thread safe, so there typically - * is no need to create other instances. - */ - public final static EnglishReasonPhraseCatalog INSTANCE = - new EnglishReasonPhraseCatalog(); - - - /** - * Restricted default constructor, for derived classes. - * If you need an instance of this class, use {@link #INSTANCE INSTANCE}. - */ - protected EnglishReasonPhraseCatalog() { - // no body - } - - - /** - * Obtains the reason phrase for a status code. - * - * @param status the status code, in the range 100-599 - * @param loc ignored - * - * @return the reason phrase, or {@code null} - */ - @Override - public String getReason(final int status, final Locale loc) { - Args.check(status >= 100 && status < 600, "Unknown category for status code " + status); - final int category = status / 100; - final int subcode = status - 100*category; - - String reason = null; - if (REASON_PHRASES[category].length > subcode) { - reason = REASON_PHRASES[category][subcode]; - } - - return reason; - } - - - /** Reason phrases lookup table. */ - private static final String[][] REASON_PHRASES = new String[][]{ - null, - new String[3], // 1xx - new String[8], // 2xx - new String[8], // 3xx - new String[25], // 4xx - new String[8] // 5xx - }; - - - - /** - * Stores the given reason phrase, by status code. - * Helper method to initialize the static lookup table. - * - * @param status the status code for which to define the phrase - * @param reason the reason phrase for this status code - */ - private static void setReason(final int status, final String reason) { - final int category = status / 100; - final int subcode = status - 100*category; - REASON_PHRASES[category][subcode] = reason; - } - - - // ----------------------------------------------------- Static Initializer - - /** Set up status code to "reason phrase" map. */ - static { - // HTTP 1.0 Server status codes -- see RFC 1945 - setReason(HttpStatus.SC_OK, - "OK"); - setReason(HttpStatus.SC_CREATED, - "Created"); - setReason(HttpStatus.SC_ACCEPTED, - "Accepted"); - setReason(HttpStatus.SC_NO_CONTENT, - "No Content"); - setReason(HttpStatus.SC_MOVED_PERMANENTLY, - "Moved Permanently"); - setReason(HttpStatus.SC_MOVED_TEMPORARILY, - "Moved Temporarily"); - setReason(HttpStatus.SC_NOT_MODIFIED, - "Not Modified"); - setReason(HttpStatus.SC_BAD_REQUEST, - "Bad Request"); - setReason(HttpStatus.SC_UNAUTHORIZED, - "Unauthorized"); - setReason(HttpStatus.SC_FORBIDDEN, - "Forbidden"); - setReason(HttpStatus.SC_NOT_FOUND, - "Not Found"); - setReason(HttpStatus.SC_INTERNAL_SERVER_ERROR, - "Internal Server Error"); - setReason(HttpStatus.SC_NOT_IMPLEMENTED, - "Not Implemented"); - setReason(HttpStatus.SC_BAD_GATEWAY, - "Bad Gateway"); - setReason(HttpStatus.SC_SERVICE_UNAVAILABLE, - "Service Unavailable"); - - // HTTP 1.1 Server status codes -- see RFC 2048 - setReason(HttpStatus.SC_CONTINUE, - "Continue"); - setReason(HttpStatus.SC_TEMPORARY_REDIRECT, - "Temporary Redirect"); - setReason(HttpStatus.SC_METHOD_NOT_ALLOWED, - "Method Not Allowed"); - setReason(HttpStatus.SC_CONFLICT, - "Conflict"); - setReason(HttpStatus.SC_PRECONDITION_FAILED, - "Precondition Failed"); - setReason(HttpStatus.SC_REQUEST_TOO_LONG, - "Request Too Long"); - setReason(HttpStatus.SC_REQUEST_URI_TOO_LONG, - "Request-URI Too Long"); - setReason(HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE, - "Unsupported Media Type"); - setReason(HttpStatus.SC_MULTIPLE_CHOICES, - "Multiple Choices"); - setReason(HttpStatus.SC_SEE_OTHER, - "See Other"); - setReason(HttpStatus.SC_USE_PROXY, - "Use Proxy"); - setReason(HttpStatus.SC_PAYMENT_REQUIRED, - "Payment Required"); - setReason(HttpStatus.SC_NOT_ACCEPTABLE, - "Not Acceptable"); - setReason(HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED, - "Proxy Authentication Required"); - setReason(HttpStatus.SC_REQUEST_TIMEOUT, - "Request Timeout"); - - setReason(HttpStatus.SC_SWITCHING_PROTOCOLS, - "Switching Protocols"); - setReason(HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION, - "Non Authoritative Information"); - setReason(HttpStatus.SC_RESET_CONTENT, - "Reset Content"); - setReason(HttpStatus.SC_PARTIAL_CONTENT, - "Partial Content"); - setReason(HttpStatus.SC_GATEWAY_TIMEOUT, - "Gateway Timeout"); - setReason(HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED, - "Http Version Not Supported"); - setReason(HttpStatus.SC_GONE, - "Gone"); - setReason(HttpStatus.SC_LENGTH_REQUIRED, - "Length Required"); - setReason(HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE, - "Requested Range Not Satisfiable"); - setReason(HttpStatus.SC_EXPECTATION_FAILED, - "Expectation Failed"); - - // WebDAV Server-specific status codes - setReason(HttpStatus.SC_PROCESSING, - "Processing"); - setReason(HttpStatus.SC_MULTI_STATUS, - "Multi-Status"); - setReason(HttpStatus.SC_UNPROCESSABLE_ENTITY, - "Unprocessable Entity"); - setReason(HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE, - "Insufficient Space On Resource"); - setReason(HttpStatus.SC_METHOD_FAILURE, - "Method Failure"); - setReason(HttpStatus.SC_LOCKED, - "Locked"); - setReason(HttpStatus.SC_INSUFFICIENT_STORAGE, - "Insufficient Storage"); - setReason(HttpStatus.SC_FAILED_DEPENDENCY, - "Failed Dependency"); - } - - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/HttpConnectionMetricsImpl.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/HttpConnectionMetricsImpl.java deleted file mode 100644 index 07c7d39d..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/HttpConnectionMetricsImpl.java +++ /dev/null @@ -1,154 +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 com.tracelytics.ext.apache.http.impl; - -import java.util.HashMap; -import java.util.Map; - -import com.tracelytics.ext.apache.http.HttpConnectionMetrics; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.io.HttpTransportMetrics; - -/** - * Default implementation of the {@link HttpConnectionMetrics} interface. - * - * @since 4.0 - */ -@NotThreadSafe -public class HttpConnectionMetricsImpl implements HttpConnectionMetrics { - - public static final String REQUEST_COUNT = "http.request-count"; - public static final String RESPONSE_COUNT = "http.response-count"; - public static final String SENT_BYTES_COUNT = "http.sent-bytes-count"; - public static final String RECEIVED_BYTES_COUNT = "http.received-bytes-count"; - - private final HttpTransportMetrics inTransportMetric; - private final HttpTransportMetrics outTransportMetric; - private long requestCount = 0; - private long responseCount = 0; - - /** - * The cache map for all metrics values. - */ - private Map metricsCache; - - public HttpConnectionMetricsImpl( - final HttpTransportMetrics inTransportMetric, - final HttpTransportMetrics outTransportMetric) { - super(); - this.inTransportMetric = inTransportMetric; - this.outTransportMetric = outTransportMetric; - } - - /* ------------------ Public interface method -------------------------- */ - - @Override - public long getReceivedBytesCount() { - if (this.inTransportMetric != null) { - return this.inTransportMetric.getBytesTransferred(); - } else { - return -1; - } - } - - @Override - public long getSentBytesCount() { - if (this.outTransportMetric != null) { - return this.outTransportMetric.getBytesTransferred(); - } else { - return -1; - } - } - - @Override - public long getRequestCount() { - return this.requestCount; - } - - public void incrementRequestCount() { - this.requestCount++; - } - - @Override - public long getResponseCount() { - return this.responseCount; - } - - public void incrementResponseCount() { - this.responseCount++; - } - - @Override - public Object getMetric(final String metricName) { - Object value = null; - if (this.metricsCache != null) { - value = this.metricsCache.get(metricName); - } - if (value == null) { - if (REQUEST_COUNT.equals(metricName)) { - value = Long.valueOf(requestCount); - } else if (RESPONSE_COUNT.equals(metricName)) { - value = Long.valueOf(responseCount); - } else if (RECEIVED_BYTES_COUNT.equals(metricName)) { - if (this.inTransportMetric != null) { - return Long.valueOf(this.inTransportMetric.getBytesTransferred()); - } else { - return null; - } - } else if (SENT_BYTES_COUNT.equals(metricName)) { - if (this.outTransportMetric != null) { - return Long.valueOf(this.outTransportMetric.getBytesTransferred()); - } else { - return null; - } - } - } - return value; - } - - public void setMetric(final String metricName, final Object obj) { - if (this.metricsCache == null) { - this.metricsCache = new HashMap(); - } - this.metricsCache.put(metricName, obj); - } - - @Override - public void reset() { - if (this.outTransportMetric != null) { - this.outTransportMetric.reset(); - } - if (this.inTransportMetric != null) { - this.inTransportMetric.reset(); - } - this.requestCount = 0; - this.responseCount = 0; - this.metricsCache = null; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/NoConnectionReuseStrategy.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/NoConnectionReuseStrategy.java deleted file mode 100644 index e288734f..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/NoConnectionReuseStrategy.java +++ /dev/null @@ -1,54 +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 com.tracelytics.ext.apache.http.impl; - -import com.tracelytics.ext.apache.http.ConnectionReuseStrategy; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -/** - * A strategy that never re-uses a connection. - * - * @since 4.0 - */ -@Immutable -public class NoConnectionReuseStrategy implements ConnectionReuseStrategy { - - public static final NoConnectionReuseStrategy INSTANCE = new NoConnectionReuseStrategy(); - - public NoConnectionReuseStrategy() { - super(); - } - - @Override - public boolean keepAlive(final HttpResponse response, final HttpContext context) { - return false; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/SocketHttpClientConnection.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/SocketHttpClientConnection.java deleted file mode 100644 index 8a11bbb3..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/SocketHttpClientConnection.java +++ /dev/null @@ -1,284 +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 com.tracelytics.ext.apache.http.impl; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.net.SocketAddress; -import java.net.SocketException; - -import com.tracelytics.ext.apache.http.HttpInetConnection; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.io.SessionInputBuffer; -import com.tracelytics.ext.apache.http.io.SessionOutputBuffer; -import com.tracelytics.ext.apache.http.params.CoreConnectionPNames; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.Asserts; - -import com.tracelytics.ext.apache.http.impl.io.SocketInputBuffer; -import com.tracelytics.ext.apache.http.impl.io.SocketOutputBuffer; - -/** - * Implementation of a client-side HTTP connection that can be bound to an - * arbitrary {@link Socket} for receiving data from and transmitting data to - * a remote server. - * - * @since 4.0 - * - * @deprecated (4.3) use {@link DefaultBHttpClientConnection} - */ -@NotThreadSafe -@Deprecated -public class SocketHttpClientConnection - extends AbstractHttpClientConnection implements HttpInetConnection { - - private volatile boolean open; - private volatile Socket socket = null; - - public SocketHttpClientConnection() { - super(); - } - - protected void assertNotOpen() { - Asserts.check(!this.open, "Connection is already open"); - } - - @Override - protected void assertOpen() { - Asserts.check(this.open, "Connection is not open"); - } - - /** - * Creates an instance of {@link SocketInputBuffer} to be used for - * receiving data from the given {@link Socket}. - *

- * This method can be overridden in a super class in order to provide - * a custom implementation of {@link SessionInputBuffer} interface. - * - * @see SocketInputBuffer#SocketInputBuffer(Socket, int, HttpParams) - * - * @param socket the socket. - * @param buffersize the buffer size. - * @param params HTTP parameters. - * @return session input buffer. - * @throws IOException in case of an I/O error. - */ - protected SessionInputBuffer createSessionInputBuffer( - final Socket socket, - final int buffersize, - final HttpParams params) throws IOException { - return new SocketInputBuffer(socket, buffersize, params); - } - - /** - * Creates an instance of {@link SessionOutputBuffer} to be used for - * sending data to the given {@link Socket}. - *

- * This method can be overridden in a super class in order to provide - * a custom implementation of {@link SocketOutputBuffer} interface. - * - * @see SocketOutputBuffer#SocketOutputBuffer(Socket, int, HttpParams) - * - * @param socket the socket. - * @param buffersize the buffer size. - * @param params HTTP parameters. - * @return session output buffer. - * @throws IOException in case of an I/O error. - */ - protected SessionOutputBuffer createSessionOutputBuffer( - final Socket socket, - final int buffersize, - final HttpParams params) throws IOException { - return new SocketOutputBuffer(socket, buffersize, params); - } - - /** - * Binds this connection to the given {@link Socket}. This socket will be - * used by the connection to send and receive data. - *

- * This method will invoke {@link #createSessionInputBuffer(Socket, int, HttpParams)} - * and {@link #createSessionOutputBuffer(Socket, int, HttpParams)} methods - * to create session input / output buffers bound to this socket and then - * will invoke {@link #init(SessionInputBuffer, SessionOutputBuffer, HttpParams)} - * method to pass references to those buffers to the underlying HTTP message - * parser and formatter. - *

- * After this method's execution the connection status will be reported - * as open and the {@link #isOpen()} will return {@code true}. - * - * @param socket the socket. - * @param params HTTP parameters. - * @throws IOException in case of an I/O error. - */ - protected void bind( - final Socket socket, - final HttpParams params) throws IOException { - Args.notNull(socket, "Socket"); - Args.notNull(params, "HTTP parameters"); - this.socket = socket; - - final int buffersize = params.getIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, -1); - init( - createSessionInputBuffer(socket, buffersize, params), - createSessionOutputBuffer(socket, buffersize, params), - params); - - this.open = true; - } - - public boolean isOpen() { - return this.open; - } - - protected Socket getSocket() { - return this.socket; - } - - public InetAddress getLocalAddress() { - if (this.socket != null) { - return this.socket.getLocalAddress(); - } else { - return null; - } - } - - public int getLocalPort() { - if (this.socket != null) { - return this.socket.getLocalPort(); - } else { - return -1; - } - } - - public InetAddress getRemoteAddress() { - if (this.socket != null) { - return this.socket.getInetAddress(); - } else { - return null; - } - } - - public int getRemotePort() { - if (this.socket != null) { - return this.socket.getPort(); - } else { - return -1; - } - } - - public void setSocketTimeout(final int timeout) { - assertOpen(); - if (this.socket != null) { - try { - this.socket.setSoTimeout(timeout); - } catch (final SocketException ignore) { - // It is not quite clear from the Sun's documentation if there are any - // other legitimate cases for a socket exception to be thrown when setting - // SO_TIMEOUT besides the socket being already closed - } - } - } - - public int getSocketTimeout() { - if (this.socket != null) { - try { - return this.socket.getSoTimeout(); - } catch (final SocketException ignore) { - return -1; - } - } else { - return -1; - } - } - - public void shutdown() throws IOException { - this.open = false; - final Socket tmpsocket = this.socket; - if (tmpsocket != null) { - tmpsocket.close(); - } - } - - public void close() throws IOException { - if (!this.open) { - return; - } - this.open = false; - final Socket sock = this.socket; - try { - doFlush(); - try { - try { - sock.shutdownOutput(); - } catch (final IOException ignore) { - } - try { - sock.shutdownInput(); - } catch (final IOException ignore) { - } - } catch (final UnsupportedOperationException ignore) { - // if one isn't supported, the other one isn't either - } - } finally { - sock.close(); - } - } - - private static void formatAddress(final StringBuilder buffer, final SocketAddress socketAddress) { - if (socketAddress instanceof InetSocketAddress) { - final InetSocketAddress addr = ((InetSocketAddress) socketAddress); - buffer.append(addr.getAddress() != null ? addr.getAddress().getHostAddress() : - addr.getAddress()) - .append(':') - .append(addr.getPort()); - } else { - buffer.append(socketAddress); - } - } - - @Override - public String toString() { - if (this.socket != null) { - final StringBuilder buffer = new StringBuilder(); - final SocketAddress remoteAddress = this.socket.getRemoteSocketAddress(); - final SocketAddress localAddress = this.socket.getLocalSocketAddress(); - if (remoteAddress != null && localAddress != null) { - formatAddress(buffer, localAddress); - buffer.append("<->"); - formatAddress(buffer, remoteAddress); - } - return buffer.toString(); - } else { - return super.toString(); - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/SocketHttpServerConnection.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/SocketHttpServerConnection.java deleted file mode 100644 index 377e4cb9..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/SocketHttpServerConnection.java +++ /dev/null @@ -1,272 +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 com.tracelytics.ext.apache.http.impl; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.net.SocketAddress; -import java.net.SocketException; - -import com.tracelytics.ext.apache.http.HttpInetConnection; -import com.tracelytics.ext.apache.http.io.SessionInputBuffer; -import com.tracelytics.ext.apache.http.io.SessionOutputBuffer; -import com.tracelytics.ext.apache.http.params.CoreConnectionPNames; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.Asserts; - -import com.tracelytics.ext.apache.http.impl.io.SocketInputBuffer; -import com.tracelytics.ext.apache.http.impl.io.SocketOutputBuffer; - -@Deprecated -public class SocketHttpServerConnection extends - AbstractHttpServerConnection implements HttpInetConnection { - - private volatile boolean open; - private volatile Socket socket = null; - - public SocketHttpServerConnection() { - super(); - } - - protected void assertNotOpen() { - Asserts.check(!this.open, "Connection is already open"); - } - - @Override - protected void assertOpen() { - Asserts.check(this.open, "Connection is not open"); - } - - /** - * Creates an instance of {@link SocketInputBuffer} to be used for - * receiving data from the given {@link Socket}. - *

- * This method can be overridden in a super class in order to provide - * a custom implementation of {@link SessionInputBuffer} interface. - * - * @see SocketInputBuffer#SocketInputBuffer(Socket, int, HttpParams) - * - * @param socket the socket. - * @param buffersize the buffer size. - * @param params HTTP parameters. - * @return session input buffer. - * @throws IOException in case of an I/O error. - */ - protected SessionInputBuffer createSessionInputBuffer( - final Socket socket, - final int buffersize, - final HttpParams params) throws IOException { - return new SocketInputBuffer(socket, buffersize, params); - } - - /** - * Creates an instance of {@link SessionOutputBuffer} to be used for - * sending data to the given {@link Socket}. - *

- * This method can be overridden in a super class in order to provide - * a custom implementation of {@link SocketOutputBuffer} interface. - * - * @see SocketOutputBuffer#SocketOutputBuffer(Socket, int, HttpParams) - * - * @param socket the socket. - * @param buffersize the buffer size. - * @param params HTTP parameters. - * @return session output buffer. - * @throws IOException in case of an I/O error. - */ - protected SessionOutputBuffer createSessionOutputBuffer( - final Socket socket, - final int buffersize, - final HttpParams params) throws IOException { - return new SocketOutputBuffer(socket, buffersize, params); - } - - /** - * Binds this connection to the given {@link Socket}. This socket will be - * used by the connection to send and receive data. - *

- * This method will invoke {@link #createSessionInputBuffer(Socket, int, HttpParams)} - * and {@link #createSessionOutputBuffer(Socket, int, HttpParams)} methods - * to create session input / output buffers bound to this socket and then - * will invoke {@link #init(SessionInputBuffer, SessionOutputBuffer, HttpParams)} - * method to pass references to those buffers to the underlying HTTP message - * parser and formatter. - *

- * After this method's execution the connection status will be reported - * as open and the {@link #isOpen()} will return {@code true}. - * - * @param socket the socket. - * @param params HTTP parameters. - * @throws IOException in case of an I/O error. - */ - protected void bind(final Socket socket, final HttpParams params) throws IOException { - Args.notNull(socket, "Socket"); - Args.notNull(params, "HTTP parameters"); - this.socket = socket; - - final int buffersize = params.getIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, -1); - init( - createSessionInputBuffer(socket, buffersize, params), - createSessionOutputBuffer(socket, buffersize, params), - params); - - this.open = true; - } - - protected Socket getSocket() { - return this.socket; - } - - public boolean isOpen() { - return this.open; - } - - public InetAddress getLocalAddress() { - if (this.socket != null) { - return this.socket.getLocalAddress(); - } else { - return null; - } - } - - public int getLocalPort() { - if (this.socket != null) { - return this.socket.getLocalPort(); - } else { - return -1; - } - } - - public InetAddress getRemoteAddress() { - if (this.socket != null) { - return this.socket.getInetAddress(); - } else { - return null; - } - } - - public int getRemotePort() { - if (this.socket != null) { - return this.socket.getPort(); - } else { - return -1; - } - } - - public void setSocketTimeout(final int timeout) { - assertOpen(); - if (this.socket != null) { - try { - this.socket.setSoTimeout(timeout); - } catch (final SocketException ignore) { - // It is not quite clear from the Sun's documentation if there are any - // other legitimate cases for a socket exception to be thrown when setting - // SO_TIMEOUT besides the socket being already closed - } - } - } - - public int getSocketTimeout() { - if (this.socket != null) { - try { - return this.socket.getSoTimeout(); - } catch (final SocketException ignore) { - return -1; - } - } else { - return -1; - } - } - - public void shutdown() throws IOException { - this.open = false; - final Socket tmpsocket = this.socket; - if (tmpsocket != null) { - tmpsocket.close(); - } - } - - public void close() throws IOException { - if (!this.open) { - return; - } - this.open = false; - this.open = false; - final Socket sock = this.socket; - try { - doFlush(); - try { - try { - sock.shutdownOutput(); - } catch (final IOException ignore) { - } - try { - sock.shutdownInput(); - } catch (final IOException ignore) { - } - } catch (final UnsupportedOperationException ignore) { - // if one isn't supported, the other one isn't either - } - } finally { - sock.close(); - } - } - - private static void formatAddress(final StringBuilder buffer, final SocketAddress socketAddress) { - if (socketAddress instanceof InetSocketAddress) { - final InetSocketAddress addr = ((InetSocketAddress) socketAddress); - buffer.append(addr.getAddress() != null ? addr.getAddress().getHostAddress() : - addr.getAddress()) - .append(':') - .append(addr.getPort()); - } else { - buffer.append(socketAddress); - } - } - - @Override - public String toString() { - if (this.socket != null) { - final StringBuilder buffer = new StringBuilder(); - final SocketAddress remoteAddress = this.socket.getRemoteSocketAddress(); - final SocketAddress localAddress = this.socket.getLocalSocketAddress(); - if (remoteAddress != null && localAddress != null) { - formatAddress(buffer, localAddress); - buffer.append("<->"); - formatAddress(buffer, remoteAddress); - } - return buffer.toString(); - } else { - return super.toString(); - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/AuthSchemeBase.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/AuthSchemeBase.java deleted file mode 100644 index b08bffae..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/AuthSchemeBase.java +++ /dev/null @@ -1,172 +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 com.tracelytics.ext.apache.http.impl.auth; - -import java.util.Locale; - -import com.tracelytics.ext.apache.http.FormattedHeader; -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.protocol.HTTP; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -import com.tracelytics.ext.apache.http.auth.AUTH; -import com.tracelytics.ext.apache.http.auth.AuthenticationException; -import com.tracelytics.ext.apache.http.auth.ChallengeState; -import com.tracelytics.ext.apache.http.auth.ContextAwareAuthScheme; -import com.tracelytics.ext.apache.http.auth.Credentials; -import com.tracelytics.ext.apache.http.auth.MalformedChallengeException; - -/** - * Abstract authentication scheme class that serves as a basis - * for all authentication schemes supported by HttpClient. This class - * defines the generic way of parsing an authentication challenge. It - * does not make any assumptions regarding the format of the challenge - * nor does it impose any specific way of responding to that challenge. - * - * - * @since 4.0 - */ -@NotThreadSafe -public abstract class AuthSchemeBase implements ContextAwareAuthScheme { - - private ChallengeState challengeState; - - /** - * Creates an instance of {@code AuthSchemeBase} with the given challenge - * state. - * - * @since 4.2 - * - * @deprecated (4.3) do not use. - */ - @Deprecated - public AuthSchemeBase(final ChallengeState challengeState) { - super(); - this.challengeState = challengeState; - } - - public AuthSchemeBase() { - super(); - } - - /** - * Processes the given challenge token. Some authentication schemes - * may involve multiple challenge-response exchanges. Such schemes must be able - * to maintain the state information when dealing with sequential challenges - * - * @param header the challenge header - * - * @throws MalformedChallengeException is thrown if the authentication challenge - * is malformed - */ - @Override - public void processChallenge(final Header header) throws MalformedChallengeException { - Args.notNull(header, "Header"); - final String authheader = header.getName(); - if (authheader.equalsIgnoreCase(AUTH.WWW_AUTH)) { - this.challengeState = ChallengeState.TARGET; - } else if (authheader.equalsIgnoreCase(AUTH.PROXY_AUTH)) { - this.challengeState = ChallengeState.PROXY; - } else { - throw new MalformedChallengeException("Unexpected header name: " + authheader); - } - - final CharArrayBuffer buffer; - int pos; - if (header instanceof FormattedHeader) { - buffer = ((FormattedHeader) header).getBuffer(); - pos = ((FormattedHeader) header).getValuePos(); - } else { - final String s = header.getValue(); - if (s == null) { - throw new MalformedChallengeException("Header value is null"); - } - buffer = new CharArrayBuffer(s.length()); - buffer.append(s); - pos = 0; - } - while (pos < buffer.length() && HTTP.isWhitespace(buffer.charAt(pos))) { - pos++; - } - final int beginIndex = pos; - while (pos < buffer.length() && !HTTP.isWhitespace(buffer.charAt(pos))) { - pos++; - } - final int endIndex = pos; - final String s = buffer.substring(beginIndex, endIndex); - if (!s.equalsIgnoreCase(getSchemeName())) { - throw new MalformedChallengeException("Invalid scheme identifier: " + s); - } - - parseChallenge(buffer, pos, buffer.length()); - } - - - @Override - @SuppressWarnings("deprecation") - public Header authenticate( - final Credentials credentials, - final HttpRequest request, - final HttpContext context) throws AuthenticationException { - return authenticate(credentials, request); - } - - protected abstract void parseChallenge( - CharArrayBuffer buffer, int beginIndex, int endIndex) throws MalformedChallengeException; - - /** - * Returns {@code true} if authenticating against a proxy, {@code false} - * otherwise. - */ - public boolean isProxy() { - return this.challengeState != null && this.challengeState == ChallengeState.PROXY; - } - - /** - * Returns {@link ChallengeState} value or {@code null} if unchallenged. - * - * @since 4.2 - */ - public ChallengeState getChallengeState() { - return this.challengeState; - } - - @Override - public String toString() { - final String name = getSchemeName(); - if (name != null) { - return name.toUpperCase(Locale.ROOT); - } else { - return super.toString(); - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/BasicScheme.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/BasicScheme.java deleted file mode 100644 index c063d365..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/BasicScheme.java +++ /dev/null @@ -1,227 +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 com.tracelytics.ext.apache.http.impl.auth; - -import java.nio.charset.Charset; - -import com.tracelytics.ext.apache.http.Consts; -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.auth.AUTH; -import com.tracelytics.ext.apache.http.auth.AuthenticationException; -import com.tracelytics.ext.apache.http.auth.ChallengeState; -import com.tracelytics.ext.apache.http.auth.Credentials; -import com.tracelytics.ext.apache.http.auth.MalformedChallengeException; -import com.tracelytics.ext.apache.http.message.BufferedHeader; -import com.tracelytics.ext.apache.http.protocol.BasicHttpContext; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; -import com.tracelytics.ext.apache.http.util.EncodingUtils; -import com.tracelytics.ext.base64.Base64; - -/** - * Basic authentication scheme as defined in RFC 2617. - * - * @since 4.0 - */ -@NotThreadSafe -public class BasicScheme extends RFC2617Scheme { - - private static final long serialVersionUID = -1931571557597830536L; - - /** Whether the basic authentication process is complete */ - private boolean complete; - - /** - * @since 4.3 - */ - public BasicScheme(final Charset credentialsCharset) { - super(credentialsCharset); - this.complete = false; - } - - /** - * Creates an instance of {@code BasicScheme} with the given challenge - * state. - * - * @since 4.2 - * - * @deprecated (4.3) do not use. - */ - @Deprecated - public BasicScheme(final ChallengeState challengeState) { - super(challengeState); - } - - public BasicScheme() { - this(Consts.ASCII); - } - - /** - * Returns textual designation of the basic authentication scheme. - * - * @return {@code basic} - */ - @Override - public String getSchemeName() { - return "basic"; - } - - /** - * Processes the Basic challenge. - * - * @param header the challenge header - * - * @throws MalformedChallengeException is thrown if the authentication challenge - * is malformed - */ - @Override - public void processChallenge( - final Header header) throws MalformedChallengeException { - super.processChallenge(header); - this.complete = true; - } - - /** - * Tests if the Basic authentication process has been completed. - * - * @return {@code true} if Basic authorization has been processed, - * {@code false} otherwise. - */ - @Override - public boolean isComplete() { - return this.complete; - } - - /** - * Returns {@code false}. Basic authentication scheme is request based. - * - * @return {@code false}. - */ - @Override - public boolean isConnectionBased() { - return false; - } - - /** - * @deprecated (4.2) Use {@link com.tracelytics.ext.apache.http.auth.ContextAwareAuthScheme#authenticate( - * Credentials, HttpRequest, com.tracelytics.ext.apache.http.protocol.HttpContext)} - */ - @Override - @Deprecated - public Header authenticate( - final Credentials credentials, final HttpRequest request) throws AuthenticationException { - return authenticate(credentials, request, new BasicHttpContext()); - } - - /** - * Produces basic authorization header for the given set of {@link Credentials}. - * - * @param credentials The set of credentials to be used for authentication - * @param request The request being authenticated - * @throws com.tracelytics.ext.apache.http.auth.InvalidCredentialsException if authentication - * credentials are not valid or not applicable for this authentication scheme - * @throws AuthenticationException if authorization string cannot - * be generated due to an authentication failure - * - * @return a basic authorization string - */ - @Override - public Header authenticate( - final Credentials credentials, - final HttpRequest request, - final HttpContext context) throws AuthenticationException { - - Args.notNull(credentials, "Credentials"); - Args.notNull(request, "HTTP request"); - final StringBuilder tmp = new StringBuilder(); - tmp.append(credentials.getUserPrincipal().getName()); - tmp.append(":"); - tmp.append((credentials.getPassword() == null) ? "null" : credentials.getPassword()); - - final byte[] base64password = Base64.encodeBytesToBytes(EncodingUtils.getBytes(tmp.toString(), getCredentialsCharset(request))); - - final CharArrayBuffer buffer = new CharArrayBuffer(32); - if (isProxy()) { - buffer.append(AUTH.PROXY_AUTH_RESP); - } else { - buffer.append(AUTH.WWW_AUTH_RESP); - } - buffer.append(": Basic "); - buffer.append(base64password, 0, base64password.length); - - return new BufferedHeader(buffer); - } - - /** - * Returns a basic {@code Authorization} header value for the given - * {@link Credentials} and charset. - * - * @param credentials The credentials to encode. - * @param charset The charset to use for encoding the credentials - * - * @return a basic authorization header - * - * @deprecated (4.3) use {@link #authenticate(Credentials, HttpRequest, HttpContext)}. - */ - @Deprecated - public static Header authenticate( - final Credentials credentials, - final String charset, - final boolean proxy) { - Args.notNull(credentials, "Credentials"); - Args.notNull(charset, "charset"); - - final StringBuilder tmp = new StringBuilder(); - tmp.append(credentials.getUserPrincipal().getName()); - tmp.append(":"); - tmp.append((credentials.getPassword() == null) ? "null" : credentials.getPassword()); - - final byte[] base64password = Base64.encodeBytesToBytes(EncodingUtils.getBytes(tmp.toString(), charset)); - - final CharArrayBuffer buffer = new CharArrayBuffer(32); - if (proxy) { - buffer.append(AUTH.PROXY_AUTH_RESP); - } else { - buffer.append(AUTH.WWW_AUTH_RESP); - } - buffer.append(": Basic "); - buffer.append(base64password, 0, base64password.length); - - return new BufferedHeader(buffer); - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("BASIC [complete=").append(complete) - .append("]"); - return builder.toString(); - } -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/BasicSchemeFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/BasicSchemeFactory.java deleted file mode 100644 index ab8b2030..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/BasicSchemeFactory.java +++ /dev/null @@ -1,74 +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 com.tracelytics.ext.apache.http.impl.auth; - -import java.nio.charset.Charset; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -import com.tracelytics.ext.apache.http.auth.AuthScheme; -import com.tracelytics.ext.apache.http.auth.AuthSchemeFactory; -import com.tracelytics.ext.apache.http.auth.AuthSchemeProvider; - -/** - * {@link AuthSchemeProvider} implementation that creates and initializes - * {@link BasicScheme} instances. - * - * @since 4.0 - */ -@Immutable -@SuppressWarnings("deprecation") -public class BasicSchemeFactory implements AuthSchemeFactory, AuthSchemeProvider { - - private final Charset charset; - - /** - * @since 4.3 - */ - public BasicSchemeFactory(final Charset charset) { - super(); - this.charset = charset; - } - - public BasicSchemeFactory() { - this(null); - } - - @Override - public AuthScheme newInstance(final HttpParams params) { - return new BasicScheme(); - } - - @Override - public AuthScheme create(final HttpContext context) { - return new BasicScheme(this.charset); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/DigestScheme.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/DigestScheme.java deleted file mode 100644 index cb7a8414..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/DigestScheme.java +++ /dev/null @@ -1,500 +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 com.tracelytics.ext.apache.http.impl.auth; - -import java.io.IOException; -import java.nio.charset.Charset; -import java.security.MessageDigest; -import java.security.SecureRandom; -import java.util.ArrayList; -import java.util.Formatter; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Set; -import java.util.StringTokenizer; - -import com.tracelytics.ext.apache.http.Consts; -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpEntityEnclosingRequest; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.message.BasicHeaderValueFormatter; -import com.tracelytics.ext.apache.http.message.BasicNameValuePair; -import com.tracelytics.ext.apache.http.message.BufferedHeader; -import com.tracelytics.ext.apache.http.protocol.BasicHttpContext; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; -import com.tracelytics.ext.apache.http.util.EncodingUtils; - -import com.tracelytics.ext.apache.http.auth.AUTH; -import com.tracelytics.ext.apache.http.auth.AuthenticationException; -import com.tracelytics.ext.apache.http.auth.ChallengeState; -import com.tracelytics.ext.apache.http.auth.Credentials; -import com.tracelytics.ext.apache.http.auth.MalformedChallengeException; - -/** - * Digest authentication scheme as defined in RFC 2617. - * Both MD5 (default) and MD5-sess are supported. - * Currently only qop=auth or no qop is supported. qop=auth-int - * is unsupported. If auth and auth-int are provided, auth is - * used. - *

- * Since the digest username is included as clear text in the generated - * Authentication header, the charset of the username must be compatible - * with the HTTP element charset used by the connection. - *

- * - * @since 4.0 - */ -@NotThreadSafe -public class DigestScheme extends RFC2617Scheme { - - private static final long serialVersionUID = 3883908186234566916L; - - /** - * Hexa values used when creating 32 character long digest in HTTP DigestScheme - * in case of authentication. - * - * @see #encode(byte[]) - */ - private static final char[] HEXADECIMAL = { - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', - 'e', 'f' - }; - - /** Whether the digest authentication process is complete */ - private boolean complete; - - private static final int QOP_UNKNOWN = -1; - private static final int QOP_MISSING = 0; - private static final int QOP_AUTH_INT = 1; - private static final int QOP_AUTH = 2; - - private String lastNonce; - private long nounceCount; - private String cnonce; - private String a1; - private String a2; - - /** - * @since 4.3 - */ - public DigestScheme(final Charset credentialsCharset) { - super(credentialsCharset); - this.complete = false; - } - - /** - * Creates an instance of {@code DigestScheme} with the given challenge - * state. - * - * @since 4.2 - * - * @deprecated (4.3) do not use. - */ - @Deprecated - public DigestScheme(final ChallengeState challengeState) { - super(challengeState); - } - - public DigestScheme() { - this(Consts.ASCII); - } - - /** - * Processes the Digest challenge. - * - * @param header the challenge header - * - * @throws MalformedChallengeException is thrown if the authentication challenge - * is malformed - */ - @Override - public void processChallenge( - final Header header) throws MalformedChallengeException { - super.processChallenge(header); - this.complete = true; - if (getParameters().isEmpty()) { - throw new MalformedChallengeException("Authentication challenge is empty"); - } - } - - /** - * Tests if the Digest authentication process has been completed. - * - * @return {@code true} if Digest authorization has been processed, - * {@code false} otherwise. - */ - @Override - public boolean isComplete() { - final String s = getParameter("stale"); - if ("true".equalsIgnoreCase(s)) { - return false; - } else { - return this.complete; - } - } - - /** - * Returns textual designation of the digest authentication scheme. - * - * @return {@code digest} - */ - @Override - public String getSchemeName() { - return "digest"; - } - - /** - * Returns {@code false}. Digest authentication scheme is request based. - * - * @return {@code false}. - */ - @Override - public boolean isConnectionBased() { - return false; - } - - public void overrideParamter(final String name, final String value) { - getParameters().put(name, value); - } - - /** - * @deprecated (4.2) Use {@link com.tracelytics.ext.apache.http.auth.ContextAwareAuthScheme#authenticate( - * Credentials, HttpRequest, com.tracelytics.ext.apache.http.protocol.HttpContext)} - */ - @Override - @Deprecated - public Header authenticate( - final Credentials credentials, final HttpRequest request) throws AuthenticationException { - return authenticate(credentials, request, new BasicHttpContext()); - } - - /** - * Produces a digest authorization string for the given set of - * {@link Credentials}, method name and URI. - * - * @param credentials A set of credentials to be used for athentication - * @param request The request being authenticated - * - * @throws com.tracelytics.ext.apache.http.auth.InvalidCredentialsException if authentication credentials - * are not valid or not applicable for this authentication scheme - * @throws AuthenticationException if authorization string cannot - * be generated due to an authentication failure - * - * @return a digest authorization string - */ - @Override - public Header authenticate( - final Credentials credentials, - final HttpRequest request, - final HttpContext context) throws AuthenticationException { - - Args.notNull(credentials, "Credentials"); - Args.notNull(request, "HTTP request"); - if (getParameter("realm") == null) { - throw new AuthenticationException("missing realm in challenge"); - } - if (getParameter("nonce") == null) { - throw new AuthenticationException("missing nonce in challenge"); - } - // Add method name and request-URI to the parameter map - getParameters().put("methodname", request.getRequestLine().getMethod()); - getParameters().put("uri", request.getRequestLine().getUri()); - final String charset = getParameter("charset"); - if (charset == null) { - getParameters().put("charset", getCredentialsCharset(request)); - } - return createDigestHeader(credentials, request); - } - - private static MessageDigest createMessageDigest( - final String digAlg) throws UnsupportedDigestAlgorithmException { - try { - return MessageDigest.getInstance(digAlg); - } catch (final Exception e) { - throw new UnsupportedDigestAlgorithmException( - "Unsupported algorithm in HTTP Digest authentication: " - + digAlg); - } - } - - /** - * Creates digest-response header as defined in RFC2617. - * - * @param credentials User credentials - * - * @return The digest-response as String. - */ - private Header createDigestHeader( - final Credentials credentials, - final HttpRequest request) throws AuthenticationException { - final String uri = getParameter("uri"); - final String realm = getParameter("realm"); - final String nonce = getParameter("nonce"); - final String opaque = getParameter("opaque"); - final String method = getParameter("methodname"); - String algorithm = getParameter("algorithm"); - // If an algorithm is not specified, default to MD5. - if (algorithm == null) { - algorithm = "MD5"; - } - - final Set qopset = new HashSet(8); - int qop = QOP_UNKNOWN; - final String qoplist = getParameter("qop"); - if (qoplist != null) { - final StringTokenizer tok = new StringTokenizer(qoplist, ","); - while (tok.hasMoreTokens()) { - final String variant = tok.nextToken().trim(); - qopset.add(variant.toLowerCase(Locale.ROOT)); - } - if (request instanceof HttpEntityEnclosingRequest && qopset.contains("auth-int")) { - qop = QOP_AUTH_INT; - } else if (qopset.contains("auth")) { - qop = QOP_AUTH; - } - } else { - qop = QOP_MISSING; - } - - if (qop == QOP_UNKNOWN) { - throw new AuthenticationException("None of the qop methods is supported: " + qoplist); - } - - String charset = getParameter("charset"); - if (charset == null) { - charset = "ISO-8859-1"; - } - - String digAlg = algorithm; - if (digAlg.equalsIgnoreCase("MD5-sess")) { - digAlg = "MD5"; - } - - final MessageDigest digester; - try { - digester = createMessageDigest(digAlg); - } catch (final UnsupportedDigestAlgorithmException ex) { - throw new AuthenticationException("Unsuppported digest algorithm: " + digAlg); - } - - final String uname = credentials.getUserPrincipal().getName(); - final String pwd = credentials.getPassword(); - - if (nonce.equals(this.lastNonce)) { - nounceCount++; - } else { - nounceCount = 1; - cnonce = null; - lastNonce = nonce; - } - final StringBuilder sb = new StringBuilder(256); - final Formatter formatter = new Formatter(sb, Locale.US); - formatter.format("%08x", Long.valueOf(nounceCount)); - formatter.close(); - final String nc = sb.toString(); - - if (cnonce == null) { - cnonce = createCnonce(); - } - - a1 = null; - a2 = null; - // 3.2.2.2: Calculating digest - if (algorithm.equalsIgnoreCase("MD5-sess")) { - // H( unq(username-value) ":" unq(realm-value) ":" passwd ) - // ":" unq(nonce-value) - // ":" unq(cnonce-value) - - // calculated one per session - sb.setLength(0); - sb.append(uname).append(':').append(realm).append(':').append(pwd); - final String checksum = encode(digester.digest(EncodingUtils.getBytes(sb.toString(), charset))); - sb.setLength(0); - sb.append(checksum).append(':').append(nonce).append(':').append(cnonce); - a1 = sb.toString(); - } else { - // unq(username-value) ":" unq(realm-value) ":" passwd - sb.setLength(0); - sb.append(uname).append(':').append(realm).append(':').append(pwd); - a1 = sb.toString(); - } - - final String hasha1 = encode(digester.digest(EncodingUtils.getBytes(a1, charset))); - - if (qop == QOP_AUTH) { - // Method ":" digest-uri-value - a2 = method + ':' + uri; - } else if (qop == QOP_AUTH_INT) { - // Method ":" digest-uri-value ":" H(entity-body) - HttpEntity entity = null; - if (request instanceof HttpEntityEnclosingRequest) { - entity = ((HttpEntityEnclosingRequest) request).getEntity(); - } - if (entity != null && !entity.isRepeatable()) { - // If the entity is not repeatable, try falling back onto QOP_AUTH - if (qopset.contains("auth")) { - qop = QOP_AUTH; - a2 = method + ':' + uri; - } else { - throw new AuthenticationException("Qop auth-int cannot be used with " + - "a non-repeatable entity"); - } - } else { - final HttpEntityDigester entityDigester = new HttpEntityDigester(digester); - try { - if (entity != null) { - entity.writeTo(entityDigester); - } - entityDigester.close(); - } catch (final IOException ex) { - throw new AuthenticationException("I/O error reading entity content", ex); - } - a2 = method + ':' + uri + ':' + encode(entityDigester.getDigest()); - } - } else { - a2 = method + ':' + uri; - } - - final String hasha2 = encode(digester.digest(EncodingUtils.getBytes(a2, charset))); - - // 3.2.2.1 - - final String digestValue; - if (qop == QOP_MISSING) { - sb.setLength(0); - sb.append(hasha1).append(':').append(nonce).append(':').append(hasha2); - digestValue = sb.toString(); - } else { - sb.setLength(0); - sb.append(hasha1).append(':').append(nonce).append(':').append(nc).append(':') - .append(cnonce).append(':').append(qop == QOP_AUTH_INT ? "auth-int" : "auth") - .append(':').append(hasha2); - digestValue = sb.toString(); - } - - final String digest = encode(digester.digest(EncodingUtils.getAsciiBytes(digestValue))); - - final CharArrayBuffer buffer = new CharArrayBuffer(128); - if (isProxy()) { - buffer.append(AUTH.PROXY_AUTH_RESP); - } else { - buffer.append(AUTH.WWW_AUTH_RESP); - } - buffer.append(": Digest "); - - final List params = new ArrayList(20); - params.add(new BasicNameValuePair("username", uname)); - params.add(new BasicNameValuePair("realm", realm)); - params.add(new BasicNameValuePair("nonce", nonce)); - params.add(new BasicNameValuePair("uri", uri)); - params.add(new BasicNameValuePair("response", digest)); - - if (qop != QOP_MISSING) { - params.add(new BasicNameValuePair("qop", qop == QOP_AUTH_INT ? "auth-int" : "auth")); - params.add(new BasicNameValuePair("nc", nc)); - params.add(new BasicNameValuePair("cnonce", cnonce)); - } - // algorithm cannot be null here - params.add(new BasicNameValuePair("algorithm", algorithm)); - if (opaque != null) { - params.add(new BasicNameValuePair("opaque", opaque)); - } - - for (int i = 0; i < params.size(); i++) { - final BasicNameValuePair param = params.get(i); - if (i > 0) { - buffer.append(", "); - } - final String name = param.getName(); - final boolean noQuotes = ("nc".equals(name) || "qop".equals(name) - || "algorithm".equals(name)); - BasicHeaderValueFormatter.INSTANCE.formatNameValuePair(buffer, param, !noQuotes); - } - return new BufferedHeader(buffer); - } - - String getCnonce() { - return cnonce; - } - - String getA1() { - return a1; - } - - String getA2() { - return a2; - } - - /** - * Encodes the 128 bit (16 bytes) MD5 digest into a 32 characters long - * String according to RFC 2617. - * - * @param binaryData array containing the digest - * @return encoded MD5, or null if encoding failed - */ - static String encode(final byte[] binaryData) { - final int n = binaryData.length; - final char[] buffer = new char[n * 2]; - for (int i = 0; i < n; i++) { - final int low = (binaryData[i] & 0x0f); - final int high = ((binaryData[i] & 0xf0) >> 4); - buffer[i * 2] = HEXADECIMAL[high]; - buffer[(i * 2) + 1] = HEXADECIMAL[low]; - } - - return new String(buffer); - } - - - /** - * Creates a random cnonce value based on the current time. - * - * @return The cnonce value as String. - */ - public static String createCnonce() { - final SecureRandom rnd = new SecureRandom(); - final byte[] tmp = new byte[8]; - rnd.nextBytes(tmp); - return encode(tmp); - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("DIGEST [complete=").append(complete) - .append(", nonce=").append(lastNonce) - .append(", nc=").append(nounceCount) - .append("]"); - return builder.toString(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/DigestSchemeFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/DigestSchemeFactory.java deleted file mode 100644 index 1c8870be..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/DigestSchemeFactory.java +++ /dev/null @@ -1,74 +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 com.tracelytics.ext.apache.http.impl.auth; - -import java.nio.charset.Charset; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -import com.tracelytics.ext.apache.http.auth.AuthScheme; -import com.tracelytics.ext.apache.http.auth.AuthSchemeFactory; -import com.tracelytics.ext.apache.http.auth.AuthSchemeProvider; - -/** - * {@link AuthSchemeProvider} implementation that creates and initializes - * {@link DigestScheme} instances. - * - * @since 4.0 - */ -@Immutable -@SuppressWarnings("deprecation") -public class DigestSchemeFactory implements AuthSchemeFactory, AuthSchemeProvider { - - private final Charset charset; - - /** - * @since 4.3 - */ - public DigestSchemeFactory(final Charset charset) { - super(); - this.charset = charset; - } - - public DigestSchemeFactory() { - this(null); - } - - @Override - public AuthScheme newInstance(final HttpParams params) { - return new DigestScheme(); - } - - @Override - public AuthScheme create(final HttpContext context) { - return new DigestScheme(this.charset); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/GGSSchemeBase.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/GGSSchemeBase.java deleted file mode 100644 index 39317f95..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/GGSSchemeBase.java +++ /dev/null @@ -1,281 +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 com.tracelytics.ext.apache.http.impl.auth; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.ietf.jgss.GSSContext; -import org.ietf.jgss.GSSCredential; -import org.ietf.jgss.GSSException; -import org.ietf.jgss.GSSManager; -import org.ietf.jgss.GSSName; -import org.ietf.jgss.Oid; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.auth.AUTH; -import com.tracelytics.ext.apache.http.auth.AuthenticationException; -import com.tracelytics.ext.apache.http.auth.Credentials; -import com.tracelytics.ext.apache.http.auth.InvalidCredentialsException; -import com.tracelytics.ext.apache.http.auth.KerberosCredentials; -import com.tracelytics.ext.apache.http.auth.MalformedChallengeException; -import com.tracelytics.ext.apache.http.client.protocol.HttpClientContext; -import com.tracelytics.ext.apache.http.conn.routing.HttpRoute; -import com.tracelytics.ext.apache.http.message.BufferedHeader; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; -import com.tracelytics.ext.base64.Base64; - -/** - * @since 4.2 - */ -@NotThreadSafe -public abstract class GGSSchemeBase extends AuthSchemeBase { - - enum State { - UNINITIATED, - CHALLENGE_RECEIVED, - TOKEN_GENERATED, - FAILED, - } - - private final Logger log = Logger.getLogger(getClass().getName()); - - private final boolean stripPort; - private final boolean useCanonicalHostname; - - /** Authentication process state */ - private State state; - - /** base64 decoded challenge **/ - private byte[] token; - - GGSSchemeBase(final boolean stripPort, final boolean useCanonicalHostname) { - super(); - this.stripPort = stripPort; - this.useCanonicalHostname = useCanonicalHostname; - this.state = State.UNINITIATED; - } - - GGSSchemeBase(final boolean stripPort) { - this(stripPort, true); - } - - GGSSchemeBase() { - this(true,true); - } - - protected GSSManager getManager() { - return GSSManager.getInstance(); - } - - protected byte[] generateGSSToken( - final byte[] input, final Oid oid, final String authServer) throws GSSException { - return generateGSSToken(input, oid, authServer, null); - } - - /** - * @since 4.4 - */ - protected byte[] generateGSSToken( - final byte[] input, final Oid oid, final String authServer, - final Credentials credentials) throws GSSException { - byte[] inputBuff = input; - if (inputBuff == null) { - inputBuff = new byte[0]; - } - final GSSManager manager = getManager(); - final GSSName serverName = manager.createName("HTTP@" + authServer, GSSName.NT_HOSTBASED_SERVICE); - - final GSSCredential gssCredential; - if (credentials instanceof KerberosCredentials) { - gssCredential = ((KerberosCredentials) credentials).getGSSCredential(); - } else { - gssCredential = null; - } - - final GSSContext gssContext = manager.createContext( - serverName.canonicalize(oid), oid, gssCredential, GSSContext.DEFAULT_LIFETIME); - gssContext.requestMutualAuth(true); - gssContext.requestCredDeleg(true); - return gssContext.initSecContext(inputBuff, 0, inputBuff.length); - } - - /** - * @deprecated (4.4) Use {@link #generateToken(byte[], String, com.tracelytics.ext.apache.http.auth.Credentials)}. - */ - @Deprecated - protected byte[] generateToken(final byte[] input, final String authServer) throws GSSException { - return null; - } - - /** - * @since 4.4 - */ - //TODO: make this method abstract - @SuppressWarnings("deprecation") - protected byte[] generateToken( - final byte[] input, final String authServer, final Credentials credentials) throws GSSException { - return generateToken(input, authServer); - } - - @Override - public boolean isComplete() { - return this.state == State.TOKEN_GENERATED || this.state == State.FAILED; - } - - /** - * @deprecated (4.2) Use {@link com.tracelytics.ext.apache.http.auth.ContextAwareAuthScheme#authenticate( - * Credentials, HttpRequest, com.tracelytics.ext.apache.http.protocol.HttpContext)} - */ - @Override - @Deprecated - public Header authenticate( - final Credentials credentials, - final HttpRequest request) throws AuthenticationException { - return authenticate(credentials, request, null); - } - - @Override - public Header authenticate( - final Credentials credentials, - final HttpRequest request, - final HttpContext context) throws AuthenticationException { - Args.notNull(request, "HTTP request"); - switch (state) { - case UNINITIATED: - throw new AuthenticationException(getSchemeName() + " authentication has not been initiated"); - case FAILED: - throw new AuthenticationException(getSchemeName() + " authentication has failed"); - case CHALLENGE_RECEIVED: - try { - final HttpRoute route = (HttpRoute) context.getAttribute(HttpClientContext.HTTP_ROUTE); - if (route == null) { - throw new AuthenticationException("Connection route is not available"); - } - HttpHost host; - if (isProxy()) { - host = route.getProxyHost(); - if (host == null) { - host = route.getTargetHost(); - } - } else { - host = route.getTargetHost(); - } - final String authServer; - String hostname = host.getHostName(); - - if (this.useCanonicalHostname){ - try { - //TODO: uncomment this statement and delete the resolveCanonicalHostname, - //TODO: as soon canonical hostname resolving is implemented in the SystemDefaultDnsResolver - //final DnsResolver dnsResolver = SystemDefaultDnsResolver.INSTANCE; - //hostname = dnsResolver.resolveCanonicalHostname(host.getHostName()); - hostname = resolveCanonicalHostname(hostname); - } catch (UnknownHostException ignore){ - } - } - if (this.stripPort) { // || host.getPort()==80 || host.getPort()==443) { - authServer = hostname; - } else { - authServer = hostname + ":" + host.getPort(); - } - - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "init " + authServer); - } - token = generateToken(token, authServer, credentials); - state = State.TOKEN_GENERATED; - } catch (final GSSException gsse) { - state = State.FAILED; - if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL - || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED) { - throw new InvalidCredentialsException(gsse.getMessage(), gsse); - } - if (gsse.getMajor() == GSSException.NO_CRED ) { - throw new InvalidCredentialsException(gsse.getMessage(), gsse); - } - if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN - || gsse.getMajor() == GSSException.DUPLICATE_TOKEN - || gsse.getMajor() == GSSException.OLD_TOKEN) { - throw new AuthenticationException(gsse.getMessage(), gsse); - } - // other error - throw new AuthenticationException(gsse.getMessage()); - } - case TOKEN_GENERATED: - final String tokenstr = Base64.encodeBytes(token); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Sending response '" + tokenstr + "' back to the auth server"); - } - final CharArrayBuffer buffer = new CharArrayBuffer(32); - if (isProxy()) { - buffer.append(AUTH.PROXY_AUTH_RESP); - } else { - buffer.append(AUTH.WWW_AUTH_RESP); - } - buffer.append(": Negotiate "); - buffer.append(tokenstr); - return new BufferedHeader(buffer); - default: - throw new IllegalStateException("Illegal state: " + state); - } - } - - @Override - protected void parseChallenge( - final CharArrayBuffer buffer, - final int beginIndex, final int endIndex) throws MalformedChallengeException { - final String challenge = buffer.substringTrimmed(beginIndex, endIndex); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Received challenge '" + challenge + "' from the auth server"); - } - if (state == State.UNINITIATED) { - token = Base64.encodeBytesToBytes(challenge.getBytes()); - state = State.CHALLENGE_RECEIVED; - } else { - log.log(Level.FINE, "Authentication already attempted"); - state = State.FAILED; - } - } - - private String resolveCanonicalHostname(final String host) throws UnknownHostException { - final InetAddress in = InetAddress.getByName(host); - final String canonicalServer = in.getCanonicalHostName(); - if (in.getHostAddress().contentEquals(canonicalServer)) { - return host; - } - return canonicalServer; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/HttpAuthenticator.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/HttpAuthenticator.java deleted file mode 100644 index 9daa6b1a..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/HttpAuthenticator.java +++ /dev/null @@ -1,245 +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 com.tracelytics.ext.apache.http.impl.auth; - -import java.io.IOException; -import java.util.Locale; -import java.util.Map; -import java.util.Queue; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.auth.AuthOption; -import com.tracelytics.ext.apache.http.auth.AuthProtocolState; -import com.tracelytics.ext.apache.http.auth.AuthScheme; -import com.tracelytics.ext.apache.http.auth.AuthState; -import com.tracelytics.ext.apache.http.auth.AuthenticationException; -import com.tracelytics.ext.apache.http.auth.ContextAwareAuthScheme; -import com.tracelytics.ext.apache.http.auth.Credentials; -import com.tracelytics.ext.apache.http.auth.MalformedChallengeException; -import com.tracelytics.ext.apache.http.client.AuthenticationStrategy; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.util.Asserts; - -/** - * @since 4.3 - */ -public class HttpAuthenticator { - - private final Logger log; - - public HttpAuthenticator(final Logger log) { - super(); - this.log = log != null ? log : Logger.getLogger(getClass().getName()); - } - - public HttpAuthenticator() { - this(null); - } - - public boolean isAuthenticationRequested( - final HttpHost host, - final HttpResponse response, - final AuthenticationStrategy authStrategy, - final AuthState authState, - final HttpContext context) { - if (authStrategy.isAuthenticationRequested(host, response, context)) { - this.log.log(Level.FINE, "Authentication required"); - if (authState.getState() == AuthProtocolState.SUCCESS) { - authStrategy.authFailed(host, authState.getAuthScheme(), context); - } - return true; - } else { - switch (authState.getState()) { - case CHALLENGED: - case HANDSHAKE: - this.log.log(Level.FINE, "Authentication succeeded"); - authState.setState(AuthProtocolState.SUCCESS); - authStrategy.authSucceeded(host, authState.getAuthScheme(), context); - break; - case SUCCESS: - break; - default: - authState.setState(AuthProtocolState.UNCHALLENGED); - } - return false; - } - } - - public boolean handleAuthChallenge( - final HttpHost host, - final HttpResponse response, - final AuthenticationStrategy authStrategy, - final AuthState authState, - final HttpContext context) { - try { - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, host.toHostString() + " requested authentication"); - } - final Map challenges = authStrategy.getChallenges(host, response, context); - if (challenges.isEmpty()) { - this.log.log(Level.FINE, "Response contains no authentication challenges"); - return false; - } - - final AuthScheme authScheme = authState.getAuthScheme(); - switch (authState.getState()) { - case FAILURE: - return false; - case SUCCESS: - authState.reset(); - break; - case CHALLENGED: - case HANDSHAKE: - if (authScheme == null) { - this.log.log(Level.FINE, "Auth scheme is null"); - authStrategy.authFailed(host, null, context); - authState.reset(); - authState.setState(AuthProtocolState.FAILURE); - return false; - } - case UNCHALLENGED: - if (authScheme != null) { - final String id = authScheme.getSchemeName(); - final Header challenge = challenges.get(id.toLowerCase(Locale.ROOT)); - if (challenge != null) { - this.log.log(Level.FINE, "Authorization challenge processed"); - authScheme.processChallenge(challenge); - if (authScheme.isComplete()) { - this.log.log(Level.FINE, "Authentication failed"); - authStrategy.authFailed(host, authState.getAuthScheme(), context); - authState.reset(); - authState.setState(AuthProtocolState.FAILURE); - return false; - } else { - authState.setState(AuthProtocolState.HANDSHAKE); - return true; - } - } else { - authState.reset(); - // Retry authentication with a different scheme - } - } - } - final Queue authOptions = authStrategy.select(challenges, host, response, context); - if (authOptions != null && !authOptions.isEmpty()) { - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Selected authentication options: " + authOptions); - } - authState.setState(AuthProtocolState.CHALLENGED); - authState.update(authOptions); - return true; - } else { - return false; - } - } catch (final MalformedChallengeException ex) { - if (this.log.isLoggable(Level.WARNING)) { - this.log.log(Level.WARNING, "Malformed challenge: " + ex.getMessage()); - } - authState.reset(); - return false; - } - } - - public void generateAuthResponse( - final HttpRequest request, - final AuthState authState, - final HttpContext context) throws HttpException, IOException { - AuthScheme authScheme = authState.getAuthScheme(); - Credentials creds = authState.getCredentials(); - switch (authState.getState()) { // TODO add UNCHALLENGED and HANDSHAKE cases - case FAILURE: - return; - case SUCCESS: - ensureAuthScheme(authScheme); - if (authScheme.isConnectionBased()) { - return; - } - break; - case CHALLENGED: - final Queue authOptions = authState.getAuthOptions(); - if (authOptions != null) { - while (!authOptions.isEmpty()) { - final AuthOption authOption = authOptions.remove(); - authScheme = authOption.getAuthScheme(); - creds = authOption.getCredentials(); - authState.update(authScheme, creds); - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Generating response to an authentication challenge using " - + authScheme.getSchemeName() + " scheme"); - } - try { - final Header header = doAuth(authScheme, creds, request, context); - request.addHeader(header); - break; - } catch (final AuthenticationException ex) { - if (this.log.isLoggable(Level.WARNING)) { - this.log.log(Level.WARNING, authScheme + " authentication error: " + ex.getMessage()); - } - } - } - return; - } else { - ensureAuthScheme(authScheme); - } - } - if (authScheme != null) { - try { - final Header header = doAuth(authScheme, creds, request, context); - request.addHeader(header); - } catch (final AuthenticationException ex) { - if (this.log.isLoggable(Level.WARNING)) { - this.log.log(Level.WARNING, authScheme + " authentication error: " + ex.getMessage()); - } - } - } - } - - private void ensureAuthScheme(final AuthScheme authScheme) { - Asserts.notNull(authScheme, "Auth scheme"); - } - - @SuppressWarnings("deprecation") - private Header doAuth( - final AuthScheme authScheme, - final Credentials creds, - final HttpRequest request, - final HttpContext context) throws AuthenticationException { - if (authScheme instanceof ContextAwareAuthScheme) { - return ((ContextAwareAuthScheme) authScheme).authenticate(creds, request, context); - } else { - return authScheme.authenticate(creds, request); - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/HttpEntityDigester.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/HttpEntityDigester.java deleted file mode 100644 index 506b1005..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/HttpEntityDigester.java +++ /dev/null @@ -1,75 +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 com.tracelytics.ext.apache.http.impl.auth; - -import java.io.IOException; -import java.io.OutputStream; -import java.security.MessageDigest; - -class HttpEntityDigester extends OutputStream { - - private final MessageDigest digester; - private boolean closed; - private byte[] digest; - - HttpEntityDigester(final MessageDigest digester) { - super(); - this.digester = digester; - this.digester.reset(); - } - - @Override - public void write(final int b) throws IOException { - if (this.closed) { - throw new IOException("Stream has been already closed"); - } - this.digester.update((byte) b); - } - - @Override - public void write(final byte[] b, final int off, final int len) throws IOException { - if (this.closed) { - throw new IOException("Stream has been already closed"); - } - this.digester.update(b, off, len); - } - - @Override - public void close() throws IOException { - if (this.closed) { - return; - } - this.closed = true; - this.digest = this.digester.digest(); - super.close(); - } - - public byte[] getDigest() { - return this.digest; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/KerberosScheme.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/KerberosScheme.java deleted file mode 100644 index 9f37c64f..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/KerberosScheme.java +++ /dev/null @@ -1,133 +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 com.tracelytics.ext.apache.http.impl.auth; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.util.Args; -import org.ietf.jgss.GSSException; -import org.ietf.jgss.Oid; - -import com.tracelytics.ext.apache.http.auth.AuthenticationException; -import com.tracelytics.ext.apache.http.auth.Credentials; - -/** - * KERBEROS authentication scheme. - * - * @since 4.2 - */ -@NotThreadSafe -public class KerberosScheme extends GGSSchemeBase { - - private static final String KERBEROS_OID = "1.2.840.113554.1.2.2"; - - /** - * @since 4.4 - */ - public KerberosScheme(final boolean stripPort, final boolean useCanonicalHostname) { - super(stripPort, useCanonicalHostname); - } - - public KerberosScheme(final boolean stripPort) { - super(stripPort); - } - - public KerberosScheme() { - super(); - } - - @Override - public String getSchemeName() { - return "Kerberos"; - } - - /** - * Produces KERBEROS authorization Header based on token created by - * processChallenge. - * - * @param credentials not used by the KERBEROS scheme. - * @param request The request being authenticated - * - * @throws AuthenticationException if authentication string cannot - * be generated due to an authentication failure - * - * @return KERBEROS authentication Header - */ - @Override - public Header authenticate( - final Credentials credentials, - final HttpRequest request, - final HttpContext context) throws AuthenticationException { - return super.authenticate(credentials, request, context); - } - - @Override @SuppressWarnings("deprecation") - protected byte[] generateToken(final byte[] input, final String authServer) throws GSSException { - return super.generateToken(input, authServer); - } - - @Override - protected byte[] generateToken(final byte[] input, final String authServer, final Credentials credentials) throws GSSException { - return generateGSSToken(input, new Oid(KERBEROS_OID), authServer, credentials); - } - - /** - * There are no valid parameters for KERBEROS authentication so this - * method always returns {@code null}. - * - * @return {@code null} - */ - @Override - public String getParameter(final String name) { - Args.notNull(name, "Parameter name"); - return null; - } - - /** - * The concept of an authentication realm is not supported by the Negotiate - * authentication scheme. Always returns {@code null}. - * - * @return {@code null} - */ - @Override - public String getRealm() { - return null; - } - - /** - * Returns {@code true}. KERBEROS authentication scheme is connection based. - * - * @return {@code true}. - */ - @Override - public boolean isConnectionBased() { - return true; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/KerberosSchemeFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/KerberosSchemeFactory.java deleted file mode 100644 index eb56807d..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/KerberosSchemeFactory.java +++ /dev/null @@ -1,87 +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 com.tracelytics.ext.apache.http.impl.auth; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -import com.tracelytics.ext.apache.http.auth.AuthScheme; -import com.tracelytics.ext.apache.http.auth.AuthSchemeFactory; -import com.tracelytics.ext.apache.http.auth.AuthSchemeProvider; - -/** - * {@link AuthSchemeProvider} implementation that creates and initializes - * {@link KerberosScheme} instances. - * - * @since 4.2 - */ -@Immutable -@SuppressWarnings("deprecation") -public class KerberosSchemeFactory implements AuthSchemeFactory, AuthSchemeProvider { - - private final boolean stripPort; - private final boolean useCanonicalHostname; - - /** - * @since 4.4 - */ - public KerberosSchemeFactory(final boolean stripPort, final boolean useCanonicalHostname) { - super(); - this.stripPort = stripPort; - this.useCanonicalHostname = useCanonicalHostname; - } - - public KerberosSchemeFactory(final boolean stripPort) { - super(); - this.stripPort = stripPort; - this.useCanonicalHostname = true; - } - - public KerberosSchemeFactory() { - this(true, true); - } - - public boolean isStripPort() { - return stripPort; - } - - public boolean isUseCanonicalHostname() { - return useCanonicalHostname; - } - - @Override - public AuthScheme newInstance(final HttpParams params) { - return new KerberosScheme(this.stripPort, this.useCanonicalHostname); - } - - @Override - public AuthScheme create(final HttpContext context) { - return new KerberosScheme(this.stripPort, this.useCanonicalHostname); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/NTLMEngine.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/NTLMEngine.java deleted file mode 100644 index 444df927..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/NTLMEngine.java +++ /dev/null @@ -1,70 +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 com.tracelytics.ext.apache.http.impl.auth; - -/** - * Abstract NTLM authentication engine. The engine can be used to - * generate Type1 messages and Type3 messages in response to a - * Type2 challenge. - * - * @since 4.0 - */ -public interface NTLMEngine { - - /** - * Generates a Type1 message given the domain and workstation. - * - * @param domain Optional Windows domain name. Can be {@code null}. - * @param workstation Optional Windows workstation name. Can be - * {@code null}. - * @return Type1 message - * @throws NTLMEngineException - */ - String generateType1Msg( - String domain, - String workstation) throws NTLMEngineException; - - /** - * Generates a Type3 message given the user credentials and the - * authentication challenge. - * - * @param username Windows user name - * @param password Password - * @param domain Windows domain name - * @param workstation Windows workstation name - * @param challenge Type2 challenge. - * @return Type3 response. - * @throws NTLMEngineException - */ - String generateType3Msg( - String username, - String password, - String domain, - String workstation, - String challenge) throws NTLMEngineException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/NTLMEngineException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/NTLMEngineException.java deleted file mode 100644 index 190f9330..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/NTLMEngineException.java +++ /dev/null @@ -1,68 +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 com.tracelytics.ext.apache.http.impl.auth; - -import com.tracelytics.ext.apache.http.annotation.Immutable; - -import com.tracelytics.ext.apache.http.auth.AuthenticationException; - -/** - * Signals NTLM protocol failure. - * - * - * @since 4.0 - */ -@Immutable -public class NTLMEngineException extends AuthenticationException { - - private static final long serialVersionUID = 6027981323731768824L; - - public NTLMEngineException() { - super(); - } - - /** - * Creates a new NTLMEngineException with the specified message. - * - * @param message the exception detail message - */ - public NTLMEngineException(final String message) { - super(message); - } - - /** - * Creates a new NTLMEngineException with the specified detail message and cause. - * - * @param message the exception detail message - * @param cause the {@code Throwable} that caused this exception, or {@code null} - * if the cause is unavailable, unknown, or not a {@code Throwable} - */ - public NTLMEngineException(final String message, final Throwable cause) { - super(message, cause); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/NTLMEngineImpl.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/NTLMEngineImpl.java deleted file mode 100644 index a458a6fe..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/NTLMEngineImpl.java +++ /dev/null @@ -1,1655 +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 com.tracelytics.ext.apache.http.impl.auth; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.nio.charset.Charset; -import java.security.Key; -import java.security.MessageDigest; -import java.util.Arrays; -import java.util.Locale; - -import javax.crypto.Cipher; -import javax.crypto.spec.SecretKeySpec; - -import com.tracelytics.ext.apache.http.Consts; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.util.CharsetUtils; -import com.tracelytics.ext.apache.http.util.EncodingUtils; -import com.tracelytics.ext.base64.Base64; - -/** - * Provides an implementation for NTLMv1, NTLMv2, and NTLM2 Session forms of the NTLM - * authentication protocol. - * - * @since 4.1 - */ -@NotThreadSafe -final class NTLMEngineImpl implements NTLMEngine { - - /** Unicode encoding */ - private static final Charset UNICODE_LITTLE_UNMARKED = CharsetUtils.lookup("UnicodeLittleUnmarked"); - /** Character encoding */ - private static final Charset DEFAULT_CHARSET = Consts.ASCII; - - // Flags we use; descriptions according to: - // http://davenport.sourceforge.net/ntlm.html - // and - // http://msdn.microsoft.com/en-us/library/cc236650%28v=prot.20%29.aspx - protected static final int FLAG_REQUEST_UNICODE_ENCODING = 0x00000001; // Unicode string encoding requested - protected static final int FLAG_REQUEST_TARGET = 0x00000004; // Requests target field - protected static final int FLAG_REQUEST_SIGN = 0x00000010; // Requests all messages have a signature attached, in NEGOTIATE message. - protected static final int FLAG_REQUEST_SEAL = 0x00000020; // Request key exchange for message confidentiality in NEGOTIATE message. MUST be used in conjunction with 56BIT. - protected static final int FLAG_REQUEST_LAN_MANAGER_KEY = 0x00000080; // Request Lan Manager key instead of user session key - protected static final int FLAG_REQUEST_NTLMv1 = 0x00000200; // Request NTLMv1 security. MUST be set in NEGOTIATE and CHALLENGE both - protected static final int FLAG_DOMAIN_PRESENT = 0x00001000; // Domain is present in message - protected static final int FLAG_WORKSTATION_PRESENT = 0x00002000; // Workstation is present in message - protected static final int FLAG_REQUEST_ALWAYS_SIGN = 0x00008000; // Requests a signature block on all messages. Overridden by REQUEST_SIGN and REQUEST_SEAL. - protected static final int FLAG_REQUEST_NTLM2_SESSION = 0x00080000; // From server in challenge, requesting NTLM2 session security - protected static final int FLAG_REQUEST_VERSION = 0x02000000; // Request protocol version - protected static final int FLAG_TARGETINFO_PRESENT = 0x00800000; // From server in challenge message, indicating targetinfo is present - protected static final int FLAG_REQUEST_128BIT_KEY_EXCH = 0x20000000; // Request explicit 128-bit key exchange - protected static final int FLAG_REQUEST_EXPLICIT_KEY_EXCH = 0x40000000; // Request explicit key exchange - protected static final int FLAG_REQUEST_56BIT_ENCRYPTION = 0x80000000; // Must be used in conjunction with SEAL - - - /** Secure random generator */ - private static final java.security.SecureRandom RND_GEN; - static { - java.security.SecureRandom rnd = null; - try { - rnd = java.security.SecureRandom.getInstance("SHA1PRNG"); - } catch (final Exception ignore) { - } - RND_GEN = rnd; - } - - /** The signature string as bytes in the default encoding */ - private static final byte[] SIGNATURE; - - static { - final byte[] bytesWithoutNull = "NTLMSSP".getBytes(Consts.ASCII); - SIGNATURE = new byte[bytesWithoutNull.length + 1]; - System.arraycopy(bytesWithoutNull, 0, SIGNATURE, 0, bytesWithoutNull.length); - SIGNATURE[bytesWithoutNull.length] = (byte) 0x00; - } - - private static final Type1Message TYPE_1_MESSAGE = new Type1Message(); - - /** - * Returns the response for the given message. - * - * @param message - * the message that was received from the server. - * @param username - * the username to authenticate with. - * @param password - * the password to authenticate with. - * @param host - * The host. - * @param domain - * the NT domain to authenticate in. - * @return The response. - * @throws com.tracelytics.ext.apache.http.HttpException - * If the messages cannot be retrieved. - */ - static String getResponseFor(final String message, final String username, final String password, - final String host, final String domain) throws NTLMEngineException { - - final String response; - if (message == null || message.trim().equals("")) { - response = getType1Message(host, domain); - } else { - final Type2Message t2m = new Type2Message(message); - response = getType3Message(username, password, host, domain, t2m.getChallenge(), t2m - .getFlags(), t2m.getTarget(), t2m.getTargetInfo()); - } - return response; - } - - /** - * Creates the first message (type 1 message) in the NTLM authentication - * sequence. This message includes the user name, domain and host for the - * authentication session. - * - * @param host - * the computer name of the host requesting authentication. - * @param domain - * The domain to authenticate with. - * @return String the message to add to the HTTP request header. - */ - static String getType1Message(final String host, final String domain) throws NTLMEngineException { - // For compatibility reason do not include domain and host in type 1 message - //return new Type1Message(domain, host).getResponse(); - return TYPE_1_MESSAGE.getResponse(); - } - - /** - * Creates the type 3 message using the given server nonce. The type 3 - * message includes all the information for authentication, host, domain, - * username and the result of encrypting the nonce sent by the server using - * the user's password as the key. - * - * @param user - * The user name. This should not include the domain name. - * @param password - * The password. - * @param host - * The host that is originating the authentication request. - * @param domain - * The domain to authenticate within. - * @param nonce - * the 8 byte array the server sent. - * @return The type 3 message. - * @throws NTLMEngineException - * If {@encrypt(byte[],byte[])} fails. - */ - static String getType3Message(final String user, final String password, final String host, final String domain, - final byte[] nonce, final int type2Flags, final String target, final byte[] targetInformation) - throws NTLMEngineException { - return new Type3Message(domain, host, user, password, nonce, type2Flags, target, - targetInformation).getResponse(); - } - - /** Strip dot suffix from a name */ - private static String stripDotSuffix(final String value) { - if (value == null) { - return null; - } - final int index = value.indexOf("."); - if (index != -1) { - return value.substring(0, index); - } - return value; - } - - /** Convert host to standard form */ - private static String convertHost(final String host) { - return stripDotSuffix(host); - } - - /** Convert domain to standard form */ - private static String convertDomain(final String domain) { - return stripDotSuffix(domain); - } - - private static int readULong(final byte[] src, final int index) throws NTLMEngineException { - if (src.length < index + 4) { - throw new NTLMEngineException("NTLM authentication - buffer too small for DWORD"); - } - return (src[index] & 0xff) | ((src[index + 1] & 0xff) << 8) - | ((src[index + 2] & 0xff) << 16) | ((src[index + 3] & 0xff) << 24); - } - - private static int readUShort(final byte[] src, final int index) throws NTLMEngineException { - if (src.length < index + 2) { - throw new NTLMEngineException("NTLM authentication - buffer too small for WORD"); - } - return (src[index] & 0xff) | ((src[index + 1] & 0xff) << 8); - } - - private static byte[] readSecurityBuffer(final byte[] src, final int index) throws NTLMEngineException { - final int length = readUShort(src, index); - final int offset = readULong(src, index + 4); - if (src.length < offset + length) { - throw new NTLMEngineException( - "NTLM authentication - buffer too small for data item"); - } - final byte[] buffer = new byte[length]; - System.arraycopy(src, offset, buffer, 0, length); - return buffer; - } - - /** Calculate a challenge block */ - private static byte[] makeRandomChallenge() throws NTLMEngineException { - if (RND_GEN == null) { - throw new NTLMEngineException("Random generator not available"); - } - final byte[] rval = new byte[8]; - synchronized (RND_GEN) { - RND_GEN.nextBytes(rval); - } - return rval; - } - - /** Calculate a 16-byte secondary key */ - private static byte[] makeSecondaryKey() throws NTLMEngineException { - if (RND_GEN == null) { - throw new NTLMEngineException("Random generator not available"); - } - final byte[] rval = new byte[16]; - synchronized (RND_GEN) { - RND_GEN.nextBytes(rval); - } - return rval; - } - - protected static class CipherGen { - - protected final String domain; - protected final String user; - protected final String password; - protected final byte[] challenge; - protected final String target; - protected final byte[] targetInformation; - - // Information we can generate but may be passed in (for testing) - protected byte[] clientChallenge; - protected byte[] clientChallenge2; - protected byte[] secondaryKey; - protected byte[] timestamp; - - // Stuff we always generate - protected byte[] lmHash = null; - protected byte[] lmResponse = null; - protected byte[] ntlmHash = null; - protected byte[] ntlmResponse = null; - protected byte[] ntlmv2Hash = null; - protected byte[] lmv2Hash = null; - protected byte[] lmv2Response = null; - protected byte[] ntlmv2Blob = null; - protected byte[] ntlmv2Response = null; - protected byte[] ntlm2SessionResponse = null; - protected byte[] lm2SessionResponse = null; - protected byte[] lmUserSessionKey = null; - protected byte[] ntlmUserSessionKey = null; - protected byte[] ntlmv2UserSessionKey = null; - protected byte[] ntlm2SessionResponseUserSessionKey = null; - protected byte[] lanManagerSessionKey = null; - - public CipherGen(final String domain, final String user, final String password, - final byte[] challenge, final String target, final byte[] targetInformation, - final byte[] clientChallenge, final byte[] clientChallenge2, - final byte[] secondaryKey, final byte[] timestamp) { - this.domain = domain; - this.target = target; - this.user = user; - this.password = password; - this.challenge = challenge; - this.targetInformation = targetInformation; - this.clientChallenge = clientChallenge; - this.clientChallenge2 = clientChallenge2; - this.secondaryKey = secondaryKey; - this.timestamp = timestamp; - } - - public CipherGen(final String domain, final String user, final String password, - final byte[] challenge, final String target, final byte[] targetInformation) { - this(domain, user, password, challenge, target, targetInformation, null, null, null, null); - } - - /** Calculate and return client challenge */ - public byte[] getClientChallenge() - throws NTLMEngineException { - if (clientChallenge == null) { - clientChallenge = makeRandomChallenge(); - } - return clientChallenge; - } - - /** Calculate and return second client challenge */ - public byte[] getClientChallenge2() - throws NTLMEngineException { - if (clientChallenge2 == null) { - clientChallenge2 = makeRandomChallenge(); - } - return clientChallenge2; - } - - /** Calculate and return random secondary key */ - public byte[] getSecondaryKey() - throws NTLMEngineException { - if (secondaryKey == null) { - secondaryKey = makeSecondaryKey(); - } - return secondaryKey; - } - - /** Calculate and return the LMHash */ - public byte[] getLMHash() - throws NTLMEngineException { - if (lmHash == null) { - lmHash = lmHash(password); - } - return lmHash; - } - - /** Calculate and return the LMResponse */ - public byte[] getLMResponse() - throws NTLMEngineException { - if (lmResponse == null) { - lmResponse = lmResponse(getLMHash(),challenge); - } - return lmResponse; - } - - /** Calculate and return the NTLMHash */ - public byte[] getNTLMHash() - throws NTLMEngineException { - if (ntlmHash == null) { - ntlmHash = ntlmHash(password); - } - return ntlmHash; - } - - /** Calculate and return the NTLMResponse */ - public byte[] getNTLMResponse() - throws NTLMEngineException { - if (ntlmResponse == null) { - ntlmResponse = lmResponse(getNTLMHash(),challenge); - } - return ntlmResponse; - } - - /** Calculate the LMv2 hash */ - public byte[] getLMv2Hash() - throws NTLMEngineException { - if (lmv2Hash == null) { - lmv2Hash = lmv2Hash(domain, user, getNTLMHash()); - } - return lmv2Hash; - } - - /** Calculate the NTLMv2 hash */ - public byte[] getNTLMv2Hash() - throws NTLMEngineException { - if (ntlmv2Hash == null) { - ntlmv2Hash = ntlmv2Hash(domain, user, getNTLMHash()); - } - return ntlmv2Hash; - } - - /** Calculate a timestamp */ - public byte[] getTimestamp() { - if (timestamp == null) { - long time = System.currentTimeMillis(); - time += 11644473600000l; // milliseconds from January 1, 1601 -> epoch. - time *= 10000; // tenths of a microsecond. - // convert to little-endian byte array. - timestamp = new byte[8]; - for (int i = 0; i < 8; i++) { - timestamp[i] = (byte) time; - time >>>= 8; - } - } - return timestamp; - } - - /** Calculate the NTLMv2Blob */ - public byte[] getNTLMv2Blob() - throws NTLMEngineException { - if (ntlmv2Blob == null) { - ntlmv2Blob = createBlob(getClientChallenge2(), targetInformation, getTimestamp()); - } - return ntlmv2Blob; - } - - /** Calculate the NTLMv2Response */ - public byte[] getNTLMv2Response() - throws NTLMEngineException { - if (ntlmv2Response == null) { - ntlmv2Response = lmv2Response(getNTLMv2Hash(),challenge,getNTLMv2Blob()); - } - return ntlmv2Response; - } - - /** Calculate the LMv2Response */ - public byte[] getLMv2Response() - throws NTLMEngineException { - if (lmv2Response == null) { - lmv2Response = lmv2Response(getLMv2Hash(),challenge,getClientChallenge()); - } - return lmv2Response; - } - - /** Get NTLM2SessionResponse */ - public byte[] getNTLM2SessionResponse() - throws NTLMEngineException { - if (ntlm2SessionResponse == null) { - ntlm2SessionResponse = ntlm2SessionResponse(getNTLMHash(),challenge,getClientChallenge()); - } - return ntlm2SessionResponse; - } - - /** Calculate and return LM2 session response */ - public byte[] getLM2SessionResponse() - throws NTLMEngineException { - if (lm2SessionResponse == null) { - final byte[] clntChallenge = getClientChallenge(); - lm2SessionResponse = new byte[24]; - System.arraycopy(clntChallenge, 0, lm2SessionResponse, 0, clntChallenge.length); - Arrays.fill(lm2SessionResponse, clntChallenge.length, lm2SessionResponse.length, (byte) 0x00); - } - return lm2SessionResponse; - } - - /** Get LMUserSessionKey */ - public byte[] getLMUserSessionKey() - throws NTLMEngineException { - if (lmUserSessionKey == null) { - lmUserSessionKey = new byte[16]; - System.arraycopy(getLMHash(), 0, lmUserSessionKey, 0, 8); - Arrays.fill(lmUserSessionKey, 8, 16, (byte) 0x00); - } - return lmUserSessionKey; - } - - /** Get NTLMUserSessionKey */ - public byte[] getNTLMUserSessionKey() - throws NTLMEngineException { - if (ntlmUserSessionKey == null) { - final MD4 md4 = new MD4(); - md4.update(getNTLMHash()); - ntlmUserSessionKey = md4.getOutput(); - } - return ntlmUserSessionKey; - } - - /** GetNTLMv2UserSessionKey */ - public byte[] getNTLMv2UserSessionKey() - throws NTLMEngineException { - if (ntlmv2UserSessionKey == null) { - final byte[] ntlmv2hash = getNTLMv2Hash(); - final byte[] truncatedResponse = new byte[16]; - System.arraycopy(getNTLMv2Response(), 0, truncatedResponse, 0, 16); - ntlmv2UserSessionKey = hmacMD5(truncatedResponse, ntlmv2hash); - } - return ntlmv2UserSessionKey; - } - - /** Get NTLM2SessionResponseUserSessionKey */ - public byte[] getNTLM2SessionResponseUserSessionKey() - throws NTLMEngineException { - if (ntlm2SessionResponseUserSessionKey == null) { - final byte[] ntlm2SessionResponseNonce = getLM2SessionResponse(); - final byte[] sessionNonce = new byte[challenge.length + ntlm2SessionResponseNonce.length]; - System.arraycopy(challenge, 0, sessionNonce, 0, challenge.length); - System.arraycopy(ntlm2SessionResponseNonce, 0, sessionNonce, challenge.length, ntlm2SessionResponseNonce.length); - ntlm2SessionResponseUserSessionKey = hmacMD5(sessionNonce,getNTLMUserSessionKey()); - } - return ntlm2SessionResponseUserSessionKey; - } - - /** Get LAN Manager session key */ - public byte[] getLanManagerSessionKey() - throws NTLMEngineException { - if (lanManagerSessionKey == null) { - try { - final byte[] keyBytes = new byte[14]; - System.arraycopy(getLMHash(), 0, keyBytes, 0, 8); - Arrays.fill(keyBytes, 8, keyBytes.length, (byte)0xbd); - final Key lowKey = createDESKey(keyBytes, 0); - final Key highKey = createDESKey(keyBytes, 7); - final byte[] truncatedResponse = new byte[8]; - System.arraycopy(getLMResponse(), 0, truncatedResponse, 0, truncatedResponse.length); - Cipher des = Cipher.getInstance("DES/ECB/NoPadding"); - des.init(Cipher.ENCRYPT_MODE, lowKey); - final byte[] lowPart = des.doFinal(truncatedResponse); - des = Cipher.getInstance("DES/ECB/NoPadding"); - des.init(Cipher.ENCRYPT_MODE, highKey); - final byte[] highPart = des.doFinal(truncatedResponse); - lanManagerSessionKey = new byte[16]; - System.arraycopy(lowPart, 0, lanManagerSessionKey, 0, lowPart.length); - System.arraycopy(highPart, 0, lanManagerSessionKey, lowPart.length, highPart.length); - } catch (final Exception e) { - throw new NTLMEngineException(e.getMessage(), e); - } - } - return lanManagerSessionKey; - } - } - - /** Calculates HMAC-MD5 */ - static byte[] hmacMD5(final byte[] value, final byte[] key) - throws NTLMEngineException { - final HMACMD5 hmacMD5 = new HMACMD5(key); - hmacMD5.update(value); - return hmacMD5.getOutput(); - } - - /** Calculates RC4 */ - static byte[] RC4(final byte[] value, final byte[] key) - throws NTLMEngineException { - try { - final Cipher rc4 = Cipher.getInstance("RC4"); - rc4.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "RC4")); - return rc4.doFinal(value); - } catch (final Exception e) { - throw new NTLMEngineException(e.getMessage(), e); - } - } - - /** - * Calculates the NTLM2 Session Response for the given challenge, using the - * specified password and client challenge. - * - * @return The NTLM2 Session Response. This is placed in the NTLM response - * field of the Type 3 message; the LM response field contains the - * client challenge, null-padded to 24 bytes. - */ - static byte[] ntlm2SessionResponse(final byte[] ntlmHash, final byte[] challenge, - final byte[] clientChallenge) throws NTLMEngineException { - try { - final MessageDigest md5 = MessageDigest.getInstance("MD5"); - md5.update(challenge); - md5.update(clientChallenge); - final byte[] digest = md5.digest(); - - final byte[] sessionHash = new byte[8]; - System.arraycopy(digest, 0, sessionHash, 0, 8); - return lmResponse(ntlmHash, sessionHash); - } catch (final Exception e) { - if (e instanceof NTLMEngineException) { - throw (NTLMEngineException) e; - } - throw new NTLMEngineException(e.getMessage(), e); - } - } - - /** - * Creates the LM Hash of the user's password. - * - * @param password - * The password. - * - * @return The LM Hash of the given password, used in the calculation of the - * LM Response. - */ - private static byte[] lmHash(final String password) throws NTLMEngineException { - try { - final byte[] oemPassword = password.toUpperCase(Locale.ROOT).getBytes(Consts.ASCII); - final int length = Math.min(oemPassword.length, 14); - final byte[] keyBytes = new byte[14]; - System.arraycopy(oemPassword, 0, keyBytes, 0, length); - final Key lowKey = createDESKey(keyBytes, 0); - final Key highKey = createDESKey(keyBytes, 7); - final byte[] magicConstant = "KGS!@#$%".getBytes(Consts.ASCII); - final Cipher des = Cipher.getInstance("DES/ECB/NoPadding"); - des.init(Cipher.ENCRYPT_MODE, lowKey); - final byte[] lowHash = des.doFinal(magicConstant); - des.init(Cipher.ENCRYPT_MODE, highKey); - final byte[] highHash = des.doFinal(magicConstant); - final byte[] lmHash = new byte[16]; - System.arraycopy(lowHash, 0, lmHash, 0, 8); - System.arraycopy(highHash, 0, lmHash, 8, 8); - return lmHash; - } catch (final Exception e) { - throw new NTLMEngineException(e.getMessage(), e); - } - } - - /** - * Creates the NTLM Hash of the user's password. - * - * @param password - * The password. - * - * @return The NTLM Hash of the given password, used in the calculation of - * the NTLM Response and the NTLMv2 and LMv2 Hashes. - */ - private static byte[] ntlmHash(final String password) throws NTLMEngineException { - if (UNICODE_LITTLE_UNMARKED == null) { - throw new NTLMEngineException("Unicode not supported"); - } - final byte[] unicodePassword = password.getBytes(UNICODE_LITTLE_UNMARKED); - final MD4 md4 = new MD4(); - md4.update(unicodePassword); - return md4.getOutput(); - } - - /** - * Creates the LMv2 Hash of the user's password. - * - * @return The LMv2 Hash, used in the calculation of the NTLMv2 and LMv2 - * Responses. - */ - private static byte[] lmv2Hash(final String domain, final String user, final byte[] ntlmHash) - throws NTLMEngineException { - if (UNICODE_LITTLE_UNMARKED == null) { - throw new NTLMEngineException("Unicode not supported"); - } - final HMACMD5 hmacMD5 = new HMACMD5(ntlmHash); - // Upper case username, upper case domain! - hmacMD5.update(user.toUpperCase(Locale.ROOT).getBytes(UNICODE_LITTLE_UNMARKED)); - if (domain != null) { - hmacMD5.update(domain.toUpperCase(Locale.ROOT).getBytes(UNICODE_LITTLE_UNMARKED)); - } - return hmacMD5.getOutput(); - } - - /** - * Creates the NTLMv2 Hash of the user's password. - * - * @return The NTLMv2 Hash, used in the calculation of the NTLMv2 and LMv2 - * Responses. - */ - private static byte[] ntlmv2Hash(final String domain, final String user, final byte[] ntlmHash) - throws NTLMEngineException { - if (UNICODE_LITTLE_UNMARKED == null) { - throw new NTLMEngineException("Unicode not supported"); - } - final HMACMD5 hmacMD5 = new HMACMD5(ntlmHash); - // Upper case username, mixed case target!! - hmacMD5.update(user.toUpperCase(Locale.ROOT).getBytes(UNICODE_LITTLE_UNMARKED)); - if (domain != null) { - hmacMD5.update(domain.getBytes(UNICODE_LITTLE_UNMARKED)); - } - return hmacMD5.getOutput(); - } - - /** - * Creates the LM Response from the given hash and Type 2 challenge. - * - * @param hash - * The LM or NTLM Hash. - * @param challenge - * The server challenge from the Type 2 message. - * - * @return The response (either LM or NTLM, depending on the provided hash). - */ - private static byte[] lmResponse(final byte[] hash, final byte[] challenge) throws NTLMEngineException { - try { - final byte[] keyBytes = new byte[21]; - System.arraycopy(hash, 0, keyBytes, 0, 16); - final Key lowKey = createDESKey(keyBytes, 0); - final Key middleKey = createDESKey(keyBytes, 7); - final Key highKey = createDESKey(keyBytes, 14); - final Cipher des = Cipher.getInstance("DES/ECB/NoPadding"); - des.init(Cipher.ENCRYPT_MODE, lowKey); - final byte[] lowResponse = des.doFinal(challenge); - des.init(Cipher.ENCRYPT_MODE, middleKey); - final byte[] middleResponse = des.doFinal(challenge); - des.init(Cipher.ENCRYPT_MODE, highKey); - final byte[] highResponse = des.doFinal(challenge); - final byte[] lmResponse = new byte[24]; - System.arraycopy(lowResponse, 0, lmResponse, 0, 8); - System.arraycopy(middleResponse, 0, lmResponse, 8, 8); - System.arraycopy(highResponse, 0, lmResponse, 16, 8); - return lmResponse; - } catch (final Exception e) { - throw new NTLMEngineException(e.getMessage(), e); - } - } - - /** - * Creates the LMv2 Response from the given hash, client data, and Type 2 - * challenge. - * - * @param hash - * The NTLMv2 Hash. - * @param clientData - * The client data (blob or client challenge). - * @param challenge - * The server challenge from the Type 2 message. - * - * @return The response (either NTLMv2 or LMv2, depending on the client - * data). - */ - private static byte[] lmv2Response(final byte[] hash, final byte[] challenge, final byte[] clientData) - throws NTLMEngineException { - final HMACMD5 hmacMD5 = new HMACMD5(hash); - hmacMD5.update(challenge); - hmacMD5.update(clientData); - final byte[] mac = hmacMD5.getOutput(); - final byte[] lmv2Response = new byte[mac.length + clientData.length]; - System.arraycopy(mac, 0, lmv2Response, 0, mac.length); - System.arraycopy(clientData, 0, lmv2Response, mac.length, clientData.length); - return lmv2Response; - } - - /** - * Creates the NTLMv2 blob from the given target information block and - * client challenge. - * - * @param targetInformation - * The target information block from the Type 2 message. - * @param clientChallenge - * The random 8-byte client challenge. - * - * @return The blob, used in the calculation of the NTLMv2 Response. - */ - private static byte[] createBlob(final byte[] clientChallenge, final byte[] targetInformation, final byte[] timestamp) { - final byte[] blobSignature = new byte[] { (byte) 0x01, (byte) 0x01, (byte) 0x00, (byte) 0x00 }; - final byte[] reserved = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 }; - final byte[] unknown1 = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 }; - final byte[] unknown2 = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 }; - final byte[] blob = new byte[blobSignature.length + reserved.length + timestamp.length + 8 - + unknown1.length + targetInformation.length + unknown2.length]; - int offset = 0; - System.arraycopy(blobSignature, 0, blob, offset, blobSignature.length); - offset += blobSignature.length; - System.arraycopy(reserved, 0, blob, offset, reserved.length); - offset += reserved.length; - System.arraycopy(timestamp, 0, blob, offset, timestamp.length); - offset += timestamp.length; - System.arraycopy(clientChallenge, 0, blob, offset, 8); - offset += 8; - System.arraycopy(unknown1, 0, blob, offset, unknown1.length); - offset += unknown1.length; - System.arraycopy(targetInformation, 0, blob, offset, targetInformation.length); - offset += targetInformation.length; - System.arraycopy(unknown2, 0, blob, offset, unknown2.length); - offset += unknown2.length; - return blob; - } - - /** - * Creates a DES encryption key from the given key material. - * - * @param bytes - * A byte array containing the DES key material. - * @param offset - * The offset in the given byte array at which the 7-byte key - * material starts. - * - * @return A DES encryption key created from the key material starting at - * the specified offset in the given byte array. - */ - private static Key createDESKey(final byte[] bytes, final int offset) { - final byte[] keyBytes = new byte[7]; - System.arraycopy(bytes, offset, keyBytes, 0, 7); - final byte[] material = new byte[8]; - material[0] = keyBytes[0]; - material[1] = (byte) (keyBytes[0] << 7 | (keyBytes[1] & 0xff) >>> 1); - material[2] = (byte) (keyBytes[1] << 6 | (keyBytes[2] & 0xff) >>> 2); - material[3] = (byte) (keyBytes[2] << 5 | (keyBytes[3] & 0xff) >>> 3); - material[4] = (byte) (keyBytes[3] << 4 | (keyBytes[4] & 0xff) >>> 4); - material[5] = (byte) (keyBytes[4] << 3 | (keyBytes[5] & 0xff) >>> 5); - material[6] = (byte) (keyBytes[5] << 2 | (keyBytes[6] & 0xff) >>> 6); - material[7] = (byte) (keyBytes[6] << 1); - oddParity(material); - return new SecretKeySpec(material, "DES"); - } - - /** - * Applies odd parity to the given byte array. - * - * @param bytes - * The data whose parity bits are to be adjusted for odd parity. - */ - private static void oddParity(final byte[] bytes) { - for (int i = 0; i < bytes.length; i++) { - final byte b = bytes[i]; - final boolean needsParity = (((b >>> 7) ^ (b >>> 6) ^ (b >>> 5) ^ (b >>> 4) ^ (b >>> 3) - ^ (b >>> 2) ^ (b >>> 1)) & 0x01) == 0; - if (needsParity) { - bytes[i] |= (byte) 0x01; - } else { - bytes[i] &= (byte) 0xfe; - } - } - } - - /** NTLM message generation, base class */ - static class NTLMMessage { - /** The current response */ - private byte[] messageContents = null; - - /** The current output position */ - private int currentOutputPosition = 0; - - /** Constructor to use when message contents are not yet known */ - NTLMMessage() { - } - - /** Constructor to use when message contents are known */ - NTLMMessage(final String messageBody, final int expectedType) throws NTLMEngineException { - try { - messageContents = Base64.decode(messageBody.getBytes(DEFAULT_CHARSET)); - } catch (IOException e) { - throw new NTLMEngineException(e.getMessage(), e); - } - // Look for NTLM message - if (messageContents.length < SIGNATURE.length) { - throw new NTLMEngineException("NTLM message decoding error - packet too short"); - } - int i = 0; - while (i < SIGNATURE.length) { - if (messageContents[i] != SIGNATURE[i]) { - throw new NTLMEngineException( - "NTLM message expected - instead got unrecognized bytes"); - } - i++; - } - - // Check to be sure there's a type 2 message indicator next - final int type = readULong(SIGNATURE.length); - if (type != expectedType) { - throw new NTLMEngineException("NTLM type " + Integer.toString(expectedType) - + " message expected - instead got type " + Integer.toString(type)); - } - - currentOutputPosition = messageContents.length; - } - - /** - * Get the length of the signature and flags, so calculations can adjust - * offsets accordingly. - */ - protected int getPreambleLength() { - return SIGNATURE.length + 4; - } - - /** Get the message length */ - protected int getMessageLength() { - return currentOutputPosition; - } - - /** Read a byte from a position within the message buffer */ - protected byte readByte(final int position) throws NTLMEngineException { - if (messageContents.length < position + 1) { - throw new NTLMEngineException("NTLM: Message too short"); - } - return messageContents[position]; - } - - /** Read a bunch of bytes from a position in the message buffer */ - protected void readBytes(final byte[] buffer, final int position) throws NTLMEngineException { - if (messageContents.length < position + buffer.length) { - throw new NTLMEngineException("NTLM: Message too short"); - } - System.arraycopy(messageContents, position, buffer, 0, buffer.length); - } - - /** Read a ushort from a position within the message buffer */ - protected int readUShort(final int position) throws NTLMEngineException { - return NTLMEngineImpl.readUShort(messageContents, position); - } - - /** Read a ulong from a position within the message buffer */ - protected int readULong(final int position) throws NTLMEngineException { - return NTLMEngineImpl.readULong(messageContents, position); - } - - /** Read a security buffer from a position within the message buffer */ - protected byte[] readSecurityBuffer(final int position) throws NTLMEngineException { - return NTLMEngineImpl.readSecurityBuffer(messageContents, position); - } - - /** - * Prepares the object to create a response of the given length. - * - * @param maxlength - * the maximum length of the response to prepare, not - * including the type and the signature (which this method - * adds). - */ - protected void prepareResponse(final int maxlength, final int messageType) { - messageContents = new byte[maxlength]; - currentOutputPosition = 0; - addBytes(SIGNATURE); - addULong(messageType); - } - - /** - * Adds the given byte to the response. - * - * @param b - * the byte to add. - */ - protected void addByte(final byte b) { - messageContents[currentOutputPosition] = b; - currentOutputPosition++; - } - - /** - * Adds the given bytes to the response. - * - * @param bytes - * the bytes to add. - */ - protected void addBytes(final byte[] bytes) { - if (bytes == null) { - return; - } - for (final byte b : bytes) { - messageContents[currentOutputPosition] = b; - currentOutputPosition++; - } - } - - /** Adds a USHORT to the response */ - protected void addUShort(final int value) { - addByte((byte) (value & 0xff)); - addByte((byte) (value >> 8 & 0xff)); - } - - /** Adds a ULong to the response */ - protected void addULong(final int value) { - addByte((byte) (value & 0xff)); - addByte((byte) (value >> 8 & 0xff)); - addByte((byte) (value >> 16 & 0xff)); - addByte((byte) (value >> 24 & 0xff)); - } - - /** - * Returns the response that has been generated after shrinking the - * array if required and base64 encodes the response. - * - * @return The response as above. - */ - String getResponse() { - final byte[] resp; - if (messageContents.length > currentOutputPosition) { - final byte[] tmp = new byte[currentOutputPosition]; - System.arraycopy(messageContents, 0, tmp, 0, currentOutputPosition); - resp = tmp; - } else { - resp = messageContents; - } - return EncodingUtils.getAsciiString(Base64.encodeBytesToBytes(resp)); - } - - } - - /** Type 1 message assembly class */ - static class Type1Message extends NTLMMessage { - - private final byte[] hostBytes; - private final byte[] domainBytes; - - Type1Message(final String domain, final String host) throws NTLMEngineException { - super(); - if (UNICODE_LITTLE_UNMARKED == null) { - throw new NTLMEngineException("Unicode not supported"); - } - // Strip off domain name from the host! - final String unqualifiedHost = convertHost(host); - // Use only the base domain name! - final String unqualifiedDomain = convertDomain(domain); - - hostBytes = unqualifiedHost != null ? - unqualifiedHost.getBytes(UNICODE_LITTLE_UNMARKED) : null; - domainBytes = unqualifiedDomain != null ? - unqualifiedDomain.toUpperCase(Locale.ROOT).getBytes(UNICODE_LITTLE_UNMARKED) : null; - } - - Type1Message() { - super(); - hostBytes = null; - domainBytes = null; - } - /** - * Getting the response involves building the message before returning - * it - */ - @Override - String getResponse() { - // Now, build the message. Calculate its length first, including - // signature or type. - final int finalLength = 32 + 8 /*+ hostBytes.length + domainBytes.length */; - - // Set up the response. This will initialize the signature, message - // type, and flags. - prepareResponse(finalLength, 1); - - // Flags. These are the complete set of flags we support. - addULong( - //FLAG_WORKSTATION_PRESENT | - //FLAG_DOMAIN_PRESENT | - - // Required flags - //FLAG_REQUEST_LAN_MANAGER_KEY | - FLAG_REQUEST_NTLMv1 | - FLAG_REQUEST_NTLM2_SESSION | - - // Protocol version request - FLAG_REQUEST_VERSION | - - // Recommended privacy settings - FLAG_REQUEST_ALWAYS_SIGN | - //FLAG_REQUEST_SEAL | - //FLAG_REQUEST_SIGN | - - // These must be set according to documentation, based on use of SEAL above - FLAG_REQUEST_128BIT_KEY_EXCH | - FLAG_REQUEST_56BIT_ENCRYPTION | - //FLAG_REQUEST_EXPLICIT_KEY_EXCH | - - FLAG_REQUEST_UNICODE_ENCODING); - - // Domain length (two times). - addUShort(/*domainBytes.length*/0); - addUShort(/*domainBytes.length*/0); - - // Domain offset. - addULong(/*hostBytes.length +*/ 32 + 8); - - // Host length (two times). - addUShort(/*hostBytes.length*/0); - addUShort(/*hostBytes.length*/0); - - // Host offset (always 32 + 8). - addULong(32 + 8); - - // Version - addUShort(0x0105); - // Build - addULong(2600); - // NTLM revision - addUShort(0x0f00); - - // Host (workstation) String. - if (hostBytes != null) { - addBytes(hostBytes); - } - // Domain String. - if (domainBytes != null) { - addBytes(domainBytes); - } - - return super.getResponse(); - } - - } - - /** Type 2 message class */ - static class Type2Message extends NTLMMessage { - protected byte[] challenge; - protected String target; - protected byte[] targetInfo; - protected int flags; - - Type2Message(final String message) throws NTLMEngineException { - super(message, 2); - - // Type 2 message is laid out as follows: - // First 8 bytes: NTLMSSP[0] - // Next 4 bytes: Ulong, value 2 - // Next 8 bytes, starting at offset 12: target field (2 ushort lengths, 1 ulong offset) - // Next 4 bytes, starting at offset 20: Flags, e.g. 0x22890235 - // Next 8 bytes, starting at offset 24: Challenge - // Next 8 bytes, starting at offset 32: ??? (8 bytes of zeros) - // Next 8 bytes, starting at offset 40: targetinfo field (2 ushort lengths, 1 ulong offset) - // Next 2 bytes, major/minor version number (e.g. 0x05 0x02) - // Next 8 bytes, build number - // Next 2 bytes, protocol version number (e.g. 0x00 0x0f) - // Next, various text fields, and a ushort of value 0 at the end - - // Parse out the rest of the info we need from the message - // The nonce is the 8 bytes starting from the byte in position 24. - challenge = new byte[8]; - readBytes(challenge, 24); - - flags = readULong(20); - - if ((flags & FLAG_REQUEST_UNICODE_ENCODING) == 0) { - throw new NTLMEngineException( - "NTLM type 2 message indicates no support for Unicode. Flags are: " - + Integer.toString(flags)); - } - - // Do the target! - target = null; - // The TARGET_DESIRED flag is said to not have understood semantics - // in Type2 messages, so use the length of the packet to decide - // how to proceed instead - if (getMessageLength() >= 12 + 8) { - final byte[] bytes = readSecurityBuffer(12); - if (bytes.length != 0) { - try { - target = new String(bytes, "UnicodeLittleUnmarked"); - } catch (final UnsupportedEncodingException e) { - throw new NTLMEngineException(e.getMessage(), e); - } - } - } - - // Do the target info! - targetInfo = null; - // TARGET_DESIRED flag cannot be relied on, so use packet length - if (getMessageLength() >= 40 + 8) { - final byte[] bytes = readSecurityBuffer(40); - if (bytes.length != 0) { - targetInfo = bytes; - } - } - } - - /** Retrieve the challenge */ - byte[] getChallenge() { - return challenge; - } - - /** Retrieve the target */ - String getTarget() { - return target; - } - - /** Retrieve the target info */ - byte[] getTargetInfo() { - return targetInfo; - } - - /** Retrieve the response flags */ - int getFlags() { - return flags; - } - - } - - /** Type 3 message assembly class */ - static class Type3Message extends NTLMMessage { - // Response flags from the type2 message - protected int type2Flags; - - protected byte[] domainBytes; - protected byte[] hostBytes; - protected byte[] userBytes; - - protected byte[] lmResp; - protected byte[] ntResp; - protected byte[] sessionKey; - - - /** Constructor. Pass the arguments we will need */ - Type3Message(final String domain, final String host, final String user, final String password, final byte[] nonce, - final int type2Flags, final String target, final byte[] targetInformation) - throws NTLMEngineException { - // Save the flags - this.type2Flags = type2Flags; - - // Strip off domain name from the host! - final String unqualifiedHost = convertHost(host); - // Use only the base domain name! - final String unqualifiedDomain = convertDomain(domain); - - // Create a cipher generator class. Use domain BEFORE it gets modified! - final CipherGen gen = new CipherGen(unqualifiedDomain, user, password, nonce, target, targetInformation); - - // Use the new code to calculate the responses, including v2 if that - // seems warranted. - byte[] userSessionKey; - try { - // This conditional may not work on Windows Server 2008 R2 and above, where it has not yet - // been tested - if (((type2Flags & FLAG_TARGETINFO_PRESENT) != 0) && - targetInformation != null && target != null) { - // NTLMv2 - ntResp = gen.getNTLMv2Response(); - lmResp = gen.getLMv2Response(); - if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0) { - userSessionKey = gen.getLanManagerSessionKey(); - } else { - userSessionKey = gen.getNTLMv2UserSessionKey(); - } - } else { - // NTLMv1 - if ((type2Flags & FLAG_REQUEST_NTLM2_SESSION) != 0) { - // NTLM2 session stuff is requested - ntResp = gen.getNTLM2SessionResponse(); - lmResp = gen.getLM2SessionResponse(); - if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0) { - userSessionKey = gen.getLanManagerSessionKey(); - } else { - userSessionKey = gen.getNTLM2SessionResponseUserSessionKey(); - } - } else { - ntResp = gen.getNTLMResponse(); - lmResp = gen.getLMResponse(); - if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0) { - userSessionKey = gen.getLanManagerSessionKey(); - } else { - userSessionKey = gen.getNTLMUserSessionKey(); - } - } - } - } catch (final NTLMEngineException e) { - // This likely means we couldn't find the MD4 hash algorithm - - // fail back to just using LM - ntResp = new byte[0]; - lmResp = gen.getLMResponse(); - if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0) { - userSessionKey = gen.getLanManagerSessionKey(); - } else { - userSessionKey = gen.getLMUserSessionKey(); - } - } - - if ((type2Flags & FLAG_REQUEST_SIGN) != 0) { - if ((type2Flags & FLAG_REQUEST_EXPLICIT_KEY_EXCH) != 0) { - sessionKey = RC4(gen.getSecondaryKey(), userSessionKey); - } else { - sessionKey = userSessionKey; - } - } else { - sessionKey = null; - } - if (UNICODE_LITTLE_UNMARKED == null) { - throw new NTLMEngineException("Unicode not supported"); - } - hostBytes = unqualifiedHost != null ? unqualifiedHost.getBytes(UNICODE_LITTLE_UNMARKED) : null; - domainBytes = unqualifiedDomain != null ? unqualifiedDomain - .toUpperCase(Locale.ROOT).getBytes(UNICODE_LITTLE_UNMARKED) : null; - userBytes = user.getBytes(UNICODE_LITTLE_UNMARKED); - } - - /** Assemble the response */ - @Override - String getResponse() { - final int ntRespLen = ntResp.length; - final int lmRespLen = lmResp.length; - - final int domainLen = domainBytes != null ? domainBytes.length : 0; - final int hostLen = hostBytes != null ? hostBytes.length: 0; - final int userLen = userBytes.length; - final int sessionKeyLen; - if (sessionKey != null) { - sessionKeyLen = sessionKey.length; - } else { - sessionKeyLen = 0; - } - - // Calculate the layout within the packet - final int lmRespOffset = 72; // allocate space for the version - final int ntRespOffset = lmRespOffset + lmRespLen; - final int domainOffset = ntRespOffset + ntRespLen; - final int userOffset = domainOffset + domainLen; - final int hostOffset = userOffset + userLen; - final int sessionKeyOffset = hostOffset + hostLen; - final int finalLength = sessionKeyOffset + sessionKeyLen; - - // Start the response. Length includes signature and type - prepareResponse(finalLength, 3); - - // LM Resp Length (twice) - addUShort(lmRespLen); - addUShort(lmRespLen); - - // LM Resp Offset - addULong(lmRespOffset); - - // NT Resp Length (twice) - addUShort(ntRespLen); - addUShort(ntRespLen); - - // NT Resp Offset - addULong(ntRespOffset); - - // Domain length (twice) - addUShort(domainLen); - addUShort(domainLen); - - // Domain offset. - addULong(domainOffset); - - // User Length (twice) - addUShort(userLen); - addUShort(userLen); - - // User offset - addULong(userOffset); - - // Host length (twice) - addUShort(hostLen); - addUShort(hostLen); - - // Host offset - addULong(hostOffset); - - // Session key length (twice) - addUShort(sessionKeyLen); - addUShort(sessionKeyLen); - - // Session key offset - addULong(sessionKeyOffset); - - // Flags. - addULong( - //FLAG_WORKSTATION_PRESENT | - //FLAG_DOMAIN_PRESENT | - - // Required flags - (type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) | - (type2Flags & FLAG_REQUEST_NTLMv1) | - (type2Flags & FLAG_REQUEST_NTLM2_SESSION) | - - // Protocol version request - FLAG_REQUEST_VERSION | - - // Recommended privacy settings - (type2Flags & FLAG_REQUEST_ALWAYS_SIGN) | - (type2Flags & FLAG_REQUEST_SEAL) | - (type2Flags & FLAG_REQUEST_SIGN) | - - // These must be set according to documentation, based on use of SEAL above - (type2Flags & FLAG_REQUEST_128BIT_KEY_EXCH) | - (type2Flags & FLAG_REQUEST_56BIT_ENCRYPTION) | - (type2Flags & FLAG_REQUEST_EXPLICIT_KEY_EXCH) | - - (type2Flags & FLAG_TARGETINFO_PRESENT) | - (type2Flags & FLAG_REQUEST_UNICODE_ENCODING) | - (type2Flags & FLAG_REQUEST_TARGET) - ); - - // Version - addUShort(0x0105); - // Build - addULong(2600); - // NTLM revision - addUShort(0x0f00); - - // Add the actual data - addBytes(lmResp); - addBytes(ntResp); - addBytes(domainBytes); - addBytes(userBytes); - addBytes(hostBytes); - if (sessionKey != null) { - addBytes(sessionKey); - } - - return super.getResponse(); - } - } - - static void writeULong(final byte[] buffer, final int value, final int offset) { - buffer[offset] = (byte) (value & 0xff); - buffer[offset + 1] = (byte) (value >> 8 & 0xff); - buffer[offset + 2] = (byte) (value >> 16 & 0xff); - buffer[offset + 3] = (byte) (value >> 24 & 0xff); - } - - static int F(final int x, final int y, final int z) { - return ((x & y) | (~x & z)); - } - - static int G(final int x, final int y, final int z) { - return ((x & y) | (x & z) | (y & z)); - } - - static int H(final int x, final int y, final int z) { - return (x ^ y ^ z); - } - - static int rotintlft(final int val, final int numbits) { - return ((val << numbits) | (val >>> (32 - numbits))); - } - - /** - * Cryptography support - MD4. The following class was based loosely on the - * RFC and on code found at http://www.cs.umd.edu/~harry/jotp/src/md.java. - * Code correctness was verified by looking at MD4.java from the jcifs - * library (http://jcifs.samba.org). It was massaged extensively to the - * final form found here by Karl Wright (kwright@metacarta.com). - */ - static class MD4 { - protected int A = 0x67452301; - protected int B = 0xefcdab89; - protected int C = 0x98badcfe; - protected int D = 0x10325476; - protected long count = 0L; - protected byte[] dataBuffer = new byte[64]; - - MD4() { - } - - void update(final byte[] input) { - // We always deal with 512 bits at a time. Correspondingly, there is - // a buffer 64 bytes long that we write data into until it gets - // full. - int curBufferPos = (int) (count & 63L); - int inputIndex = 0; - while (input.length - inputIndex + curBufferPos >= dataBuffer.length) { - // We have enough data to do the next step. Do a partial copy - // and a transform, updating inputIndex and curBufferPos - // accordingly - final int transferAmt = dataBuffer.length - curBufferPos; - System.arraycopy(input, inputIndex, dataBuffer, curBufferPos, transferAmt); - count += transferAmt; - curBufferPos = 0; - inputIndex += transferAmt; - processBuffer(); - } - - // If there's anything left, copy it into the buffer and leave it. - // We know there's not enough left to process. - if (inputIndex < input.length) { - final int transferAmt = input.length - inputIndex; - System.arraycopy(input, inputIndex, dataBuffer, curBufferPos, transferAmt); - count += transferAmt; - curBufferPos += transferAmt; - } - } - - byte[] getOutput() { - // Feed pad/length data into engine. This must round out the input - // to a multiple of 512 bits. - final int bufferIndex = (int) (count & 63L); - final int padLen = (bufferIndex < 56) ? (56 - bufferIndex) : (120 - bufferIndex); - final byte[] postBytes = new byte[padLen + 8]; - // Leading 0x80, specified amount of zero padding, then length in - // bits. - postBytes[0] = (byte) 0x80; - // Fill out the last 8 bytes with the length - for (int i = 0; i < 8; i++) { - postBytes[padLen + i] = (byte) ((count * 8) >>> (8 * i)); - } - - // Update the engine - update(postBytes); - - // Calculate final result - final byte[] result = new byte[16]; - writeULong(result, A, 0); - writeULong(result, B, 4); - writeULong(result, C, 8); - writeULong(result, D, 12); - return result; - } - - protected void processBuffer() { - // Convert current buffer to 16 ulongs - final int[] d = new int[16]; - - for (int i = 0; i < 16; i++) { - d[i] = (dataBuffer[i * 4] & 0xff) + ((dataBuffer[i * 4 + 1] & 0xff) << 8) - + ((dataBuffer[i * 4 + 2] & 0xff) << 16) - + ((dataBuffer[i * 4 + 3] & 0xff) << 24); - } - - // Do a round of processing - final int AA = A; - final int BB = B; - final int CC = C; - final int DD = D; - round1(d); - round2(d); - round3(d); - A += AA; - B += BB; - C += CC; - D += DD; - - } - - protected void round1(final int[] d) { - A = rotintlft((A + F(B, C, D) + d[0]), 3); - D = rotintlft((D + F(A, B, C) + d[1]), 7); - C = rotintlft((C + F(D, A, B) + d[2]), 11); - B = rotintlft((B + F(C, D, A) + d[3]), 19); - - A = rotintlft((A + F(B, C, D) + d[4]), 3); - D = rotintlft((D + F(A, B, C) + d[5]), 7); - C = rotintlft((C + F(D, A, B) + d[6]), 11); - B = rotintlft((B + F(C, D, A) + d[7]), 19); - - A = rotintlft((A + F(B, C, D) + d[8]), 3); - D = rotintlft((D + F(A, B, C) + d[9]), 7); - C = rotintlft((C + F(D, A, B) + d[10]), 11); - B = rotintlft((B + F(C, D, A) + d[11]), 19); - - A = rotintlft((A + F(B, C, D) + d[12]), 3); - D = rotintlft((D + F(A, B, C) + d[13]), 7); - C = rotintlft((C + F(D, A, B) + d[14]), 11); - B = rotintlft((B + F(C, D, A) + d[15]), 19); - } - - protected void round2(final int[] d) { - A = rotintlft((A + G(B, C, D) + d[0] + 0x5a827999), 3); - D = rotintlft((D + G(A, B, C) + d[4] + 0x5a827999), 5); - C = rotintlft((C + G(D, A, B) + d[8] + 0x5a827999), 9); - B = rotintlft((B + G(C, D, A) + d[12] + 0x5a827999), 13); - - A = rotintlft((A + G(B, C, D) + d[1] + 0x5a827999), 3); - D = rotintlft((D + G(A, B, C) + d[5] + 0x5a827999), 5); - C = rotintlft((C + G(D, A, B) + d[9] + 0x5a827999), 9); - B = rotintlft((B + G(C, D, A) + d[13] + 0x5a827999), 13); - - A = rotintlft((A + G(B, C, D) + d[2] + 0x5a827999), 3); - D = rotintlft((D + G(A, B, C) + d[6] + 0x5a827999), 5); - C = rotintlft((C + G(D, A, B) + d[10] + 0x5a827999), 9); - B = rotintlft((B + G(C, D, A) + d[14] + 0x5a827999), 13); - - A = rotintlft((A + G(B, C, D) + d[3] + 0x5a827999), 3); - D = rotintlft((D + G(A, B, C) + d[7] + 0x5a827999), 5); - C = rotintlft((C + G(D, A, B) + d[11] + 0x5a827999), 9); - B = rotintlft((B + G(C, D, A) + d[15] + 0x5a827999), 13); - - } - - protected void round3(final int[] d) { - A = rotintlft((A + H(B, C, D) + d[0] + 0x6ed9eba1), 3); - D = rotintlft((D + H(A, B, C) + d[8] + 0x6ed9eba1), 9); - C = rotintlft((C + H(D, A, B) + d[4] + 0x6ed9eba1), 11); - B = rotintlft((B + H(C, D, A) + d[12] + 0x6ed9eba1), 15); - - A = rotintlft((A + H(B, C, D) + d[2] + 0x6ed9eba1), 3); - D = rotintlft((D + H(A, B, C) + d[10] + 0x6ed9eba1), 9); - C = rotintlft((C + H(D, A, B) + d[6] + 0x6ed9eba1), 11); - B = rotintlft((B + H(C, D, A) + d[14] + 0x6ed9eba1), 15); - - A = rotintlft((A + H(B, C, D) + d[1] + 0x6ed9eba1), 3); - D = rotintlft((D + H(A, B, C) + d[9] + 0x6ed9eba1), 9); - C = rotintlft((C + H(D, A, B) + d[5] + 0x6ed9eba1), 11); - B = rotintlft((B + H(C, D, A) + d[13] + 0x6ed9eba1), 15); - - A = rotintlft((A + H(B, C, D) + d[3] + 0x6ed9eba1), 3); - D = rotintlft((D + H(A, B, C) + d[11] + 0x6ed9eba1), 9); - C = rotintlft((C + H(D, A, B) + d[7] + 0x6ed9eba1), 11); - B = rotintlft((B + H(C, D, A) + d[15] + 0x6ed9eba1), 15); - - } - - } - - /** - * Cryptography support - HMACMD5 - algorithmically based on various web - * resources by Karl Wright - */ - static class HMACMD5 { - protected byte[] ipad; - protected byte[] opad; - protected MessageDigest md5; - - HMACMD5(final byte[] input) throws NTLMEngineException { - byte[] key = input; - try { - md5 = MessageDigest.getInstance("MD5"); - } catch (final Exception ex) { - // Umm, the algorithm doesn't exist - throw an - // NTLMEngineException! - throw new NTLMEngineException( - "Error getting md5 message digest implementation: " + ex.getMessage(), ex); - } - - // Initialize the pad buffers with the key - ipad = new byte[64]; - opad = new byte[64]; - - int keyLength = key.length; - if (keyLength > 64) { - // Use MD5 of the key instead, as described in RFC 2104 - md5.update(key); - key = md5.digest(); - keyLength = key.length; - } - int i = 0; - while (i < keyLength) { - ipad[i] = (byte) (key[i] ^ (byte) 0x36); - opad[i] = (byte) (key[i] ^ (byte) 0x5c); - i++; - } - while (i < 64) { - ipad[i] = (byte) 0x36; - opad[i] = (byte) 0x5c; - i++; - } - - // Very important: update the digest with the ipad buffer - md5.reset(); - md5.update(ipad); - - } - - /** Grab the current digest. This is the "answer". */ - byte[] getOutput() { - final byte[] digest = md5.digest(); - md5.update(opad); - return md5.digest(digest); - } - - /** Update by adding a complete array */ - void update(final byte[] input) { - md5.update(input); - } - - /** Update the algorithm */ - void update(final byte[] input, final int offset, final int length) { - md5.update(input, offset, length); - } - - } - - @Override - public String generateType1Msg( - final String domain, - final String workstation) throws NTLMEngineException { - return getType1Message(workstation, domain); - } - - @Override - public String generateType3Msg( - final String username, - final String password, - final String domain, - final String workstation, - final String challenge) throws NTLMEngineException { - final Type2Message t2m = new Type2Message(challenge); - return getType3Message( - username, - password, - workstation, - domain, - t2m.getChallenge(), - t2m.getFlags(), - t2m.getTarget(), - t2m.getTargetInfo()); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/NTLMScheme.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/NTLMScheme.java deleted file mode 100644 index 93f33e7a..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/NTLMScheme.java +++ /dev/null @@ -1,171 +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 com.tracelytics.ext.apache.http.impl.auth; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.message.BufferedHeader; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -import com.tracelytics.ext.apache.http.auth.AUTH; -import com.tracelytics.ext.apache.http.auth.AuthenticationException; -import com.tracelytics.ext.apache.http.auth.Credentials; -import com.tracelytics.ext.apache.http.auth.InvalidCredentialsException; -import com.tracelytics.ext.apache.http.auth.MalformedChallengeException; -import com.tracelytics.ext.apache.http.auth.NTCredentials; - -/** - * NTLM is a proprietary authentication scheme developed by Microsoft - * and optimized for Windows platforms. - * - * @since 4.0 - */ -@NotThreadSafe -public class NTLMScheme extends AuthSchemeBase { - - enum State { - UNINITIATED, - CHALLENGE_RECEIVED, - MSG_TYPE1_GENERATED, - MSG_TYPE2_RECEVIED, - MSG_TYPE3_GENERATED, - FAILED, - } - - private final NTLMEngine engine; - - private State state; - private String challenge; - - public NTLMScheme(final NTLMEngine engine) { - super(); - Args.notNull(engine, "NTLM engine"); - this.engine = engine; - this.state = State.UNINITIATED; - this.challenge = null; - } - - /** - * @since 4.3 - */ - public NTLMScheme() { - this(new NTLMEngineImpl()); - } - - @Override - public String getSchemeName() { - return "ntlm"; - } - - @Override - public String getParameter(final String name) { - // String parameters not supported - return null; - } - - @Override - public String getRealm() { - // NTLM does not support the concept of an authentication realm - return null; - } - - @Override - public boolean isConnectionBased() { - return true; - } - - @Override - protected void parseChallenge( - final CharArrayBuffer buffer, - final int beginIndex, final int endIndex) throws MalformedChallengeException { - this.challenge = buffer.substringTrimmed(beginIndex, endIndex); - if (this.challenge.isEmpty()) { - if (this.state == State.UNINITIATED) { - this.state = State.CHALLENGE_RECEIVED; - } else { - this.state = State.FAILED; - } - } else { - if (this.state.compareTo(State.MSG_TYPE1_GENERATED) < 0) { - this.state = State.FAILED; - throw new MalformedChallengeException("Out of sequence NTLM response message"); - } else if (this.state == State.MSG_TYPE1_GENERATED) { - this.state = State.MSG_TYPE2_RECEVIED; - } - } - } - - @Override - public Header authenticate( - final Credentials credentials, - final HttpRequest request) throws AuthenticationException { - NTCredentials ntcredentials = null; - try { - ntcredentials = (NTCredentials) credentials; - } catch (final ClassCastException e) { - throw new InvalidCredentialsException( - "Credentials cannot be used for NTLM authentication: " - + credentials.getClass().getName()); - } - String response = null; - if (this.state == State.FAILED) { - throw new AuthenticationException("NTLM authentication failed"); - } else if (this.state == State.CHALLENGE_RECEIVED) { - response = this.engine.generateType1Msg( - ntcredentials.getDomain(), - ntcredentials.getWorkstation()); - this.state = State.MSG_TYPE1_GENERATED; - } else if (this.state == State.MSG_TYPE2_RECEVIED) { - response = this.engine.generateType3Msg( - ntcredentials.getUserName(), - ntcredentials.getPassword(), - ntcredentials.getDomain(), - ntcredentials.getWorkstation(), - this.challenge); - this.state = State.MSG_TYPE3_GENERATED; - } else { - throw new AuthenticationException("Unexpected state: " + this.state); - } - final CharArrayBuffer buffer = new CharArrayBuffer(32); - if (isProxy()) { - buffer.append(AUTH.PROXY_AUTH_RESP); - } else { - buffer.append(AUTH.WWW_AUTH_RESP); - } - buffer.append(": NTLM "); - buffer.append(response); - return new BufferedHeader(buffer); - } - - @Override - public boolean isComplete() { - return this.state == State.MSG_TYPE3_GENERATED || this.state == State.FAILED; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/NTLMSchemeFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/NTLMSchemeFactory.java deleted file mode 100644 index 07c88a22..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/NTLMSchemeFactory.java +++ /dev/null @@ -1,59 +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 com.tracelytics.ext.apache.http.impl.auth; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -import com.tracelytics.ext.apache.http.auth.AuthScheme; -import com.tracelytics.ext.apache.http.auth.AuthSchemeFactory; -import com.tracelytics.ext.apache.http.auth.AuthSchemeProvider; - -/** - * {@link AuthSchemeProvider} implementation that creates and initializes - * {@link NTLMScheme} instances configured to use the default {@link NTLMEngine} - * implementation. - * - * @since 4.1 - */ -@Immutable -@SuppressWarnings("deprecation") -public class NTLMSchemeFactory implements AuthSchemeFactory, AuthSchemeProvider { - - @Override - public AuthScheme newInstance(final HttpParams params) { - return new NTLMScheme(); - } - - @Override - public AuthScheme create(final HttpContext context) { - return new NTLMScheme(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/RFC2617Scheme.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/RFC2617Scheme.java deleted file mode 100644 index e0feeb63..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/RFC2617Scheme.java +++ /dev/null @@ -1,176 +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 com.tracelytics.ext.apache.http.impl.auth; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.ObjectStreamException; -import java.io.Serializable; -import java.nio.charset.Charset; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -import com.tracelytics.ext.apache.http.Consts; -import com.tracelytics.ext.apache.http.HeaderElement; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.message.BasicHeaderValueParser; -import com.tracelytics.ext.apache.http.message.HeaderValueParser; -import com.tracelytics.ext.apache.http.message.ParserCursor; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; -import com.tracelytics.ext.apache.http.util.CharsetUtils; - -import com.tracelytics.ext.apache.http.auth.ChallengeState; -import com.tracelytics.ext.apache.http.auth.MalformedChallengeException; -import com.tracelytics.ext.apache.http.auth.params.AuthPNames; - -/** - * Abstract authentication scheme class that lays foundation for all - * RFC 2617 compliant authentication schemes and provides capabilities common - * to all authentication schemes defined in RFC 2617. - * - * @since 4.0 - */ -@SuppressWarnings("deprecation") -@NotThreadSafe // AuthSchemeBase, params -public abstract class RFC2617Scheme extends AuthSchemeBase implements Serializable { - - private static final long serialVersionUID = -2845454858205884623L; - - private final Map params; - private transient Charset credentialsCharset; - - /** - * Creates an instance of {@code RFC2617Scheme} with the given challenge - * state. - * - * @since 4.2 - * - * @deprecated (4.3) do not use. - */ - @Deprecated - public RFC2617Scheme(final ChallengeState challengeState) { - super(challengeState); - this.params = new HashMap(); - this.credentialsCharset = Consts.ASCII; - } - - /** - * @since 4.3 - */ - public RFC2617Scheme(final Charset credentialsCharset) { - super(); - this.params = new HashMap(); - this.credentialsCharset = credentialsCharset != null ? credentialsCharset : Consts.ASCII; - } - - public RFC2617Scheme() { - this(Consts.ASCII); - } - - - /** - * @since 4.3 - */ - public Charset getCredentialsCharset() { - return credentialsCharset != null ? credentialsCharset : Consts.ASCII; - } - - String getCredentialsCharset(final HttpRequest request) { - String charset = (String) request.getParams().getParameter(AuthPNames.CREDENTIAL_CHARSET); - if (charset == null) { - charset = getCredentialsCharset().name(); - } - return charset; - } - - @Override - protected void parseChallenge( - final CharArrayBuffer buffer, final int pos, final int len) throws MalformedChallengeException { - final HeaderValueParser parser = BasicHeaderValueParser.INSTANCE; - final ParserCursor cursor = new ParserCursor(pos, buffer.length()); - final HeaderElement[] elements = parser.parseElements(buffer, cursor); - this.params.clear(); - for (final HeaderElement element : elements) { - this.params.put(element.getName().toLowerCase(Locale.ROOT), element.getValue()); - } - } - - /** - * Returns authentication parameters map. Keys in the map are lower-cased. - * - * @return the map of authentication parameters - */ - protected Map getParameters() { - return this.params; - } - - /** - * Returns authentication parameter with the given name, if available. - * - * @param name The name of the parameter to be returned - * - * @return the parameter with the given name - */ - @Override - public String getParameter(final String name) { - if (name == null) { - return null; - } - return this.params.get(name.toLowerCase(Locale.ROOT)); - } - - /** - * Returns authentication realm. The realm may not be null. - * - * @return the authentication realm - */ - @Override - public String getRealm() { - return getParameter("realm"); - } - - private void writeObject(final ObjectOutputStream out) throws IOException { - out.defaultWriteObject(); - out.writeUTF(this.credentialsCharset.name()); - } - - @SuppressWarnings("unchecked") - private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); - this.credentialsCharset = CharsetUtils.get(in.readUTF()); - if (this.credentialsCharset == null) { - this.credentialsCharset = Consts.ASCII; - } - } - - private void readObjectNoData() throws ObjectStreamException { - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/SPNegoScheme.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/SPNegoScheme.java deleted file mode 100644 index 09523430..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/SPNegoScheme.java +++ /dev/null @@ -1,134 +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 com.tracelytics.ext.apache.http.impl.auth; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.util.Args; -import org.ietf.jgss.GSSException; -import org.ietf.jgss.Oid; - -import com.tracelytics.ext.apache.http.auth.AuthenticationException; -import com.tracelytics.ext.apache.http.auth.Credentials; - -/** - * SPNEGO (Simple and Protected GSSAPI Negotiation Mechanism) authentication - * scheme. - * - * @since 4.2 - */ -@NotThreadSafe -public class SPNegoScheme extends GGSSchemeBase { - - private static final String SPNEGO_OID = "1.3.6.1.5.5.2"; - - /** - * @since 4.4 - */ - public SPNegoScheme(final boolean stripPort, final boolean useCanonicalHostname) { - super(stripPort, useCanonicalHostname); - } - - public SPNegoScheme(final boolean stripPort) { - super(stripPort); - } - - public SPNegoScheme() { - super(); - } - - @Override - public String getSchemeName() { - return "Negotiate"; - } - - /** - * Produces SPNEGO authorization Header based on token created by - * processChallenge. - * - * @param credentials not used by the SPNEGO scheme. - * @param request The request being authenticated - * - * @throws AuthenticationException if authentication string cannot - * be generated due to an authentication failure - * - * @return SPNEGO authentication Header - */ - @Override - public Header authenticate( - final Credentials credentials, - final HttpRequest request, - final HttpContext context) throws AuthenticationException { - return super.authenticate(credentials, request, context); - } - - @Override @SuppressWarnings("deprecation") - protected byte[] generateToken(final byte[] input, final String authServer) throws GSSException { - return super.generateToken(input, authServer); - } - - @Override - protected byte[] generateToken(final byte[] input, final String authServer, final Credentials credentials) throws GSSException { - return generateGSSToken(input, new Oid(SPNEGO_OID), authServer, credentials); - } - - /** - * There are no valid parameters for SPNEGO authentication so this - * method always returns {@code null}. - * - * @return {@code null} - */ - @Override - public String getParameter(final String name) { - Args.notNull(name, "Parameter name"); - return null; - } - - /** - * The concept of an authentication realm is not supported by the Negotiate - * authentication scheme. Always returns {@code null}. - * - * @return {@code null} - */ - @Override - public String getRealm() { - return null; - } - - /** - * Returns {@code true}. SPNEGO authentication scheme is connection based. - * - * @return {@code true}. - */ - @Override - public boolean isConnectionBased() { - return true; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/SPNegoSchemeFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/SPNegoSchemeFactory.java deleted file mode 100644 index 999d012e..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/SPNegoSchemeFactory.java +++ /dev/null @@ -1,87 +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 com.tracelytics.ext.apache.http.impl.auth; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -import com.tracelytics.ext.apache.http.auth.AuthScheme; -import com.tracelytics.ext.apache.http.auth.AuthSchemeFactory; -import com.tracelytics.ext.apache.http.auth.AuthSchemeProvider; - -/** - * {@link AuthSchemeProvider} implementation that creates and initializes - * {@link SPNegoScheme} instances. - * - * @since 4.2 - */ -@Immutable -@SuppressWarnings("deprecation") -public class SPNegoSchemeFactory implements AuthSchemeFactory, AuthSchemeProvider { - - private final boolean stripPort; - private final boolean useCanonicalHostname; - - /** - * @since 4.4 - */ - public SPNegoSchemeFactory(final boolean stripPort, final boolean useCanonicalHostname) { - super(); - this.stripPort = stripPort; - this.useCanonicalHostname = useCanonicalHostname; - } - - public SPNegoSchemeFactory(final boolean stripPort) { - super(); - this.stripPort = stripPort; - this.useCanonicalHostname = true; - } - - public SPNegoSchemeFactory() { - this(true, true); - } - - public boolean isStripPort() { - return stripPort; - } - - public boolean isUseCanonicalHostname() { - return useCanonicalHostname; - } - - @Override - public AuthScheme newInstance(final HttpParams params) { - return new SPNegoScheme(this.stripPort, this.useCanonicalHostname); - } - - @Override - public AuthScheme create(final HttpContext context) { - return new SPNegoScheme(this.stripPort, this.useCanonicalHostname); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/UnsupportedDigestAlgorithmException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/UnsupportedDigestAlgorithmException.java deleted file mode 100644 index e16a3d0c..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/UnsupportedDigestAlgorithmException.java +++ /dev/null @@ -1,69 +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 com.tracelytics.ext.apache.http.impl.auth; - -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * Authentication credentials required to respond to a authentication - * challenge are invalid - * - * - * @since 4.0 - */ -@Immutable -public class UnsupportedDigestAlgorithmException extends RuntimeException { - - private static final long serialVersionUID = 319558534317118022L; - - /** - * Creates a new UnsupportedAuthAlgoritmException with a {@code null} detail message. - */ - public UnsupportedDigestAlgorithmException() { - super(); - } - - /** - * Creates a new UnsupportedAuthAlgoritmException with the specified message. - * - * @param message the exception detail message - */ - public UnsupportedDigestAlgorithmException(final String message) { - super(message); - } - - /** - * Creates a new UnsupportedAuthAlgoritmException with the specified detail message and cause. - * - * @param message the exception detail message - * @param cause the {@code Throwable} that caused this exception, or {@code null} - * if the cause is unavailable, unknown, or not a {@code Throwable} - */ - public UnsupportedDigestAlgorithmException(final String message, final Throwable cause) { - super(message, cause); - } -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/package-info.java deleted file mode 100644 index ed775a08..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/auth/package-info.java +++ /dev/null @@ -1,32 +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 - * . - * - */ - -/** - * Default implementations of standard and common HTTP authentication - * schemes. - */ -package com.tracelytics.ext.apache.http.impl.auth; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/bootstrap/HttpServer.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/bootstrap/HttpServer.java deleted file mode 100644 index 46a03767..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/bootstrap/HttpServer.java +++ /dev/null @@ -1,179 +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 com.tracelytics.ext.apache.http.impl.bootstrap; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.ServerSocket; -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; - -import javax.net.ServerSocketFactory; -import javax.net.ssl.SSLServerSocket; - -import com.tracelytics.ext.apache.http.ExceptionLogger; -import com.tracelytics.ext.apache.http.HttpConnectionFactory; -import com.tracelytics.ext.apache.http.HttpServerConnection; -import com.tracelytics.ext.apache.http.config.SocketConfig; -import com.tracelytics.ext.apache.http.impl.DefaultBHttpServerConnection; -import com.tracelytics.ext.apache.http.protocol.HttpService; - -/** - * @since 4.4 - */ -public class HttpServer { - - enum Status { READY, ACTIVE, STOPPING } - - private final int port; - private final InetAddress ifAddress; - private final SocketConfig socketConfig; - private final ServerSocketFactory serverSocketFactory; - private final HttpService httpService; - private final HttpConnectionFactory connectionFactory; - private final SSLServerSetupHandler sslSetupHandler; - private final ExceptionLogger exceptionLogger; - private final ExecutorService listenerExecutorService; - private final ThreadGroup workerThreads; - private final ExecutorService workerExecutorService; - private final AtomicReference status; - - private volatile ServerSocket serverSocket; - private volatile RequestListener requestListener; - - HttpServer( - final int port, - final InetAddress ifAddress, - final SocketConfig socketConfig, - final ServerSocketFactory serverSocketFactory, - final HttpService httpService, - final HttpConnectionFactory connectionFactory, - final SSLServerSetupHandler sslSetupHandler, - final ExceptionLogger exceptionLogger) { - this.port = port; - this.ifAddress = ifAddress; - this.socketConfig = socketConfig; - this.serverSocketFactory = serverSocketFactory; - this.httpService = httpService; - this.connectionFactory = connectionFactory; - this.sslSetupHandler = sslSetupHandler; - this.exceptionLogger = exceptionLogger; - this.listenerExecutorService = Executors.newSingleThreadExecutor( - new ThreadFactoryImpl("HTTP-listener-" + this.port)); - this.workerThreads = new ThreadGroup("HTTP-workers"); - this.workerExecutorService = Executors.newCachedThreadPool( - new ThreadFactoryImpl("HTTP-worker", this.workerThreads)); - this.status = new AtomicReference(Status.READY); - } - - public InetAddress getInetAddress() { - final ServerSocket localSocket = this.serverSocket; - if (localSocket != null) { - return localSocket.getInetAddress(); - } else { - return null; - } - } - - public int getLocalPort() { - final ServerSocket localSocket = this.serverSocket; - if (localSocket != null) { - return localSocket.getLocalPort(); - } else { - return -1; - } - } - - public void start() throws IOException { - if (this.status.compareAndSet(Status.READY, Status.ACTIVE)) { - this.serverSocket = this.serverSocketFactory.createServerSocket( - this.port, this.socketConfig.getBacklogSize(), this.ifAddress); - this.serverSocket.setReuseAddress(this.socketConfig.isSoReuseAddress()); - if (this.socketConfig.getRcvBufSize() > 0) { - this.serverSocket.setReceiveBufferSize(this.socketConfig.getRcvBufSize()); - } - if (this.sslSetupHandler != null && this.serverSocket instanceof SSLServerSocket) { - this.sslSetupHandler.initialize((SSLServerSocket) this.serverSocket); - } - this.requestListener = new RequestListener( - this.socketConfig, - this.serverSocket, - this.httpService, - this.connectionFactory, - this.exceptionLogger, - this.workerExecutorService); - this.listenerExecutorService.execute(this.requestListener); - } - } - - public void stop() { - if (this.status.compareAndSet(Status.ACTIVE, Status.STOPPING)) { - final RequestListener local = this.requestListener; - if (local != null) { - try { - local.terminate(); - } catch (IOException ex) { - this.exceptionLogger.log(ex); - } - } - this.workerThreads.interrupt(); - this.listenerExecutorService.shutdown(); - this.workerExecutorService.shutdown(); - } - } - - public void awaitTermination(final long timeout, final TimeUnit timeUnit) throws InterruptedException { - this.workerExecutorService.awaitTermination(timeout, timeUnit); - } - - public void shutdown(final long gracePeriod, final TimeUnit timeUnit) { - stop(); - if (gracePeriod > 0) { - try { - awaitTermination(gracePeriod, timeUnit); - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - } - } - final List runnables = this.workerExecutorService.shutdownNow(); - for (Runnable runnable: runnables) { - if (runnable instanceof Worker) { - final Worker worker = (Worker) runnable; - final HttpServerConnection conn = worker.getConnection(); - try { - conn.shutdown(); - } catch (IOException ex) { - this.exceptionLogger.log(ex); - } - } - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/bootstrap/RequestListener.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/bootstrap/RequestListener.java deleted file mode 100644 index 07889fc1..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/bootstrap/RequestListener.java +++ /dev/null @@ -1,106 +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 com.tracelytics.ext.apache.http.impl.bootstrap; - -import java.io.IOException; -import java.net.ServerSocket; -import java.net.Socket; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.atomic.AtomicBoolean; - -import com.tracelytics.ext.apache.http.ExceptionLogger; -import com.tracelytics.ext.apache.http.HttpConnectionFactory; -import com.tracelytics.ext.apache.http.HttpServerConnection; -import com.tracelytics.ext.apache.http.config.SocketConfig; -import com.tracelytics.ext.apache.http.protocol.HttpService; - -/** - * @since 4.4 - */ -class RequestListener implements Runnable { - - private final SocketConfig socketConfig; - private final ServerSocket serversocket; - private final HttpService httpService; - private final HttpConnectionFactory connectionFactory; - private final ExceptionLogger exceptionLogger; - private final ExecutorService executorService; - private final AtomicBoolean terminated; - - public RequestListener( - final SocketConfig socketConfig, - final ServerSocket serversocket, - final HttpService httpService, - final HttpConnectionFactory connectionFactory, - final ExceptionLogger exceptionLogger, - final ExecutorService executorService) { - this.socketConfig = socketConfig; - this.serversocket = serversocket; - this.connectionFactory = connectionFactory; - this.httpService = httpService; - this.exceptionLogger = exceptionLogger; - this.executorService = executorService; - this.terminated = new AtomicBoolean(false); - } - - @Override - public void run() { - try { - while (!isTerminated() && !Thread.interrupted()) { - final Socket socket = this.serversocket.accept(); - socket.setSoTimeout(this.socketConfig.getSoTimeout()); - socket.setKeepAlive(this.socketConfig.isSoKeepAlive()); - socket.setTcpNoDelay(this.socketConfig.isTcpNoDelay()); - if (this.socketConfig.getRcvBufSize() > 0) { - socket.setReceiveBufferSize(this.socketConfig.getRcvBufSize()); - } - if (this.socketConfig.getSndBufSize() > 0) { - socket.setSendBufferSize(this.socketConfig.getSndBufSize()); - } - if (this.socketConfig.getSoLinger() >= 0) { - socket.setSoLinger(true, this.socketConfig.getSoLinger()); - } - final HttpServerConnection conn = this.connectionFactory.createConnection(socket); - final Worker worker = new Worker(this.httpService, conn, this.exceptionLogger); - this.executorService.execute(worker); - } - } catch (Exception ex) { - this.exceptionLogger.log(ex); - } - } - - public boolean isTerminated() { - return this.terminated.get(); - } - - public void terminate() throws IOException { - if (this.terminated.compareAndSet(false, true)) { - this.serversocket.close(); - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/bootstrap/SSLServerSetupHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/bootstrap/SSLServerSetupHandler.java deleted file mode 100644 index 7d8709f2..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/bootstrap/SSLServerSetupHandler.java +++ /dev/null @@ -1,45 +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 com.tracelytics.ext.apache.http.impl.bootstrap; - -import javax.net.ssl.SSLException; -import javax.net.ssl.SSLServerSocket; - -/** - * Server SSL setup handler. Custom implementations of this interface can be used to - * configure various SSL protocol aspects such as supported protocol versions, cypher suites, - * and mandatory / optional client authentication. - * - * @see javax.net.ssl.SSLServerSocket - * @see javax.net.ssl.SSLSession - * @since 4.4 - */ -public interface SSLServerSetupHandler { - - void initialize(SSLServerSocket socket) throws SSLException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/bootstrap/ServerBootstrap.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/bootstrap/ServerBootstrap.java deleted file mode 100644 index 36a6ae1a..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/bootstrap/ServerBootstrap.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 com.tracelytics.ext.apache.http.impl.bootstrap; - -import java.net.InetAddress; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.Map; - -import javax.net.ServerSocketFactory; -import javax.net.ssl.SSLContext; - -import com.tracelytics.ext.apache.http.ConnectionReuseStrategy; -import com.tracelytics.ext.apache.http.ExceptionLogger; -import com.tracelytics.ext.apache.http.HttpConnectionFactory; -import com.tracelytics.ext.apache.http.HttpRequestInterceptor; -import com.tracelytics.ext.apache.http.HttpResponseFactory; -import com.tracelytics.ext.apache.http.HttpResponseInterceptor; -import com.tracelytics.ext.apache.http.config.ConnectionConfig; -import com.tracelytics.ext.apache.http.config.SocketConfig; -import com.tracelytics.ext.apache.http.impl.DefaultBHttpServerConnection; -import com.tracelytics.ext.apache.http.impl.DefaultBHttpServerConnectionFactory; -import com.tracelytics.ext.apache.http.impl.DefaultConnectionReuseStrategy; -import com.tracelytics.ext.apache.http.impl.DefaultHttpResponseFactory; -import com.tracelytics.ext.apache.http.protocol.HttpExpectationVerifier; -import com.tracelytics.ext.apache.http.protocol.HttpProcessor; -import com.tracelytics.ext.apache.http.protocol.HttpProcessorBuilder; -import com.tracelytics.ext.apache.http.protocol.HttpRequestHandler; -import com.tracelytics.ext.apache.http.protocol.HttpRequestHandlerMapper; -import com.tracelytics.ext.apache.http.protocol.HttpService; -import com.tracelytics.ext.apache.http.protocol.ResponseConnControl; -import com.tracelytics.ext.apache.http.protocol.ResponseContent; -import com.tracelytics.ext.apache.http.protocol.ResponseDate; -import com.tracelytics.ext.apache.http.protocol.ResponseServer; -import com.tracelytics.ext.apache.http.protocol.UriHttpRequestHandlerMapper; - -/** - * @since 4.4 - */ -public class ServerBootstrap { - - private int listenerPort; - private InetAddress localAddress; - private SocketConfig socketConfig; - private ConnectionConfig connectionConfig; - private LinkedList requestFirst; - private LinkedList requestLast; - private LinkedList responseFirst; - private LinkedList responseLast; - private String serverInfo; - private HttpProcessor httpProcessor; - private ConnectionReuseStrategy connStrategy; - private HttpResponseFactory responseFactory; - private HttpRequestHandlerMapper handlerMapper; - private Map handlerMap; - private HttpExpectationVerifier expectationVerifier; - private ServerSocketFactory serverSocketFactory; - private SSLContext sslContext; - private SSLServerSetupHandler sslSetupHandler; - private HttpConnectionFactory connectionFactory; - private ExceptionLogger exceptionLogger; - - private ServerBootstrap() { - } - - public static ServerBootstrap bootstrap() { - return new ServerBootstrap(); - } - - /** - * Sets listener port number. - */ - public final ServerBootstrap setListenerPort(final int listenerPort) { - this.listenerPort = listenerPort; - return this; - } - - /** - * Assigns local interface for the listener. - */ - public final ServerBootstrap setLocalAddress(final InetAddress localAddress) { - this.localAddress = localAddress; - return this; - } - - /** - * Sets socket configuration. - */ - public final ServerBootstrap setSocketConfig(final SocketConfig socketConfig) { - this.socketConfig = socketConfig; - return this; - } - - /** - * Sets connection configuration. - *

- * Please note this value can be overridden by the {@link #setConnectionFactory( - * com.tracelytics.ext.apache.http.HttpConnectionFactory)} method. - */ - public final ServerBootstrap setConnectionConfig(final ConnectionConfig connectionConfig) { - this.connectionConfig = connectionConfig; - return this; - } - - /** - * Assigns {@link HttpProcessor} instance. - */ - public final ServerBootstrap setHttpProcessor(final HttpProcessor httpProcessor) { - this.httpProcessor = httpProcessor; - return this; - } - - /** - * Adds this protocol interceptor to the head of the protocol processing list. - *

- * Please note this value can be overridden by the {@link #setHttpProcessor( - * com.tracelytics.ext.apache.http.protocol.HttpProcessor)} method. - */ - public final ServerBootstrap addInterceptorFirst(final HttpResponseInterceptor itcp) { - if (itcp == null) { - return this; - } - if (responseFirst == null) { - responseFirst = new LinkedList(); - } - responseFirst.addFirst(itcp); - return this; - } - - /** - * Adds this protocol interceptor to the tail of the protocol processing list. - *

- * Please note this value can be overridden by the {@link #setHttpProcessor( - * com.tracelytics.ext.apache.http.protocol.HttpProcessor)} method. - */ - public final ServerBootstrap addInterceptorLast(final HttpResponseInterceptor itcp) { - if (itcp == null) { - return this; - } - if (responseLast == null) { - responseLast = new LinkedList(); - } - responseLast.addLast(itcp); - return this; - } - - /** - * Adds this protocol interceptor to the head of the protocol processing list. - *

- * Please note this value can be overridden by the {@link #setHttpProcessor( - * com.tracelytics.ext.apache.http.protocol.HttpProcessor)} method. - */ - public final ServerBootstrap addInterceptorFirst(final HttpRequestInterceptor itcp) { - if (itcp == null) { - return this; - } - if (requestFirst == null) { - requestFirst = new LinkedList(); - } - requestFirst.addFirst(itcp); - return this; - } - - /** - * Adds this protocol interceptor to the tail of the protocol processing list. - *

- * Please note this value can be overridden by the {@link #setHttpProcessor( - * com.tracelytics.ext.apache.http.protocol.HttpProcessor)} method. - */ - public final ServerBootstrap addInterceptorLast(final HttpRequestInterceptor itcp) { - if (itcp == null) { - return this; - } - if (requestLast == null) { - requestLast = new LinkedList(); - } - requestLast.addLast(itcp); - return this; - } - - /** - * Assigns {@code Server} response header value. - *

- * Please note this value can be overridden by the {@link #setHttpProcessor( - * com.tracelytics.ext.apache.http.protocol.HttpProcessor)} method. - */ - public final ServerBootstrap setServerInfo(final String serverInfo) { - this.serverInfo = serverInfo; - return this; - } - - /** - * Assigns {@link ConnectionReuseStrategy} instance. - */ - public final ServerBootstrap setConnectionReuseStrategy(final ConnectionReuseStrategy connStrategy) { - this.connStrategy = connStrategy; - return this; - } - - /** - * Assigns {@link HttpResponseFactory} instance. - */ - public final ServerBootstrap setResponseFactory(final HttpResponseFactory responseFactory) { - this.responseFactory = responseFactory; - return this; - } - - /** - * Assigns {@link HttpRequestHandlerMapper} instance. - */ - public final ServerBootstrap setHandlerMapper(final HttpRequestHandlerMapper handlerMapper) { - this.handlerMapper = handlerMapper; - return this; - } - - /** - * Registers the given {@link HttpRequestHandler} as a handler for URIs - * matching the given pattern. - *

- * Please note this value can be overridden by the {@link #setHandlerMapper( - * com.tracelytics.ext.apache.http.protocol.HttpRequestHandlerMapper)} method. - * - * @param pattern the pattern to register the handler for. - * @param handler the handler. - */ - public final ServerBootstrap registerHandler(final String pattern, final HttpRequestHandler handler) { - if (pattern == null || handler == null) { - return this; - } - if (handlerMap == null) { - handlerMap = new HashMap(); - } - handlerMap.put(pattern, handler); - return this; - } - - /** - * Assigns {@link HttpExpectationVerifier} instance. - */ - public final ServerBootstrap setExpectationVerifier(final HttpExpectationVerifier expectationVerifier) { - this.expectationVerifier = expectationVerifier; - return this; - } - - /** - * Assigns {@link HttpConnectionFactory} instance. - */ - public final ServerBootstrap setConnectionFactory( - final HttpConnectionFactory connectionFactory) { - this.connectionFactory = connectionFactory; - return this; - } - - /** - * Assigns {@link com.tracelytics.ext.apache.http.impl.bootstrap.SSLServerSetupHandler} instance. - */ - public final ServerBootstrap setSslSetupHandler(final SSLServerSetupHandler sslSetupHandler) { - this.sslSetupHandler = sslSetupHandler; - return this; - } - - /** - * Assigns {@link javax.net.ServerSocketFactory} instance. - */ - public final ServerBootstrap setServerSocketFactory(final ServerSocketFactory serverSocketFactory) { - this.serverSocketFactory = serverSocketFactory; - return this; - } - - /** - * Assigns {@link javax.net.ssl.SSLContext} instance. - *

- * Please note this value can be overridden by the {@link #setServerSocketFactory( - * javax.net.ServerSocketFactory)} method. - */ - public final ServerBootstrap setSslContext(final SSLContext sslContext) { - this.sslContext = sslContext; - return this; - } - - /** - * Assigns {@link com.tracelytics.ext.apache.http.ExceptionLogger} instance. - */ - public final ServerBootstrap setExceptionLogger(final ExceptionLogger exceptionLogger) { - this.exceptionLogger = exceptionLogger; - return this; - } - - public HttpServer create() { - - HttpProcessor httpProcessorCopy = this.httpProcessor; - if (httpProcessorCopy == null) { - - final HttpProcessorBuilder b = HttpProcessorBuilder.create(); - if (requestFirst != null) { - for (final HttpRequestInterceptor i: requestFirst) { - b.addFirst(i); - } - } - if (responseFirst != null) { - for (final HttpResponseInterceptor i: responseFirst) { - b.addFirst(i); - } - } - - String serverInfoCopy = this.serverInfo; - if (serverInfoCopy == null) { - serverInfoCopy = "Apache-HttpCore/1.1"; - } - - b.addAll( - new ResponseDate(), - new ResponseServer(serverInfoCopy), - new ResponseContent(), - new ResponseConnControl()); - if (requestLast != null) { - for (final HttpRequestInterceptor i: requestLast) { - b.addLast(i); - } - } - if (responseLast != null) { - for (final HttpResponseInterceptor i: responseLast) { - b.addLast(i); - } - } - httpProcessorCopy = b.build(); - } - - HttpRequestHandlerMapper handlerMapperCopy = this.handlerMapper; - if (handlerMapperCopy == null) { - final UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); - if (handlerMap != null) { - for (Map.Entry entry: handlerMap.entrySet()) { - reqistry.register(entry.getKey(), entry.getValue()); - } - } - handlerMapperCopy = reqistry; - } - - ConnectionReuseStrategy connStrategyCopy = this.connStrategy; - if (connStrategyCopy == null) { - connStrategyCopy = DefaultConnectionReuseStrategy.INSTANCE; - } - - HttpResponseFactory responseFactoryCopy = this.responseFactory; - if (responseFactoryCopy == null) { - responseFactoryCopy = DefaultHttpResponseFactory.INSTANCE; - } - - final HttpService httpService = new HttpService( - httpProcessorCopy, connStrategyCopy, responseFactoryCopy, handlerMapperCopy, - this.expectationVerifier); - - ServerSocketFactory serverSocketFactoryCopy = this.serverSocketFactory; - if (serverSocketFactoryCopy == null) { - if (this.sslContext != null) { - serverSocketFactoryCopy = this.sslContext.getServerSocketFactory(); - } else { - serverSocketFactoryCopy = ServerSocketFactory.getDefault(); - } - } - - HttpConnectionFactory connectionFactoryCopy = this.connectionFactory; - if (connectionFactoryCopy == null) { - if (this.connectionConfig != null) { - connectionFactoryCopy = new DefaultBHttpServerConnectionFactory(this.connectionConfig); - } else { - connectionFactoryCopy = DefaultBHttpServerConnectionFactory.INSTANCE; - } - } - - ExceptionLogger exceptionLoggerCopy = this.exceptionLogger; - if (exceptionLoggerCopy == null) { - exceptionLoggerCopy = ExceptionLogger.NO_OP; - } - - return new HttpServer( - this.listenerPort > 0 ? this.listenerPort : 0, - this.localAddress, - this.socketConfig != null ? this.socketConfig : SocketConfig.DEFAULT, - serverSocketFactoryCopy, - httpService, - connectionFactoryCopy, - this.sslSetupHandler, - exceptionLoggerCopy); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/bootstrap/ThreadFactoryImpl.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/bootstrap/ThreadFactoryImpl.java deleted file mode 100644 index 4b8303eb..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/bootstrap/ThreadFactoryImpl.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 com.tracelytics.ext.apache.http.impl.bootstrap; - -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.atomic.AtomicLong; - -/** - * @since 4.4 - */ -class ThreadFactoryImpl implements ThreadFactory { - - private final String namePrefix; - private final ThreadGroup group; - private final AtomicLong count; - - ThreadFactoryImpl(final String namePrefix, final ThreadGroup group) { - this.namePrefix = namePrefix; - this.group = group; - this.count = new AtomicLong(); - } - - ThreadFactoryImpl(final String namePrefix) { - this(namePrefix, null); - } - - @Override - public Thread newThread(final Runnable target) { - return new Thread(this.group, target, this.namePrefix + "-" + this.count.incrementAndGet()); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/bootstrap/Worker.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/bootstrap/Worker.java deleted file mode 100644 index d7470c73..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/bootstrap/Worker.java +++ /dev/null @@ -1,81 +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 com.tracelytics.ext.apache.http.impl.bootstrap; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.ExceptionLogger; -import com.tracelytics.ext.apache.http.HttpServerConnection; -import com.tracelytics.ext.apache.http.protocol.BasicHttpContext; -import com.tracelytics.ext.apache.http.protocol.HttpCoreContext; -import com.tracelytics.ext.apache.http.protocol.HttpService; - -/** - * @since 4.4 - */ -class Worker implements Runnable { - - private final HttpService httpservice; - private final HttpServerConnection conn; - private final ExceptionLogger exceptionLogger; - - Worker( - final HttpService httpservice, - final HttpServerConnection conn, - final ExceptionLogger exceptionLogger) { - super(); - this.httpservice = httpservice; - this.conn = conn; - this.exceptionLogger = exceptionLogger; - } - - public HttpServerConnection getConnection() { - return this.conn; - } - - @Override - public void run() { - try { - final BasicHttpContext localContext = new BasicHttpContext(); - final HttpCoreContext context = HttpCoreContext.adapt(localContext); - while (!Thread.interrupted() && this.conn.isOpen()) { - this.httpservice.handleRequest(this.conn, context); - localContext.clear(); - } - this.conn.close(); - } catch (Exception ex) { - this.exceptionLogger.log(ex); - } finally { - try { - this.conn.shutdown(); - } catch (IOException ex) { - this.exceptionLogger.log(ex); - } - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/bootstrap/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/bootstrap/package-info.java deleted file mode 100644 index 28ee7887..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/bootstrap/package-info.java +++ /dev/null @@ -1,31 +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 - * . - * - */ - -/** - * Embedded server and server bootstrap. - */ -package com.tracelytics.ext.apache.http.impl.bootstrap; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/AIMDBackoffManager.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/AIMDBackoffManager.java deleted file mode 100644 index 846e7736..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/AIMDBackoffManager.java +++ /dev/null @@ -1,167 +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 com.tracelytics.ext.apache.http.impl.client; - -import java.util.HashMap; -import java.util.Map; - -import com.tracelytics.ext.apache.http.pool.ConnPoolControl; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.client.BackoffManager; -import com.tracelytics.ext.apache.http.conn.routing.HttpRoute; - -/** - *

The {@code AIMDBackoffManager} applies an additive increase, - * multiplicative decrease (AIMD) to managing a dynamic limit to - * the number of connections allowed to a given host. You may want - * to experiment with the settings for the cooldown periods and the - * backoff factor to get the adaptive behavior you want.

- * - *

Generally speaking, shorter cooldowns will lead to more steady-state - * variability but faster reaction times, while longer cooldowns - * will lead to more stable equilibrium behavior but slower reaction - * times.

- * - *

Similarly, higher backoff factors promote greater - * utilization of available capacity at the expense of fairness - * among clients. Lower backoff factors allow equal distribution of - * capacity among clients (fairness) to happen faster, at the - * expense of having more server capacity unused in the short term.

- * - * @since 4.2 - */ -public class AIMDBackoffManager implements BackoffManager { - - private final ConnPoolControl connPerRoute; - private final Clock clock; - private final Map lastRouteProbes; - private final Map lastRouteBackoffs; - private long coolDown = 5 * 1000L; - private double backoffFactor = 0.5; - private int cap = 2; // Per RFC 2616 sec 8.1.4 - - /** - * Creates an {@code AIMDBackoffManager} to manage - * per-host connection pool sizes represented by the - * given {@link ConnPoolControl}. - * @param connPerRoute per-host routing maximums to - * be managed - */ - public AIMDBackoffManager(final ConnPoolControl connPerRoute) { - this(connPerRoute, new SystemClock()); - } - - AIMDBackoffManager(final ConnPoolControl connPerRoute, final Clock clock) { - this.clock = clock; - this.connPerRoute = connPerRoute; - this.lastRouteProbes = new HashMap(); - this.lastRouteBackoffs = new HashMap(); - } - - @Override - public void backOff(final HttpRoute route) { - synchronized(connPerRoute) { - final int curr = connPerRoute.getMaxPerRoute(route); - final Long lastUpdate = getLastUpdate(lastRouteBackoffs, route); - final long now = clock.getCurrentTime(); - if (now - lastUpdate.longValue() < coolDown) { - return; - } - connPerRoute.setMaxPerRoute(route, getBackedOffPoolSize(curr)); - lastRouteBackoffs.put(route, Long.valueOf(now)); - } - } - - private int getBackedOffPoolSize(final int curr) { - if (curr <= 1) { - return 1; - } - return (int)(Math.floor(backoffFactor * curr)); - } - - @Override - public void probe(final HttpRoute route) { - synchronized(connPerRoute) { - final int curr = connPerRoute.getMaxPerRoute(route); - final int max = (curr >= cap) ? cap : curr + 1; - final Long lastProbe = getLastUpdate(lastRouteProbes, route); - final Long lastBackoff = getLastUpdate(lastRouteBackoffs, route); - final long now = clock.getCurrentTime(); - if (now - lastProbe.longValue() < coolDown || now - lastBackoff.longValue() < coolDown) { - return; - } - connPerRoute.setMaxPerRoute(route, max); - lastRouteProbes.put(route, Long.valueOf(now)); - } - } - - private Long getLastUpdate(final Map updates, final HttpRoute route) { - Long lastUpdate = updates.get(route); - if (lastUpdate == null) { - lastUpdate = Long.valueOf(0L); - } - return lastUpdate; - } - - /** - * Sets the factor to use when backing off; the new - * per-host limit will be roughly the current max times - * this factor. {@code Math.floor} is applied in the - * case of non-integer outcomes to ensure we actually - * decrease the pool size. Pool sizes are never decreased - * below 1, however. Defaults to 0.5. - * @param d must be between 0.0 and 1.0, exclusive. - */ - public void setBackoffFactor(final double d) { - Args.check(d > 0.0 && d < 1.0, "Backoff factor must be 0.0 < f < 1.0"); - backoffFactor = d; - } - - /** - * Sets the amount of time, in milliseconds, to wait between - * adjustments in pool sizes for a given host, to allow - * enough time for the adjustments to take effect. Defaults - * to 5000L (5 seconds). - * @param l must be positive - */ - public void setCooldownMillis(final long l) { - Args.positive(coolDown, "Cool down"); - coolDown = l; - } - - /** - * Sets the absolute maximum per-host connection pool size to - * probe up to; defaults to 2 (the default per-host max). - * @param cap must be >= 1 - */ - public void setPerHostConnectionCap(final int cap) { - Args.positive(cap, "Per host connection cap"); - this.cap = cap; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/AbstractResponseHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/AbstractResponseHandler.java deleted file mode 100644 index f7948d71..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/AbstractResponseHandler.java +++ /dev/null @@ -1,82 +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 com.tracelytics.ext.apache.http.impl.client; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.StatusLine; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.EntityUtils; - -import com.tracelytics.ext.apache.http.client.HttpResponseException; -import com.tracelytics.ext.apache.http.client.ResponseHandler; - -/** - * A generic {@link ResponseHandler} that works with the response entity - * for successful (2xx) responses. If the response code was >= 300, the response - * body is consumed and an {@link HttpResponseException} is thrown. - *

- * If this is used with - * {@link com.tracelytics.ext.apache.http.client.HttpClient#execute( - * com.tracelytics.ext.apache.http.client.methods.HttpUriRequest, ResponseHandler)}, - * HttpClient may handle redirects (3xx responses) internally. - *

- * - * @since 4.4 - */ -@Immutable -public abstract class AbstractResponseHandler implements ResponseHandler { - - /** - * Read the entity from the response body and pass it to the entity handler - * method if the response was successful (a 2xx status code). If no response - * body exists, this returns null. If the response was unsuccessful (>= 300 - * status code), throws an {@link HttpResponseException}. - */ - @Override - public T handleResponse(final HttpResponse response) - throws HttpResponseException, IOException { - final StatusLine statusLine = response.getStatusLine(); - final HttpEntity entity = response.getEntity(); - if (statusLine.getStatusCode() >= 300) { - EntityUtils.consume(entity); - throw new HttpResponseException(statusLine.getStatusCode(), - statusLine.getReasonPhrase()); - } - return entity == null ? null : handleEntity(entity); - } - - /** - * Handle the response entity and transform it into the actual response - * object. - */ - public abstract T handleEntity(HttpEntity entity) throws IOException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/AuthenticationStrategyImpl.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/AuthenticationStrategyImpl.java deleted file mode 100644 index fa51b2ce..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/AuthenticationStrategyImpl.java +++ /dev/null @@ -1,260 +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 com.tracelytics.ext.apache.http.impl.client; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Queue; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.tracelytics.ext.apache.http.FormattedHeader; -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.auth.AuthOption; -import com.tracelytics.ext.apache.http.auth.AuthScheme; -import com.tracelytics.ext.apache.http.auth.AuthSchemeProvider; -import com.tracelytics.ext.apache.http.auth.AuthScope; -import com.tracelytics.ext.apache.http.auth.Credentials; -import com.tracelytics.ext.apache.http.auth.MalformedChallengeException; -import com.tracelytics.ext.apache.http.client.AuthCache; -import com.tracelytics.ext.apache.http.client.AuthenticationStrategy; -import com.tracelytics.ext.apache.http.client.CredentialsProvider; -import com.tracelytics.ext.apache.http.client.config.AuthSchemes; -import com.tracelytics.ext.apache.http.client.config.RequestConfig; -import com.tracelytics.ext.apache.http.client.protocol.HttpClientContext; -import com.tracelytics.ext.apache.http.config.Lookup; -import com.tracelytics.ext.apache.http.protocol.HTTP; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -@Immutable -abstract class AuthenticationStrategyImpl implements AuthenticationStrategy { - - private final Logger log = Logger.getLogger(getClass().getName()); - - private static final List DEFAULT_SCHEME_PRIORITY = - Collections.unmodifiableList(Arrays.asList( - AuthSchemes.SPNEGO, - AuthSchemes.KERBEROS, - AuthSchemes.NTLM, - AuthSchemes.DIGEST, - AuthSchemes.BASIC)); - - private final int challengeCode; - private final String headerName; - - /** - * @param challengeCode for example SC_PROXY_AUTHENTICATION_REQUIRED or SC_UNAUTHORIZED - * @param headerName for example "Proxy-Authenticate" or "WWW-Authenticate" - */ - AuthenticationStrategyImpl(final int challengeCode, final String headerName) { - super(); - this.challengeCode = challengeCode; - this.headerName = headerName; - } - - @Override - public boolean isAuthenticationRequested( - final HttpHost authhost, - final HttpResponse response, - final HttpContext context) { - Args.notNull(response, "HTTP response"); - final int status = response.getStatusLine().getStatusCode(); - return status == this.challengeCode; - } - - /** - * Generates a map of challenge auth-scheme => Header entries. - * - * @return map: key=lower-cased auth-scheme name, value=Header that contains the challenge - */ - @Override - public Map getChallenges( - final HttpHost authhost, - final HttpResponse response, - final HttpContext context) throws MalformedChallengeException { - Args.notNull(response, "HTTP response"); - final Header[] headers = response.getHeaders(this.headerName); - final Map map = new HashMap(headers.length); - for (final Header header : headers) { - final CharArrayBuffer buffer; - int pos; - if (header instanceof FormattedHeader) { - buffer = ((FormattedHeader) header).getBuffer(); - pos = ((FormattedHeader) header).getValuePos(); - } else { - final String s = header.getValue(); - if (s == null) { - throw new MalformedChallengeException("Header value is null"); - } - buffer = new CharArrayBuffer(s.length()); - buffer.append(s); - pos = 0; - } - while (pos < buffer.length() && HTTP.isWhitespace(buffer.charAt(pos))) { - pos++; - } - final int beginIndex = pos; - while (pos < buffer.length() && !HTTP.isWhitespace(buffer.charAt(pos))) { - pos++; - } - final int endIndex = pos; - final String s = buffer.substring(beginIndex, endIndex); - map.put(s.toLowerCase(Locale.ROOT), header); - } - return map; - } - - abstract Collection getPreferredAuthSchemes(RequestConfig config); - - @Override - public Queue select( - final Map challenges, - final HttpHost authhost, - final HttpResponse response, - final HttpContext context) throws MalformedChallengeException { - Args.notNull(challenges, "Map of auth challenges"); - Args.notNull(authhost, "Host"); - Args.notNull(response, "HTTP response"); - Args.notNull(context, "HTTP context"); - final HttpClientContext clientContext = HttpClientContext.adapt(context); - - final Queue options = new LinkedList(); - final Lookup registry = clientContext.getAuthSchemeRegistry(); - if (registry == null) { - this.log.log(Level.FINE, "Auth scheme registry not set in the context"); - return options; - } - final CredentialsProvider credsProvider = clientContext.getCredentialsProvider(); - if (credsProvider == null) { - this.log.log(Level.FINE, "Credentials provider not set in the context"); - return options; - } - final RequestConfig config = clientContext.getRequestConfig(); - Collection authPrefs = getPreferredAuthSchemes(config); - if (authPrefs == null) { - authPrefs = DEFAULT_SCHEME_PRIORITY; - } - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Authentication schemes in the order of preference: " + authPrefs); - } - - for (final String id: authPrefs) { - final Header challenge = challenges.get(id.toLowerCase(Locale.ROOT)); - if (challenge != null) { - final AuthSchemeProvider authSchemeProvider = registry.lookup(id); - if (authSchemeProvider == null) { - if (this.log.isLoggable(Level.WARNING)) { - this.log.log(Level.WARNING, "Authentication scheme " + id + " not supported"); - // Try again - } - continue; - } - final AuthScheme authScheme = authSchemeProvider.create(context); - authScheme.processChallenge(challenge); - - final AuthScope authScope = new AuthScope( - authhost.getHostName(), - authhost.getPort(), - authScheme.getRealm(), - authScheme.getSchemeName()); - - final Credentials credentials = credsProvider.getCredentials(authScope); - if (credentials != null) { - options.add(new AuthOption(authScheme, credentials)); - } - } else { - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Challenge for " + id + " authentication scheme not available"); - // Try again - } - } - } - return options; - } - - @Override - public void authSucceeded( - final HttpHost authhost, final AuthScheme authScheme, final HttpContext context) { - Args.notNull(authhost, "Host"); - Args.notNull(authScheme, "Auth scheme"); - Args.notNull(context, "HTTP context"); - - final HttpClientContext clientContext = HttpClientContext.adapt(context); - - if (isCachable(authScheme)) { - AuthCache authCache = clientContext.getAuthCache(); - if (authCache == null) { - authCache = new BasicAuthCache(); - clientContext.setAuthCache(authCache); - } - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Caching '" + authScheme.getSchemeName() + - "' auth scheme for " + authhost); - } - authCache.put(authhost, authScheme); - } - } - - protected boolean isCachable(final AuthScheme authScheme) { - if (authScheme == null || !authScheme.isComplete()) { - return false; - } - final String schemeName = authScheme.getSchemeName(); - return schemeName.equalsIgnoreCase(AuthSchemes.BASIC) || - schemeName.equalsIgnoreCase(AuthSchemes.DIGEST); - } - - @Override - public void authFailed( - final HttpHost authhost, final AuthScheme authScheme, final HttpContext context) { - Args.notNull(authhost, "Host"); - Args.notNull(context, "HTTP context"); - - final HttpClientContext clientContext = HttpClientContext.adapt(context); - - final AuthCache authCache = clientContext.getAuthCache(); - if (authCache != null) { - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Clearing cached auth scheme for " + authhost); - } - authCache.remove(authhost); - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/BasicAuthCache.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/BasicAuthCache.java deleted file mode 100644 index 3b398400..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/BasicAuthCache.java +++ /dev/null @@ -1,165 +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 com.tracelytics.ext.apache.http.impl.client; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.auth.AuthScheme; -import com.tracelytics.ext.apache.http.client.AuthCache; -import com.tracelytics.ext.apache.http.conn.SchemePortResolver; -import com.tracelytics.ext.apache.http.conn.UnsupportedSchemeException; -import com.tracelytics.ext.apache.http.impl.conn.DefaultSchemePortResolver; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Default implementation of {@link com.tracelytics.ext.apache.http.client.AuthCache}. This implements - * expects {@link com.tracelytics.ext.apache.http.auth.AuthScheme} to be {@link java.io.Serializable} - * in order to be cacheable. - *

- * Instances of this class are thread safe as of version 4.4. - *

- * - * @since 4.1 - */ -@ThreadSafe -public class BasicAuthCache implements AuthCache { - - private final Logger log = Logger.getLogger(getClass().getName()); - - private final Map map; - private final SchemePortResolver schemePortResolver; - - /** - * Default constructor. - * - * @since 4.3 - */ - public BasicAuthCache(final SchemePortResolver schemePortResolver) { - super(); - this.map = new ConcurrentHashMap(); - this.schemePortResolver = schemePortResolver != null ? schemePortResolver : - DefaultSchemePortResolver.INSTANCE; - } - - public BasicAuthCache() { - this(null); - } - - protected HttpHost getKey(final HttpHost host) { - if (host.getPort() <= 0) { - final int port; - try { - port = schemePortResolver.resolve(host); - } catch (final UnsupportedSchemeException ignore) { - return host; - } - return new HttpHost(host.getHostName(), port, host.getSchemeName()); - } else { - return host; - } - } - - @Override - public void put(final HttpHost host, final AuthScheme authScheme) { - Args.notNull(host, "HTTP host"); - if (authScheme == null) { - return; - } - if (authScheme instanceof Serializable) { - try { - final ByteArrayOutputStream buf = new ByteArrayOutputStream(); - final ObjectOutputStream out = new ObjectOutputStream(buf); - out.writeObject(authScheme); - out.close(); - this.map.put(getKey(host), buf.toByteArray()); - } catch (IOException ex) { - if (log.isLoggable(Level.WARNING)) { - log.log(Level.WARNING, "Unexpected I/O error while serializing auth scheme", ex); - } - } - } else { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Auth scheme " + authScheme.getClass() + " is not serializable"); - } - } - } - - @Override - public AuthScheme get(final HttpHost host) { - Args.notNull(host, "HTTP host"); - final byte[] bytes = this.map.get(getKey(host)); - if (bytes != null) { - try { - final ByteArrayInputStream buf = new ByteArrayInputStream(bytes); - final ObjectInputStream in = new ObjectInputStream(buf); - final AuthScheme authScheme = (AuthScheme) in.readObject(); - in.close(); - return authScheme; - } catch (IOException ex) { - if (log.isLoggable(Level.WARNING)) { - log.log(Level.WARNING, "Unexpected I/O error while de-serializing auth scheme", ex); - } - return null; - } catch (ClassNotFoundException ex) { - if (log.isLoggable(Level.WARNING)) { - log.log(Level.WARNING, "Unexpected error while de-serializing auth scheme", ex); - } - return null; - } - } else { - return null; - } - } - - @Override - public void remove(final HttpHost host) { - Args.notNull(host, "HTTP host"); - this.map.remove(getKey(host)); - } - - @Override - public void clear() { - this.map.clear(); - } - - @Override - public String toString() { - return this.map.toString(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/BasicCookieStore.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/BasicCookieStore.java deleted file mode 100644 index c169f6da..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/BasicCookieStore.java +++ /dev/null @@ -1,149 +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 com.tracelytics.ext.apache.http.impl.client; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Date; -import java.util.Iterator; -import java.util.List; -import java.util.TreeSet; - -import com.tracelytics.ext.apache.http.annotation.GuardedBy; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; - -import com.tracelytics.ext.apache.http.client.CookieStore; -import com.tracelytics.ext.apache.http.cookie.Cookie; -import com.tracelytics.ext.apache.http.cookie.CookieIdentityComparator; - -/** - * Default implementation of {@link CookieStore} - * - * - * @since 4.0 - */ -@ThreadSafe -public class BasicCookieStore implements CookieStore, Serializable { - - private static final long serialVersionUID = -7581093305228232025L; - - @GuardedBy("this") - private final TreeSet cookies; - - public BasicCookieStore() { - super(); - this.cookies = new TreeSet(new CookieIdentityComparator()); - } - - /** - * Adds an {@link Cookie HTTP cookie}, replacing any existing equivalent cookies. - * If the given cookie has already expired it will not be added, but existing - * values will still be removed. - * - * @param cookie the {@link Cookie cookie} to be added - * - * @see #addCookies(Cookie[]) - * - */ - @Override - public synchronized void addCookie(final Cookie cookie) { - if (cookie != null) { - // first remove any old cookie that is equivalent - cookies.remove(cookie); - if (!cookie.isExpired(new Date())) { - cookies.add(cookie); - } - } - } - - /** - * Adds an array of {@link Cookie HTTP cookies}. Cookies are added individually and - * in the given array order. If any of the given cookies has already expired it will - * not be added, but existing values will still be removed. - * - * @param cookies the {@link Cookie cookies} to be added - * - * @see #addCookie(Cookie) - * - */ - public synchronized void addCookies(final Cookie[] cookies) { - if (cookies != null) { - for (final Cookie cooky : cookies) { - this.addCookie(cooky); - } - } - } - - /** - * Returns an immutable array of {@link Cookie cookies} that this HTTP - * state currently contains. - * - * @return an array of {@link Cookie cookies}. - */ - @Override - public synchronized List getCookies() { - //create defensive copy so it won't be concurrently modified - return new ArrayList(cookies); - } - - /** - * Removes all of {@link Cookie cookies} in this HTTP state - * that have expired by the specified {@link java.util.Date date}. - * - * @return true if any cookies were purged. - * - * @see Cookie#isExpired(Date) - */ - @Override - public synchronized boolean clearExpired(final Date date) { - if (date == null) { - return false; - } - boolean removed = false; - for (final Iterator it = cookies.iterator(); it.hasNext();) { - if (it.next().isExpired(date)) { - it.remove(); - removed = true; - } - } - return removed; - } - - /** - * Clears all cookies. - */ - @Override - public synchronized void clear() { - cookies.clear(); - } - - @Override - public synchronized String toString() { - return cookies.toString(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/BasicCredentialsProvider.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/BasicCredentialsProvider.java deleted file mode 100644 index 9b452f73..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/BasicCredentialsProvider.java +++ /dev/null @@ -1,113 +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 com.tracelytics.ext.apache.http.impl.client; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.auth.AuthScope; -import com.tracelytics.ext.apache.http.auth.Credentials; -import com.tracelytics.ext.apache.http.client.CredentialsProvider; - -/** - * Default implementation of {@link CredentialsProvider}. - * - * @since 4.0 - */ -@ThreadSafe -public class BasicCredentialsProvider implements CredentialsProvider { - - private final ConcurrentHashMap credMap; - - /** - * Default constructor. - */ - public BasicCredentialsProvider() { - super(); - this.credMap = new ConcurrentHashMap(); - } - - @Override - public void setCredentials( - final AuthScope authscope, - final Credentials credentials) { - Args.notNull(authscope, "Authentication scope"); - credMap.put(authscope, credentials); - } - - /** - * Find matching {@link Credentials credentials} for the given authentication scope. - * - * @param map the credentials hash map - * @param authscope the {@link AuthScope authentication scope} - * @return the credentials - * - */ - private static Credentials matchCredentials( - final Map map, - final AuthScope authscope) { - // see if we get a direct hit - Credentials creds = map.get(authscope); - if (creds == null) { - // Nope. - // Do a full scan - int bestMatchFactor = -1; - AuthScope bestMatch = null; - for (final AuthScope current: map.keySet()) { - final int factor = authscope.match(current); - if (factor > bestMatchFactor) { - bestMatchFactor = factor; - bestMatch = current; - } - } - if (bestMatch != null) { - creds = map.get(bestMatch); - } - } - return creds; - } - - @Override - public Credentials getCredentials(final AuthScope authscope) { - Args.notNull(authscope, "Authentication scope"); - return matchCredentials(this.credMap, authscope); - } - - @Override - public void clear() { - this.credMap.clear(); - } - - @Override - public String toString() { - return credMap.toString(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/BasicResponseHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/BasicResponseHandler.java deleted file mode 100644 index 91d9f4aa..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/BasicResponseHandler.java +++ /dev/null @@ -1,69 +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 com.tracelytics.ext.apache.http.impl.client; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.EntityUtils; - -import com.tracelytics.ext.apache.http.client.HttpResponseException; - -/** - * A {@link com.tracelytics.ext.apache.http.client.ResponseHandler} that returns the response body as a String - * for successful (2xx) responses. If the response code was >= 300, the response - * body is consumed and an {@link com.tracelytics.ext.apache.http.client.HttpResponseException} is thrown. - *

- * If this is used with - * {@link com.tracelytics.ext.apache.http.client.HttpClient#execute( - * com.tracelytics.ext.apache.http.client.methods.HttpUriRequest, com.tracelytics.ext.apache.http.client.ResponseHandler)}, - * HttpClient may handle redirects (3xx responses) internally. - *

- * - * @since 4.0 - */ -@Immutable -public class BasicResponseHandler extends AbstractResponseHandler { - - /** - * Returns the entity as a body as a String. - */ - @Override - public String handleEntity(final HttpEntity entity) throws IOException { - return EntityUtils.toString(entity); - } - - @Override - public String handleResponse( - final HttpResponse response) throws HttpResponseException, IOException { - return super.handleResponse(response); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/Clock.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/Clock.java deleted file mode 100644 index 2dd46153..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/Clock.java +++ /dev/null @@ -1,43 +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 com.tracelytics.ext.apache.http.impl.client; - -/** - * Interface used to enable easier testing of time-related behavior. - * - * @since 4.2 - * - */ -interface Clock { - - /** - * Returns the current time, expressed as the number of - * milliseconds since the epoch. - * @return current time - */ - long getCurrentTime(); -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/CloseableHttpClient.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/CloseableHttpClient.java deleted file mode 100644 index 21a357c7..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/CloseableHttpClient.java +++ /dev/null @@ -1,242 +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 com.tracelytics.ext.apache.http.impl.client; - -import java.io.Closeable; -import java.io.IOException; -import java.net.URI; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.client.ClientProtocolException; -import com.tracelytics.ext.apache.http.client.HttpClient; -import com.tracelytics.ext.apache.http.client.ResponseHandler; -import com.tracelytics.ext.apache.http.client.methods.CloseableHttpResponse; -import com.tracelytics.ext.apache.http.client.methods.HttpUriRequest; -import com.tracelytics.ext.apache.http.client.utils.URIUtils; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.EntityUtils; - -/** - * Base implementation of {@link HttpClient} that also implements {@link Closeable}. - * - * @since 4.3 - */ -@ThreadSafe -public abstract class CloseableHttpClient implements HttpClient, Closeable { - - private final Logger log = Logger.getLogger(getClass().getName()); - - protected abstract CloseableHttpResponse doExecute(HttpHost target, HttpRequest request, - HttpContext context) throws IOException, ClientProtocolException; - - /** - * {@inheritDoc} - */ - @Override - public CloseableHttpResponse execute( - final HttpHost target, - final HttpRequest request, - final HttpContext context) throws IOException, ClientProtocolException { - return doExecute(target, request, context); - } - - /** - * {@inheritDoc} - */ - @Override - public CloseableHttpResponse execute( - final HttpUriRequest request, - final HttpContext context) throws IOException, ClientProtocolException { - Args.notNull(request, "HTTP request"); - return doExecute(determineTarget(request), request, context); - } - - private static HttpHost determineTarget(final HttpUriRequest 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()) { - target = URIUtils.extractHost(requestURI); - if (target == null) { - throw new ClientProtocolException("URI does not specify a valid host name: " - + requestURI); - } - } - return target; - } - - /** - * {@inheritDoc} - */ - @Override - public CloseableHttpResponse execute( - final HttpUriRequest request) throws IOException, ClientProtocolException { - return execute(request, (HttpContext) null); - } - - /** - * {@inheritDoc} - */ - @Override - public CloseableHttpResponse execute( - final HttpHost target, - final HttpRequest request) throws IOException, ClientProtocolException { - return doExecute(target, request, null); - } - - /** - * Executes a request using the default context and processes the - * response using the given response handler. The content entity associated - * with the response is fully consumed and the underlying connection is - * released back to the connection manager automatically in all cases - * relieving individual {@link ResponseHandler}s from having to manage - * resource deallocation internally. - * - * @param request the request to execute - * @param responseHandler the response handler - * - * @return the response object as generated by the response handler. - * @throws IOException in case of a problem or the connection was aborted - * @throws ClientProtocolException in case of an http protocol error - */ - @Override - public T execute(final HttpUriRequest request, - final ResponseHandler responseHandler) throws IOException, - ClientProtocolException { - return execute(request, responseHandler, null); - } - - /** - * Executes a request using the default context and processes the - * response using the given response handler. The content entity associated - * with the response is fully consumed and the underlying connection is - * released back to the connection manager automatically in all cases - * relieving individual {@link ResponseHandler}s from having to manage - * resource deallocation internally. - * - * @param request the request to execute - * @param responseHandler the response handler - * @param context the context to use for the execution, or - * {@code null} to use the default context - * - * @return the response object as generated by the response handler. - * @throws IOException in case of a problem or the connection was aborted - * @throws ClientProtocolException in case of an http protocol error - */ - @Override - public T execute(final HttpUriRequest request, - final ResponseHandler responseHandler, final HttpContext context) - throws IOException, ClientProtocolException { - final HttpHost target = determineTarget(request); - return execute(target, request, responseHandler, context); - } - - /** - * Executes a request using the default context and processes the - * response using the given response handler. The content entity associated - * with the response is fully consumed and the underlying connection is - * released back to the connection manager automatically in all cases - * relieving individual {@link ResponseHandler}s from having to manage - * resource deallocation internally. - * - * @param target the target host for the request. - * Implementations may accept {@code null} - * if they can still determine a route, for example - * to a default target or by inspecting the request. - * @param request the request to execute - * @param responseHandler the response handler - * - * @return the response object as generated by the response handler. - * @throws IOException in case of a problem or the connection was aborted - * @throws ClientProtocolException in case of an http protocol error - */ - @Override - public T execute(final HttpHost target, final HttpRequest request, - final ResponseHandler responseHandler) throws IOException, - ClientProtocolException { - return execute(target, request, responseHandler, null); - } - - /** - * Executes a request using the default context and processes the - * response using the given response handler. The content entity associated - * with the response is fully consumed and the underlying connection is - * released back to the connection manager automatically in all cases - * relieving individual {@link ResponseHandler}s from having to manage - * resource deallocation internally. - * - * @param target the target host for the request. - * Implementations may accept {@code null} - * if they can still determine a route, for example - * to a default target or by inspecting the request. - * @param request the request to execute - * @param responseHandler the response handler - * @param context the context to use for the execution, or - * {@code null} to use the default context - * - * @return the response object as generated by the response handler. - * @throws IOException in case of a problem or the connection was aborted - * @throws ClientProtocolException in case of an http protocol error - */ - @Override - public T execute(final HttpHost target, final HttpRequest request, - final ResponseHandler responseHandler, final HttpContext context) - throws IOException, ClientProtocolException { - Args.notNull(responseHandler, "Response handler"); - - final CloseableHttpResponse response = execute(target, request, context); - try { - final T result = responseHandler.handleResponse(response); - final HttpEntity entity = response.getEntity(); - EntityUtils.consume(entity); - return result; - } catch (final ClientProtocolException t) { - // Try to salvage the underlying connection in case of a protocol exception - final HttpEntity entity = response.getEntity(); - try { - EntityUtils.consume(entity); - } catch (final Exception t2) { - // Log this exception. The original exception is more - // important and will be thrown to the caller. - this.log.log(Level.WARNING, "Error consuming content after an exception.", t2); - } - throw t; - } finally { - response.close(); - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/DefaultBackoffStrategy.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/DefaultBackoffStrategy.java deleted file mode 100644 index 8814ecef..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/DefaultBackoffStrategy.java +++ /dev/null @@ -1,57 +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 com.tracelytics.ext.apache.http.impl.client; - -import java.net.ConnectException; -import java.net.SocketTimeoutException; - -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.HttpStatus; - -import com.tracelytics.ext.apache.http.client.ConnectionBackoffStrategy; - -/** - * This {@link ConnectionBackoffStrategy} backs off either for a raw - * network socket or connection timeout or if the server explicitly - * sends a 503 (Service Unavailable) response. - * - * @since 4.2 - */ -public class DefaultBackoffStrategy implements ConnectionBackoffStrategy { - - @Override - public boolean shouldBackoff(final Throwable t) { - return (t instanceof SocketTimeoutException - || t instanceof ConnectException); - } - - @Override - public boolean shouldBackoff(final HttpResponse resp) { - return (resp.getStatusLine().getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/DefaultConnectionKeepAliveStrategy.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/DefaultConnectionKeepAliveStrategy.java deleted file mode 100644 index db69de8c..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/DefaultConnectionKeepAliveStrategy.java +++ /dev/null @@ -1,73 +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 com.tracelytics.ext.apache.http.impl.client; - -import com.tracelytics.ext.apache.http.HeaderElement; -import com.tracelytics.ext.apache.http.HeaderElementIterator; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.message.BasicHeaderElementIterator; -import com.tracelytics.ext.apache.http.protocol.HTTP; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.conn.ConnectionKeepAliveStrategy; - -/** - * Default implementation of a strategy deciding duration - * that a connection can remain idle. - * - * The default implementation looks solely at the 'Keep-Alive' - * header's timeout token. - * - * @since 4.0 - */ -@Immutable -public class DefaultConnectionKeepAliveStrategy implements ConnectionKeepAliveStrategy { - - public static final DefaultConnectionKeepAliveStrategy INSTANCE = new DefaultConnectionKeepAliveStrategy(); - - @Override - public long getKeepAliveDuration(final HttpResponse response, final HttpContext context) { - Args.notNull(response, "HTTP response"); - final HeaderElementIterator it = new BasicHeaderElementIterator( - response.headerIterator(HTTP.CONN_KEEP_ALIVE)); - while (it.hasNext()) { - final HeaderElement he = it.nextElement(); - final String param = he.getName(); - final String value = he.getValue(); - if (value != null && param.equalsIgnoreCase("timeout")) { - try { - return Long.parseLong(value) * 1000; - } catch(final NumberFormatException ignore) { - } - } - } - return -1; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/DefaultHttpRequestRetryHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/DefaultHttpRequestRetryHandler.java deleted file mode 100644 index 3a1c2f22..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/DefaultHttpRequestRetryHandler.java +++ /dev/null @@ -1,205 +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 com.tracelytics.ext.apache.http.impl.client; - -import java.io.IOException; -import java.io.InterruptedIOException; -import java.net.ConnectException; -import java.net.UnknownHostException; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; - -import javax.net.ssl.SSLException; - -import com.tracelytics.ext.apache.http.HttpEntityEnclosingRequest; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.client.HttpRequestRetryHandler; -import com.tracelytics.ext.apache.http.client.methods.HttpUriRequest; -import com.tracelytics.ext.apache.http.client.protocol.HttpClientContext; - -/** - * The default {@link HttpRequestRetryHandler} used by request executors. - * - * @since 4.0 - */ -@Immutable -public class DefaultHttpRequestRetryHandler implements HttpRequestRetryHandler { - - public static final DefaultHttpRequestRetryHandler INSTANCE = new DefaultHttpRequestRetryHandler(); - - /** the number of times a method will be retried */ - private final int retryCount; - - /** Whether or not methods that have successfully sent their request will be retried */ - private final boolean requestSentRetryEnabled; - - private final Set> nonRetriableClasses; - - /** - * Create the request retry handler using the specified IOException classes - * - * @param retryCount how many times to retry; 0 means no retries - * @param requestSentRetryEnabled true if it's OK to retry requests that have been sent - * @param clazzes the IOException types that should not be retried - * @since 4.3 - */ - protected DefaultHttpRequestRetryHandler( - final int retryCount, - final boolean requestSentRetryEnabled, - final Collection> clazzes) { - super(); - this.retryCount = retryCount; - this.requestSentRetryEnabled = requestSentRetryEnabled; - this.nonRetriableClasses = new HashSet>(); - for (final Class clazz: clazzes) { - this.nonRetriableClasses.add(clazz); - } - } - - /** - * Create the request retry handler using the following list of - * non-retriable IOException classes:
- *
    - *
  • InterruptedIOException
  • - *
  • UnknownHostException
  • - *
  • ConnectException
  • - *
  • SSLException
  • - *
- * @param retryCount how many times to retry; 0 means no retries - * @param requestSentRetryEnabled true if it's OK to retry non-idempotent requests that have been sent - */ - @SuppressWarnings("unchecked") - public DefaultHttpRequestRetryHandler(final int retryCount, final boolean requestSentRetryEnabled) { - this(retryCount, requestSentRetryEnabled, Arrays.asList( - InterruptedIOException.class, - UnknownHostException.class, - ConnectException.class, - SSLException.class)); - } - - /** - * Create the request retry handler with a retry count of 3, requestSentRetryEnabled false - * and using the following list of non-retriable IOException classes:
- *
    - *
  • InterruptedIOException
  • - *
  • UnknownHostException
  • - *
  • ConnectException
  • - *
  • SSLException
  • - *
- */ - public DefaultHttpRequestRetryHandler() { - this(3, false); - } - /** - * Used {@code retryCount} and {@code requestSentRetryEnabled} to determine - * if the given method should be retried. - */ - @Override - public boolean retryRequest( - final IOException exception, - final int executionCount, - final HttpContext context) { - Args.notNull(exception, "Exception parameter"); - Args.notNull(context, "HTTP context"); - if (executionCount > this.retryCount) { - // Do not retry if over max retry count - return false; - } - if (this.nonRetriableClasses.contains(exception.getClass())) { - return false; - } else { - for (final Class rejectException : this.nonRetriableClasses) { - if (rejectException.isInstance(exception)) { - return false; - } - } - } - final HttpClientContext clientContext = HttpClientContext.adapt(context); - final HttpRequest request = clientContext.getRequest(); - - if(requestIsAborted(request)){ - return false; - } - - if (handleAsIdempotent(request)) { - // Retry if the request is considered idempotent - return true; - } - - if (!clientContext.isRequestSent() || this.requestSentRetryEnabled) { - // Retry if the request has not been sent fully or - // if it's OK to retry methods that have been sent - return true; - } - // otherwise do not retry - return false; - } - - /** - * @return {@code true} if this handler will retry methods that have - * successfully sent their request, {@code false} otherwise - */ - public boolean isRequestSentRetryEnabled() { - return requestSentRetryEnabled; - } - - /** - * @return the maximum number of times a method will be retried - */ - public int getRetryCount() { - return retryCount; - } - - /** - * @since 4.2 - */ - protected boolean handleAsIdempotent(final HttpRequest request) { - return !(request instanceof HttpEntityEnclosingRequest); - } - - /** - * @since 4.2 - * - * @deprecated (4.3) - */ - @Deprecated - protected boolean requestIsAborted(final HttpRequest request) { - HttpRequest req = request; - if (request instanceof RequestWrapper) { // does not forward request to original - req = ((RequestWrapper) request).getOriginal(); - } - return (req instanceof HttpUriRequest && ((HttpUriRequest)req).isAborted()); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/DefaultRedirectStrategy.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/DefaultRedirectStrategy.java deleted file mode 100644 index 9b54cf47..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/DefaultRedirectStrategy.java +++ /dev/null @@ -1,236 +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 com.tracelytics.ext.apache.http.impl.client; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Locale; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.HttpStatus; -import com.tracelytics.ext.apache.http.ProtocolException; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.client.CircularRedirectException; -import com.tracelytics.ext.apache.http.client.RedirectStrategy; -import com.tracelytics.ext.apache.http.client.config.RequestConfig; -import com.tracelytics.ext.apache.http.client.methods.HttpGet; -import com.tracelytics.ext.apache.http.client.methods.HttpHead; -import com.tracelytics.ext.apache.http.client.methods.HttpUriRequest; -import com.tracelytics.ext.apache.http.client.methods.RequestBuilder; -import com.tracelytics.ext.apache.http.client.protocol.HttpClientContext; -import com.tracelytics.ext.apache.http.client.utils.URIBuilder; -import com.tracelytics.ext.apache.http.client.utils.URIUtils; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.Asserts; -import com.tracelytics.ext.apache.http.util.TextUtils; - -/** - * Default implementation of {@link RedirectStrategy}. This strategy honors the restrictions - * on automatic redirection of entity enclosing methods such as POST and PUT imposed by the - * HTTP specification. {@code 302 Moved Temporarily}, {@code 301 Moved Permanently} and - * {@code 307 Temporary Redirect} status codes will result in an automatic redirect of - * HEAD and GET methods only. POST and PUT methods will not be automatically redirected - * as requiring user confirmation. - *

- * The restriction on automatic redirection of POST methods can be relaxed by using - * {@link LaxRedirectStrategy} instead of {@link DefaultRedirectStrategy}. - *

- * - * @see LaxRedirectStrategy - * @since 4.1 - */ -@Immutable -public class DefaultRedirectStrategy implements RedirectStrategy { - - private final Logger log = Logger.getLogger(getClass().getName()); - - /** - * @deprecated (4.3) use {@link com.tracelytics.ext.apache.http.client.protocol.HttpClientContext#REDIRECT_LOCATIONS}. - */ - @Deprecated - public static final String REDIRECT_LOCATIONS = "http.protocol.redirect-locations"; - - public static final DefaultRedirectStrategy INSTANCE = new DefaultRedirectStrategy(); - - /** - * Redirectable methods. - */ - private static final String[] REDIRECT_METHODS = new String[] { - HttpGet.METHOD_NAME, - HttpHead.METHOD_NAME - }; - - public DefaultRedirectStrategy() { - super(); - } - - @Override - public boolean isRedirected( - final HttpRequest request, - final HttpResponse response, - final HttpContext context) throws ProtocolException { - Args.notNull(request, "HTTP request"); - Args.notNull(response, "HTTP response"); - - final int statusCode = response.getStatusLine().getStatusCode(); - final String method = request.getRequestLine().getMethod(); - final Header locationHeader = response.getFirstHeader("location"); - switch (statusCode) { - case HttpStatus.SC_MOVED_TEMPORARILY: - return isRedirectable(method) && locationHeader != null; - case HttpStatus.SC_MOVED_PERMANENTLY: - case HttpStatus.SC_TEMPORARY_REDIRECT: - return isRedirectable(method); - case HttpStatus.SC_SEE_OTHER: - return true; - default: - return false; - } //end of switch - } - - public URI getLocationURI( - final HttpRequest request, - final HttpResponse response, - final HttpContext context) throws ProtocolException { - Args.notNull(request, "HTTP request"); - Args.notNull(response, "HTTP response"); - Args.notNull(context, "HTTP context"); - - final HttpClientContext clientContext = HttpClientContext.adapt(context); - - //get the location header to find out where to redirect to - final Header locationHeader = response.getFirstHeader("location"); - if (locationHeader == null) { - // got a redirect response, but no location header - throw new ProtocolException( - "Received redirect response " + response.getStatusLine() - + " but no location header"); - } - final String location = locationHeader.getValue(); - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Redirect requested to location '" + location + "'"); - } - - final RequestConfig config = clientContext.getRequestConfig(); - - URI uri = createLocationURI(location); - - // rfc2616 demands the location value be a complete URI - // Location = "Location" ":" absoluteURI - try { - if (!uri.isAbsolute()) { - if (!config.isRelativeRedirectsAllowed()) { - throw new ProtocolException("Relative redirect location '" - + uri + "' not allowed"); - } - // Adjust 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); - } - } catch (final URISyntaxException ex) { - throw new ProtocolException(ex.getMessage(), ex); - } - - RedirectLocations redirectLocations = (RedirectLocations) clientContext.getAttribute( - HttpClientContext.REDIRECT_LOCATIONS); - if (redirectLocations == null) { - redirectLocations = new RedirectLocations(); - context.setAttribute(HttpClientContext.REDIRECT_LOCATIONS, redirectLocations); - } - if (!config.isCircularRedirectsAllowed()) { - if (redirectLocations.contains(uri)) { - throw new CircularRedirectException("Circular redirect to '" + uri + "'"); - } - } - redirectLocations.add(uri); - return uri; - } - - /** - * @since 4.1 - */ - protected URI createLocationURI(final String location) throws ProtocolException { - try { - final URIBuilder b = new URIBuilder(new URI(location).normalize()); - final String host = b.getHost(); - if (host != null) { - b.setHost(host.toLowerCase(Locale.ROOT)); - } - final String path = b.getPath(); - if (TextUtils.isEmpty(path)) { - b.setPath("/"); - } - return b.build(); - } catch (final URISyntaxException ex) { - throw new ProtocolException("Invalid redirect URI: " + location, ex); - } - } - - /** - * @since 4.2 - */ - protected boolean isRedirectable(final String method) { - for (final String m: REDIRECT_METHODS) { - if (m.equalsIgnoreCase(method)) { - return true; - } - } - return false; - } - - @Override - public HttpUriRequest getRedirect( - final HttpRequest request, - final HttpResponse response, - final HttpContext context) throws ProtocolException { - final URI uri = getLocationURI(request, response, context); - final String method = request.getRequestLine().getMethod(); - if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) { - return new HttpHead(uri); - } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) { - return new HttpGet(uri); - } else { - final int status = response.getStatusLine().getStatusCode(); - if (status == HttpStatus.SC_TEMPORARY_REDIRECT) { - return RequestBuilder.copy(request).setUri(uri).build(); - } else { - return new HttpGet(uri); - } - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/DefaultServiceUnavailableRetryStrategy.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/DefaultServiceUnavailableRetryStrategy.java deleted file mode 100644 index 2ff81618..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/DefaultServiceUnavailableRetryStrategy.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 com.tracelytics.ext.apache.http.impl.client; - -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.HttpStatus; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.client.ServiceUnavailableRetryStrategy; - -/** - * Default implementation of the {@link ServiceUnavailableRetryStrategy} interface. - * that retries {@code 503} (Service Unavailable) responses for a fixed number of times - * at a fixed interval. - * - * @since 4.2 - */ -@Immutable -public class DefaultServiceUnavailableRetryStrategy implements ServiceUnavailableRetryStrategy { - - /** - * Maximum number of allowed retries if the server responds with a HTTP code - * in our retry code list. Default value is 1. - */ - private final int maxRetries; - - /** - * Retry interval between subsequent requests, in milliseconds. Default - * value is 1 second. - */ - private final long retryInterval; - - public DefaultServiceUnavailableRetryStrategy(final int maxRetries, final int retryInterval) { - super(); - Args.positive(maxRetries, "Max retries"); - Args.positive(retryInterval, "Retry interval"); - this.maxRetries = maxRetries; - this.retryInterval = retryInterval; - } - - public DefaultServiceUnavailableRetryStrategy() { - this(1, 1000); - } - - @Override - public boolean retryRequest(final HttpResponse response, final int executionCount, final HttpContext context) { - return executionCount <= maxRetries && - response.getStatusLine().getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE; - } - - @Override - public long getRetryInterval() { - return retryInterval; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/DefaultUserTokenHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/DefaultUserTokenHandler.java deleted file mode 100644 index 73e8024f..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/DefaultUserTokenHandler.java +++ /dev/null @@ -1,103 +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 com.tracelytics.ext.apache.http.impl.client; - -import java.security.Principal; - -import javax.net.ssl.SSLSession; - -import com.tracelytics.ext.apache.http.HttpConnection; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -import com.tracelytics.ext.apache.http.auth.AuthScheme; -import com.tracelytics.ext.apache.http.auth.AuthState; -import com.tracelytics.ext.apache.http.auth.Credentials; -import com.tracelytics.ext.apache.http.client.UserTokenHandler; -import com.tracelytics.ext.apache.http.client.protocol.HttpClientContext; -import com.tracelytics.ext.apache.http.conn.ManagedHttpClientConnection; - -/** - * Default implementation of {@link UserTokenHandler}. This class will use - * an instance of {@link Principal} as a state object for HTTP connections, - * if it can be obtained from the given execution context. This helps ensure - * persistent connections created with a particular user identity within - * a particular security context can be reused by the same user only. - *

- * DefaultUserTokenHandler will use the user principle of connection - * based authentication schemes such as NTLM or that of the SSL session - * with the client authentication turned on. If both are unavailable, - * {@code null} token will be returned. - * - * @since 4.0 - */ -@Immutable -public class DefaultUserTokenHandler implements UserTokenHandler { - - public static final DefaultUserTokenHandler INSTANCE = new DefaultUserTokenHandler(); - - @Override - public Object getUserToken(final HttpContext context) { - - final HttpClientContext clientContext = HttpClientContext.adapt(context); - - Principal userPrincipal = null; - - final AuthState targetAuthState = clientContext.getTargetAuthState(); - if (targetAuthState != null) { - userPrincipal = getAuthPrincipal(targetAuthState); - if (userPrincipal == null) { - final AuthState proxyAuthState = clientContext.getProxyAuthState(); - userPrincipal = getAuthPrincipal(proxyAuthState); - } - } - - if (userPrincipal == null) { - final HttpConnection conn = clientContext.getConnection(); - if (conn.isOpen() && conn instanceof ManagedHttpClientConnection) { - final SSLSession sslsession = ((ManagedHttpClientConnection) conn).getSSLSession(); - if (sslsession != null) { - userPrincipal = sslsession.getLocalPrincipal(); - } - } - } - - return userPrincipal; - } - - private static Principal getAuthPrincipal(final AuthState authState) { - final AuthScheme scheme = authState.getAuthScheme(); - if (scheme != null && scheme.isComplete() && scheme.isConnectionBased()) { - final Credentials creds = authState.getCredentials(); - if (creds != null) { - return creds.getUserPrincipal(); - } - } - return null; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/EntityEnclosingRequestWrapper.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/EntityEnclosingRequestWrapper.java deleted file mode 100644 index 374ed471..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/EntityEnclosingRequestWrapper.java +++ /dev/null @@ -1,117 +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 com.tracelytics.ext.apache.http.impl.client; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpEntityEnclosingRequest; -import com.tracelytics.ext.apache.http.ProtocolException; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.entity.HttpEntityWrapper; -import com.tracelytics.ext.apache.http.protocol.HTTP; - -/** - * A wrapper class for {@link HttpEntityEnclosingRequest}s that can - * be used to change properties of the current request without - * modifying the original object. - *

- * This class is also capable of resetting the request headers to - * the state of the original request. - *

- * - * @since 4.0 - * - * @deprecated (4.3) do not use. - */ -@Deprecated -@NotThreadSafe // e.g. [gs]etEntity() -public class EntityEnclosingRequestWrapper extends RequestWrapper - implements HttpEntityEnclosingRequest { - - private HttpEntity entity; - private boolean consumed; - - public EntityEnclosingRequestWrapper(final HttpEntityEnclosingRequest request) - throws ProtocolException { - super(request); - setEntity(request.getEntity()); - } - - @Override - public HttpEntity getEntity() { - return this.entity; - } - - @Override - public void setEntity(final HttpEntity entity) { - this.entity = entity != null ? new EntityWrapper(entity) : null; - this.consumed = false; - } - - @Override - public boolean expectContinue() { - final Header expect = getFirstHeader(HTTP.EXPECT_DIRECTIVE); - return expect != null && HTTP.EXPECT_CONTINUE.equalsIgnoreCase(expect.getValue()); - } - - @Override - public boolean isRepeatable() { - return this.entity == null || this.entity.isRepeatable() || !this.consumed; - } - - class EntityWrapper extends HttpEntityWrapper { - - EntityWrapper(final HttpEntity entity) { - super(entity); - } - - @Override - public void consumeContent() throws IOException { - consumed = true; - super.consumeContent(); - } - - @Override - public InputStream getContent() throws IOException { - consumed = true; - return super.getContent(); - } - - @Override - public void writeTo(final OutputStream outstream) throws IOException { - consumed = true; - super.writeTo(outstream); - } - - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/FutureRequestExecutionMetrics.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/FutureRequestExecutionMetrics.java deleted file mode 100644 index a09f0d5a..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/FutureRequestExecutionMetrics.java +++ /dev/null @@ -1,156 +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 com.tracelytics.ext.apache.http.impl.client; - -import java.util.concurrent.atomic.AtomicLong; - -/** - * Collection of different counters used to gather metrics for {@link FutureRequestExecutionService}. - */ -public final class FutureRequestExecutionMetrics { - - private final AtomicLong activeConnections = new AtomicLong(); - private final AtomicLong scheduledConnections = new AtomicLong(); - private final DurationCounter successfulConnections = new DurationCounter(); - private final DurationCounter failedConnections = new DurationCounter(); - private final DurationCounter requests = new DurationCounter(); - private final DurationCounter tasks = new DurationCounter(); - - FutureRequestExecutionMetrics() { - } - - AtomicLong getActiveConnections() { - return activeConnections; - } - - AtomicLong getScheduledConnections() { - return scheduledConnections; - } - - DurationCounter getSuccessfulConnections() { - return successfulConnections; - } - - DurationCounter getFailedConnections() { - return failedConnections; - } - - DurationCounter getRequests() { - return requests; - } - - DurationCounter getTasks() { - return tasks; - } - - public long getActiveConnectionCount() { - return activeConnections.get(); - } - - public long getScheduledConnectionCount() { - return scheduledConnections.get(); - } - - public long getSuccessfulConnectionCount() { - return successfulConnections.count(); - } - - public long getSuccessfulConnectionAverageDuration() { - return successfulConnections.averageDuration(); - } - - public long getFailedConnectionCount() { - return failedConnections.count(); - } - - public long getFailedConnectionAverageDuration() { - return failedConnections.averageDuration(); - } - - public long getRequestCount() { - return requests.count(); - } - - public long getRequestAverageDuration() { - return requests.averageDuration(); - } - - public long getTaskCount() { - return tasks.count(); - } - - public long getTaskAverageDuration() { - return tasks.averageDuration(); - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("[activeConnections=").append(activeConnections) - .append(", scheduledConnections=").append(scheduledConnections) - .append(", successfulConnections=").append(successfulConnections) - .append(", failedConnections=").append(failedConnections) - .append(", requests=").append(requests) - .append(", tasks=").append(tasks) - .append("]"); - return builder.toString(); - } - - /** - * A counter that can measure duration and number of events. - */ - static class DurationCounter { - - private final AtomicLong count = new AtomicLong(0); - private final AtomicLong cumulativeDuration = new AtomicLong(0); - - public void increment(final long startTime) { - count.incrementAndGet(); - cumulativeDuration.addAndGet(System.currentTimeMillis() - startTime); - } - - public long count() { - return count.get(); - } - - public long averageDuration() { - final long counter = count.get(); - return counter > 0 ? cumulativeDuration.get() / counter : 0; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("[count=").append(count()) - .append(", averageDuration=").append(averageDuration()) - .append("]"); - return builder.toString(); - } - - } - -} \ No newline at end of file diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/FutureRequestExecutionService.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/FutureRequestExecutionService.java deleted file mode 100644 index 3781f433..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/FutureRequestExecutionService.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 com.tracelytics.ext.apache.http.impl.client; - -import java.io.Closeable; -import java.io.IOException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.atomic.AtomicBoolean; - -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.concurrent.FutureCallback; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -import com.tracelytics.ext.apache.http.client.HttpClient; -import com.tracelytics.ext.apache.http.client.ResponseHandler; -import com.tracelytics.ext.apache.http.client.methods.HttpUriRequest; - -/** - * HttpAsyncClientWithFuture wraps calls to execute with a {@link HttpRequestFutureTask} - * and schedules them using the provided executor service. Scheduled calls may be cancelled. - */ -@ThreadSafe -public class FutureRequestExecutionService implements Closeable { - - private final HttpClient httpclient; - private final ExecutorService executorService; - private final FutureRequestExecutionMetrics metrics = new FutureRequestExecutionMetrics(); - private final AtomicBoolean closed = new AtomicBoolean(false); - - /** - * Create a new FutureRequestExecutionService. - * - * @param httpclient - * you should tune your httpclient instance to match your needs. You should - * align the max number of connections in the pool and the number of threads - * in the executor; it doesn't make sense to have more threads than connections - * and if you have less connections than threads, the threads will just end up - * blocking on getting a connection from the pool. - * @param executorService - * any executorService will do here. E.g. - * {@link java.util.concurrent.Executors#newFixedThreadPool(int)} - */ - public FutureRequestExecutionService( - final HttpClient httpclient, - final ExecutorService executorService) { - this.httpclient = httpclient; - this.executorService = executorService; - } - - /** - * Schedule a request for execution. - * - * @param - * - * @param request - * request to execute - * @param responseHandler - * handler that will process the response. - * @return HttpAsyncClientFutureTask for the scheduled request. - */ - public HttpRequestFutureTask execute( - final HttpUriRequest request, - final HttpContext context, - final ResponseHandler responseHandler) { - return execute(request, context, responseHandler, null); - } - - /** - * Schedule a request for execution. - * - * @param - * - * @param request - * request to execute - * @param context - * optional context; use null if not needed. - * @param responseHandler - * handler that will process the response. - * @param callback - * callback handler that will be called when the request is scheduled, - * started, completed, failed, or cancelled. - * @return HttpAsyncClientFutureTask for the scheduled request. - */ - public HttpRequestFutureTask execute( - final HttpUriRequest request, - final HttpContext context, - final ResponseHandler responseHandler, - final FutureCallback callback) { - if(closed.get()) { - throw new IllegalStateException("Close has been called on this httpclient instance."); - } - metrics.getScheduledConnections().incrementAndGet(); - final HttpRequestTaskCallable callable = new HttpRequestTaskCallable( - httpclient, request, context, responseHandler, callback, metrics); - final HttpRequestFutureTask httpRequestFutureTask = new HttpRequestFutureTask( - request, callable); - executorService.execute(httpRequestFutureTask); - - return httpRequestFutureTask; - } - - /** - * @return metrics gathered for this instance. - * @see FutureRequestExecutionMetrics - */ - public FutureRequestExecutionMetrics metrics() { - return metrics; - } - - @Override - public void close() throws IOException { - closed.set(true); - executorService.shutdownNow(); - if (httpclient instanceof Closeable) { - ((Closeable) httpclient).close(); - } - } -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/HttpClientBuilder.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/HttpClientBuilder.java deleted file mode 100644 index 53adcfab..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/HttpClientBuilder.java +++ /dev/null @@ -1,1203 +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 com.tracelytics.ext.apache.http.impl.client; - -import java.io.Closeable; -import java.io.IOException; -import java.net.ProxySelector; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSocketFactory; - -import com.tracelytics.ext.apache.http.ConnectionReuseStrategy; -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.HttpRequestInterceptor; -import com.tracelytics.ext.apache.http.HttpResponseInterceptor; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.config.ConnectionConfig; -import com.tracelytics.ext.apache.http.config.Lookup; -import com.tracelytics.ext.apache.http.config.RegistryBuilder; -import com.tracelytics.ext.apache.http.config.SocketConfig; -import com.tracelytics.ext.apache.http.impl.DefaultConnectionReuseStrategy; -import com.tracelytics.ext.apache.http.impl.NoConnectionReuseStrategy; -import com.tracelytics.ext.apache.http.protocol.HttpProcessor; -import com.tracelytics.ext.apache.http.protocol.HttpProcessorBuilder; -import com.tracelytics.ext.apache.http.protocol.HttpRequestExecutor; -import com.tracelytics.ext.apache.http.protocol.ImmutableHttpProcessor; -import com.tracelytics.ext.apache.http.protocol.RequestContent; -import com.tracelytics.ext.apache.http.protocol.RequestTargetHost; -import com.tracelytics.ext.apache.http.protocol.RequestUserAgent; -import com.tracelytics.ext.apache.http.ssl.SSLContexts; -import com.tracelytics.ext.apache.http.util.TextUtils; -import com.tracelytics.ext.apache.http.util.VersionInfo; - -import com.tracelytics.ext.apache.http.auth.AuthSchemeProvider; -import com.tracelytics.ext.apache.http.client.AuthenticationStrategy; -import com.tracelytics.ext.apache.http.client.BackoffManager; -import com.tracelytics.ext.apache.http.client.ConnectionBackoffStrategy; -import com.tracelytics.ext.apache.http.client.CookieStore; -import com.tracelytics.ext.apache.http.client.CredentialsProvider; -import com.tracelytics.ext.apache.http.client.HttpRequestRetryHandler; -import com.tracelytics.ext.apache.http.client.RedirectStrategy; -import com.tracelytics.ext.apache.http.client.ServiceUnavailableRetryStrategy; -import com.tracelytics.ext.apache.http.client.UserTokenHandler; -import com.tracelytics.ext.apache.http.client.config.AuthSchemes; -import com.tracelytics.ext.apache.http.client.config.CookieSpecs; -import com.tracelytics.ext.apache.http.client.config.RequestConfig; -import com.tracelytics.ext.apache.http.client.entity.InputStreamFactory; -import com.tracelytics.ext.apache.http.client.protocol.RequestAcceptEncoding; -import com.tracelytics.ext.apache.http.client.protocol.RequestAddCookies; -import com.tracelytics.ext.apache.http.client.protocol.RequestAuthCache; -import com.tracelytics.ext.apache.http.client.protocol.RequestClientConnControl; -import com.tracelytics.ext.apache.http.client.protocol.RequestDefaultHeaders; -import com.tracelytics.ext.apache.http.client.protocol.RequestExpectContinue; -import com.tracelytics.ext.apache.http.client.protocol.ResponseContentEncoding; -import com.tracelytics.ext.apache.http.client.protocol.ResponseProcessCookies; -import com.tracelytics.ext.apache.http.conn.ConnectionKeepAliveStrategy; -import com.tracelytics.ext.apache.http.conn.HttpClientConnectionManager; -import com.tracelytics.ext.apache.http.conn.SchemePortResolver; -import com.tracelytics.ext.apache.http.conn.routing.HttpRoutePlanner; -import com.tracelytics.ext.apache.http.conn.socket.ConnectionSocketFactory; -import com.tracelytics.ext.apache.http.conn.socket.LayeredConnectionSocketFactory; -import com.tracelytics.ext.apache.http.conn.socket.PlainConnectionSocketFactory; -import com.tracelytics.ext.apache.http.conn.ssl.DefaultHostnameVerifier; -import com.tracelytics.ext.apache.http.conn.ssl.SSLConnectionSocketFactory; -import com.tracelytics.ext.apache.http.conn.ssl.X509HostnameVerifier; -import com.tracelytics.ext.apache.http.conn.util.PublicSuffixMatcher; -import com.tracelytics.ext.apache.http.conn.util.PublicSuffixMatcherLoader; -import com.tracelytics.ext.apache.http.cookie.CookieSpecProvider; -import com.tracelytics.ext.apache.http.impl.auth.BasicSchemeFactory; -import com.tracelytics.ext.apache.http.impl.auth.DigestSchemeFactory; -import com.tracelytics.ext.apache.http.impl.auth.KerberosSchemeFactory; -import com.tracelytics.ext.apache.http.impl.auth.NTLMSchemeFactory; -import com.tracelytics.ext.apache.http.impl.auth.SPNegoSchemeFactory; -import com.tracelytics.ext.apache.http.impl.conn.DefaultProxyRoutePlanner; -import com.tracelytics.ext.apache.http.impl.conn.DefaultRoutePlanner; -import com.tracelytics.ext.apache.http.impl.conn.DefaultSchemePortResolver; -import com.tracelytics.ext.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import com.tracelytics.ext.apache.http.impl.conn.SystemDefaultRoutePlanner; -import com.tracelytics.ext.apache.http.impl.cookie.DefaultCookieSpecProvider; -import com.tracelytics.ext.apache.http.impl.cookie.IgnoreSpecProvider; -import com.tracelytics.ext.apache.http.impl.cookie.NetscapeDraftSpecProvider; -import com.tracelytics.ext.apache.http.impl.cookie.RFC6265CookieSpecProvider; -import com.tracelytics.ext.apache.http.impl.execchain.BackoffStrategyExec; -import com.tracelytics.ext.apache.http.impl.execchain.ClientExecChain; -import com.tracelytics.ext.apache.http.impl.execchain.MainClientExec; -import com.tracelytics.ext.apache.http.impl.execchain.ProtocolExec; -import com.tracelytics.ext.apache.http.impl.execchain.RedirectExec; -import com.tracelytics.ext.apache.http.impl.execchain.RetryExec; -import com.tracelytics.ext.apache.http.impl.execchain.ServiceUnavailableRetryExec; - -/** - * Builder for {@link CloseableHttpClient} instances. - *

- * When a particular component is not explicitly set this class will - * use its default implementation. System properties will be taken - * into account when configuring the default implementations when - * {@link #useSystemProperties()} method is called prior to calling - * {@link #build()}. - *

- *
    - *
  • ssl.TrustManagerFactory.algorithm
  • - *
  • javax.net.ssl.trustStoreType
  • - *
  • javax.net.ssl.trustStore
  • - *
  • javax.net.ssl.trustStoreProvider
  • - *
  • javax.net.ssl.trustStorePassword
  • - *
  • ssl.KeyManagerFactory.algorithm
  • - *
  • javax.net.ssl.keyStoreType
  • - *
  • javax.net.ssl.keyStore
  • - *
  • javax.net.ssl.keyStoreProvider
  • - *
  • javax.net.ssl.keyStorePassword
  • - *
  • https.protocols
  • - *
  • https.cipherSuites
  • - *
  • http.proxyHost
  • - *
  • http.proxyPort
  • - *
  • http.nonProxyHosts
  • - *
  • http.keepAlive
  • - *
  • http.maxConnections
  • - *
  • http.agent
  • - *
- *

- * Please note that some settings used by this class can be mutually - * exclusive and may not apply when building {@link CloseableHttpClient} - * instances. - *

- * - * @since 4.3 - */ -@NotThreadSafe -public class HttpClientBuilder { - - private HttpRequestExecutor requestExec; - private HostnameVerifier hostnameVerifier; - private LayeredConnectionSocketFactory sslSocketFactory; - private SSLContext sslcontext; - private HttpClientConnectionManager connManager; - private boolean connManagerShared; - private SchemePortResolver schemePortResolver; - private ConnectionReuseStrategy reuseStrategy; - private ConnectionKeepAliveStrategy keepAliveStrategy; - private AuthenticationStrategy targetAuthStrategy; - private AuthenticationStrategy proxyAuthStrategy; - private UserTokenHandler userTokenHandler; - private HttpProcessor httpprocessor; - - private LinkedList requestFirst; - private LinkedList requestLast; - private LinkedList responseFirst; - private LinkedList responseLast; - - private HttpRequestRetryHandler retryHandler; - private HttpRoutePlanner routePlanner; - private RedirectStrategy redirectStrategy; - private ConnectionBackoffStrategy connectionBackoffStrategy; - private BackoffManager backoffManager; - private ServiceUnavailableRetryStrategy serviceUnavailStrategy; - private Lookup authSchemeRegistry; - private Lookup cookieSpecRegistry; - private Map contentDecoderMap; - private CookieStore cookieStore; - private CredentialsProvider credentialsProvider; - private String userAgent; - private HttpHost proxy; - private Collection defaultHeaders; - private SocketConfig defaultSocketConfig; - private ConnectionConfig defaultConnectionConfig; - private RequestConfig defaultRequestConfig; - private boolean evictExpiredConnections; - private boolean evictIdleConnections; - private long maxIdleTime; - private TimeUnit maxIdleTimeUnit; - - private boolean systemProperties; - private boolean redirectHandlingDisabled; - private boolean automaticRetriesDisabled; - private boolean contentCompressionDisabled; - private boolean cookieManagementDisabled; - private boolean authCachingDisabled; - private boolean connectionStateDisabled; - - private int maxConnTotal = 0; - private int maxConnPerRoute = 0; - - private long connTimeToLive = -1; - private TimeUnit connTimeToLiveTimeUnit = TimeUnit.MILLISECONDS; - - private List closeables; - - private PublicSuffixMatcher publicSuffixMatcher; - - public static HttpClientBuilder create() { - return new HttpClientBuilder(); - } - - protected HttpClientBuilder() { - super(); - } - - /** - * Assigns {@link HttpRequestExecutor} instance. - */ - public final HttpClientBuilder setRequestExecutor(final HttpRequestExecutor requestExec) { - this.requestExec = requestExec; - return this; - } - - /** - * Assigns {@link X509HostnameVerifier} instance. - *

- * Please note this value can be overridden by the {@link #setConnectionManager( - * com.tracelytics.ext.apache.http.conn.HttpClientConnectionManager)} and the {@link #setSSLSocketFactory( - * com.tracelytics.ext.apache.http.conn.socket.LayeredConnectionSocketFactory)} methods. - *

- * - * @deprecated (4.4) - */ - @Deprecated - public final HttpClientBuilder setHostnameVerifier(final X509HostnameVerifier hostnameVerifier) { - this.hostnameVerifier = hostnameVerifier; - return this; - } - - /** - * Assigns {@link javax.net.ssl.HostnameVerifier} instance. - *

- * Please note this value can be overridden by the {@link #setConnectionManager( - * com.tracelytics.ext.apache.http.conn.HttpClientConnectionManager)} and the {@link #setSSLSocketFactory( - * com.tracelytics.ext.apache.http.conn.socket.LayeredConnectionSocketFactory)} methods. - *

- * - * @since 4.4 - */ - public final HttpClientBuilder setSSLHostnameVerifier(final HostnameVerifier hostnameVerifier) { - this.hostnameVerifier = hostnameVerifier; - return this; - } - - /** - * Assigns file containing public suffix matcher. Instances of this class can be created - * with {@link com.tracelytics.ext.apache.http.conn.util.PublicSuffixMatcherLoader}. - * - * @see com.tracelytics.ext.apache.http.conn.util.PublicSuffixMatcher - * @see com.tracelytics.ext.apache.http.conn.util.PublicSuffixMatcherLoader - * - * @since 4.4 - */ - public final HttpClientBuilder setPublicSuffixMatcher(final PublicSuffixMatcher publicSuffixMatcher) { - this.publicSuffixMatcher = publicSuffixMatcher; - return this; - } - - /** - * Assigns {@link SSLContext} instance. - *

- * Please note this value can be overridden by the {@link #setConnectionManager( - * com.tracelytics.ext.apache.http.conn.HttpClientConnectionManager)} and the {@link #setSSLSocketFactory( - * com.tracelytics.ext.apache.http.conn.socket.LayeredConnectionSocketFactory)} methods. - *

- */ - public final HttpClientBuilder setSslcontext(final SSLContext sslcontext) { - this.sslcontext = sslcontext; - return this; - } - - /** - * Assigns {@link LayeredConnectionSocketFactory} instance. - *

- * Please note this value can be overridden by the {@link #setConnectionManager( - * com.tracelytics.ext.apache.http.conn.HttpClientConnectionManager)} method. - *

- */ - public final HttpClientBuilder setSSLSocketFactory( - final LayeredConnectionSocketFactory sslSocketFactory) { - this.sslSocketFactory = sslSocketFactory; - return this; - } - - /** - * Assigns maximum total connection value. - *

- * Please note this value can be overridden by the {@link #setConnectionManager( - * com.tracelytics.ext.apache.http.conn.HttpClientConnectionManager)} method. - *

- */ - public final HttpClientBuilder setMaxConnTotal(final int maxConnTotal) { - this.maxConnTotal = maxConnTotal; - return this; - } - - /** - * Assigns maximum connection per route value. - *

- * Please note this value can be overridden by the {@link #setConnectionManager( - * com.tracelytics.ext.apache.http.conn.HttpClientConnectionManager)} method. - *

- */ - public final HttpClientBuilder setMaxConnPerRoute(final int maxConnPerRoute) { - this.maxConnPerRoute = maxConnPerRoute; - return this; - } - - /** - * Assigns default {@link SocketConfig}. - *

- * Please note this value can be overridden by the {@link #setConnectionManager( - * com.tracelytics.ext.apache.http.conn.HttpClientConnectionManager)} method. - *

- */ - public final HttpClientBuilder setDefaultSocketConfig(final SocketConfig config) { - this.defaultSocketConfig = config; - return this; - } - - /** - * Assigns default {@link ConnectionConfig}. - *

- * Please note this value can be overridden by the {@link #setConnectionManager( - * com.tracelytics.ext.apache.http.conn.HttpClientConnectionManager)} method. - *

- */ - public final HttpClientBuilder setDefaultConnectionConfig(final ConnectionConfig config) { - this.defaultConnectionConfig = config; - return this; - } - - /** - * Sets maximum time to live for persistent connections - *

- * Please note this value can be overridden by the {@link #setConnectionManager( - * com.tracelytics.ext.apache.http.conn.HttpClientConnectionManager)} method. - *

- * - * @since 4.4 - */ - public final HttpClientBuilder setConnectionTimeToLive(final long connTimeToLive, final TimeUnit connTimeToLiveTimeUnit) { - this.connTimeToLive = connTimeToLive; - this.connTimeToLiveTimeUnit = connTimeToLiveTimeUnit; - return this; - } - - /** - * Assigns {@link HttpClientConnectionManager} instance. - */ - public final HttpClientBuilder setConnectionManager( - final HttpClientConnectionManager connManager) { - this.connManager = connManager; - return this; - } - - /** - * Defines the connection manager is to be shared by multiple - * client instances. - *

- * If the connection manager is shared its life-cycle is expected - * to be managed by the caller and it will not be shut down - * if the client is closed. - *

- * - * @param shared defines whether or not the connection manager can be shared - * by multiple clients. - * - * @since 4.4 - */ - public final HttpClientBuilder setConnectionManagerShared( - final boolean shared) { - this.connManagerShared = shared; - return this; - } - - /** - * Assigns {@link ConnectionReuseStrategy} instance. - */ - public final HttpClientBuilder setConnectionReuseStrategy( - final ConnectionReuseStrategy reuseStrategy) { - this.reuseStrategy = reuseStrategy; - return this; - } - - /** - * Assigns {@link ConnectionKeepAliveStrategy} instance. - */ - public final HttpClientBuilder setKeepAliveStrategy( - final ConnectionKeepAliveStrategy keepAliveStrategy) { - this.keepAliveStrategy = keepAliveStrategy; - return this; - } - - /** - * Assigns {@link AuthenticationStrategy} instance for target - * host authentication. - */ - public final HttpClientBuilder setTargetAuthenticationStrategy( - final AuthenticationStrategy targetAuthStrategy) { - this.targetAuthStrategy = targetAuthStrategy; - return this; - } - - /** - * Assigns {@link AuthenticationStrategy} instance for proxy - * authentication. - */ - public final HttpClientBuilder setProxyAuthenticationStrategy( - final AuthenticationStrategy proxyAuthStrategy) { - this.proxyAuthStrategy = proxyAuthStrategy; - return this; - } - - /** - * Assigns {@link UserTokenHandler} instance. - *

- * Please note this value can be overridden by the {@link #disableConnectionState()} - * method. - *

- */ - public final HttpClientBuilder setUserTokenHandler(final UserTokenHandler userTokenHandler) { - this.userTokenHandler = userTokenHandler; - return this; - } - - /** - * Disables connection state tracking. - */ - public final HttpClientBuilder disableConnectionState() { - connectionStateDisabled = true; - return this; - } - - /** - * Assigns {@link SchemePortResolver} instance. - */ - public final HttpClientBuilder setSchemePortResolver( - final SchemePortResolver schemePortResolver) { - this.schemePortResolver = schemePortResolver; - return this; - } - - /** - * Assigns {@code User-Agent} value. - *

- * Please note this value can be overridden by the {@link #setHttpProcessor( - * com.tracelytics.ext.apache.http.protocol.HttpProcessor)} method. - *

- */ - public final HttpClientBuilder setUserAgent(final String userAgent) { - this.userAgent = userAgent; - return this; - } - - /** - * Assigns default request header values. - *

- * Please note this value can be overridden by the {@link #setHttpProcessor( - * com.tracelytics.ext.apache.http.protocol.HttpProcessor)} method. - *

- */ - public final HttpClientBuilder setDefaultHeaders(final Collection defaultHeaders) { - this.defaultHeaders = defaultHeaders; - return this; - } - - /** - * Adds this protocol interceptor to the head of the protocol processing list. - *

- * Please note this value can be overridden by the {@link #setHttpProcessor( - * com.tracelytics.ext.apache.http.protocol.HttpProcessor)} method. - *

- */ - public final HttpClientBuilder addInterceptorFirst(final HttpResponseInterceptor itcp) { - if (itcp == null) { - return this; - } - if (responseFirst == null) { - responseFirst = new LinkedList(); - } - responseFirst.addFirst(itcp); - return this; - } - - /** - * Adds this protocol interceptor to the tail of the protocol processing list. - *

- * Please note this value can be overridden by the {@link #setHttpProcessor( - * com.tracelytics.ext.apache.http.protocol.HttpProcessor)} method. - *

- */ - public final HttpClientBuilder addInterceptorLast(final HttpResponseInterceptor itcp) { - if (itcp == null) { - return this; - } - if (responseLast == null) { - responseLast = new LinkedList(); - } - responseLast.addLast(itcp); - return this; - } - - /** - * Adds this protocol interceptor to the head of the protocol processing list. - *

- * Please note this value can be overridden by the {@link #setHttpProcessor( - * com.tracelytics.ext.apache.http.protocol.HttpProcessor)} method. - */ - public final HttpClientBuilder addInterceptorFirst(final HttpRequestInterceptor itcp) { - if (itcp == null) { - return this; - } - if (requestFirst == null) { - requestFirst = new LinkedList(); - } - requestFirst.addFirst(itcp); - return this; - } - - /** - * Adds this protocol interceptor to the tail of the protocol processing list. - *

- * Please note this value can be overridden by the {@link #setHttpProcessor( - * com.tracelytics.ext.apache.http.protocol.HttpProcessor)} method. - */ - public final HttpClientBuilder addInterceptorLast(final HttpRequestInterceptor itcp) { - if (itcp == null) { - return this; - } - if (requestLast == null) { - requestLast = new LinkedList(); - } - requestLast.addLast(itcp); - return this; - } - - /** - * Disables state (cookie) management. - *

- * Please note this value can be overridden by the {@link #setHttpProcessor( - * com.tracelytics.ext.apache.http.protocol.HttpProcessor)} method. - */ - public final HttpClientBuilder disableCookieManagement() { - this.cookieManagementDisabled = true; - return this; - } - - /** - * Disables automatic content decompression. - *

- * Please note this value can be overridden by the {@link #setHttpProcessor( - * com.tracelytics.ext.apache.http.protocol.HttpProcessor)} method. - */ - public final HttpClientBuilder disableContentCompression() { - contentCompressionDisabled = true; - return this; - } - - /** - * Disables authentication scheme caching. - *

- * Please note this value can be overridden by the {@link #setHttpProcessor( - * com.tracelytics.ext.apache.http.protocol.HttpProcessor)} method. - */ - public final HttpClientBuilder disableAuthCaching() { - this.authCachingDisabled = true; - return this; - } - - /** - * Assigns {@link HttpProcessor} instance. - */ - public final HttpClientBuilder setHttpProcessor(final HttpProcessor httpprocessor) { - this.httpprocessor = httpprocessor; - return this; - } - - /** - * Assigns {@link HttpRequestRetryHandler} instance. - *

- * Please note this value can be overridden by the {@link #disableAutomaticRetries()} - * method. - */ - public final HttpClientBuilder setRetryHandler(final HttpRequestRetryHandler retryHandler) { - this.retryHandler = retryHandler; - return this; - } - - /** - * Disables automatic request recovery and re-execution. - */ - public final HttpClientBuilder disableAutomaticRetries() { - automaticRetriesDisabled = true; - return this; - } - - /** - * Assigns default proxy value. - *

- * Please note this value can be overridden by the {@link #setRoutePlanner( - * com.tracelytics.ext.apache.http.conn.routing.HttpRoutePlanner)} method. - */ - public final HttpClientBuilder setProxy(final HttpHost proxy) { - this.proxy = proxy; - return this; - } - - /** - * Assigns {@link HttpRoutePlanner} instance. - */ - public final HttpClientBuilder setRoutePlanner(final HttpRoutePlanner routePlanner) { - this.routePlanner = routePlanner; - return this; - } - - /** - * Assigns {@link RedirectStrategy} instance. - *

- * Please note this value can be overridden by the {@link #disableRedirectHandling()} - * method. - *

-` */ - public final HttpClientBuilder setRedirectStrategy(final RedirectStrategy redirectStrategy) { - this.redirectStrategy = redirectStrategy; - return this; - } - - /** - * Disables automatic redirect handling. - */ - public final HttpClientBuilder disableRedirectHandling() { - redirectHandlingDisabled = true; - return this; - } - - /** - * Assigns {@link ConnectionBackoffStrategy} instance. - */ - public final HttpClientBuilder setConnectionBackoffStrategy( - final ConnectionBackoffStrategy connectionBackoffStrategy) { - this.connectionBackoffStrategy = connectionBackoffStrategy; - return this; - } - - /** - * Assigns {@link BackoffManager} instance. - */ - public final HttpClientBuilder setBackoffManager(final BackoffManager backoffManager) { - this.backoffManager = backoffManager; - return this; - } - - /** - * Assigns {@link ServiceUnavailableRetryStrategy} instance. - */ - public final HttpClientBuilder setServiceUnavailableRetryStrategy( - final ServiceUnavailableRetryStrategy serviceUnavailStrategy) { - this.serviceUnavailStrategy = serviceUnavailStrategy; - return this; - } - - /** - * Assigns default {@link CookieStore} instance which will be used for - * request execution if not explicitly set in the client execution context. - */ - public final HttpClientBuilder setDefaultCookieStore(final CookieStore cookieStore) { - this.cookieStore = cookieStore; - return this; - } - - /** - * Assigns default {@link CredentialsProvider} instance which will be used - * for request execution if not explicitly set in the client execution - * context. - */ - public final HttpClientBuilder setDefaultCredentialsProvider( - final CredentialsProvider credentialsProvider) { - this.credentialsProvider = credentialsProvider; - return this; - } - - /** - * Assigns default {@link com.tracelytics.ext.apache.http.auth.AuthScheme} registry which will - * be used for request execution if not explicitly set in the client execution - * context. - */ - public final HttpClientBuilder setDefaultAuthSchemeRegistry( - final Lookup authSchemeRegistry) { - this.authSchemeRegistry = authSchemeRegistry; - return this; - } - - /** - * Assigns default {@link com.tracelytics.ext.apache.http.cookie.CookieSpec} registry which will - * be used for request execution if not explicitly set in the client execution - * context. - */ - public final HttpClientBuilder setDefaultCookieSpecRegistry( - final Lookup cookieSpecRegistry) { - this.cookieSpecRegistry = cookieSpecRegistry; - return this; - } - - - /** - * Assigns a map of {@link com.tracelytics.ext.apache.http.client.entity.InputStreamFactory}s - * to be used for automatic content decompression. - */ - public final HttpClientBuilder setContentDecoderRegistry( - final Map contentDecoderMap) { - this.contentDecoderMap = contentDecoderMap; - return this; - } - - /** - * Assigns default {@link RequestConfig} instance which will be used - * for request execution if not explicitly set in the client execution - * context. - */ - public final HttpClientBuilder setDefaultRequestConfig(final RequestConfig config) { - this.defaultRequestConfig = config; - return this; - } - - /** - * Use system properties when creating and configuring default - * implementations. - */ - public final HttpClientBuilder useSystemProperties() { - this.systemProperties = true; - return this; - } - - /** - * Makes this instance of HttpClient proactively evict expired connections from the - * connection pool using a background thread. - *

- * One MUST explicitly close HttpClient with {@link CloseableHttpClient#close()} in order - * to stop and release the background thread. - *

- * Please note this method has no effect if the instance of HttpClient is configuted to - * use a shared connection manager. - *

- * Please note this method may not be used when the instance of HttpClient is created - * inside an EJB container. - * - * @see #setConnectionManagerShared(boolean) - * @see com.tracelytics.ext.apache.http.conn.HttpClientConnectionManager#closeExpiredConnections() - * - * @since 4.4 - */ - public final HttpClientBuilder evictExpiredConnections() { - evictExpiredConnections = true; - return this; - } - - /** - * Makes this instance of HttpClient proactively evict idle connections from the - * connection pool using a background thread. - *

- * One MUST explicitly close HttpClient with {@link CloseableHttpClient#close()} in order - * to stop and release the background thread. - *

- * Please note this method has no effect if the instance of HttpClient is configuted to - * use a shared connection manager. - *

- * Please note this method may not be used when the instance of HttpClient is created - * inside an EJB container. - * - * @see #setConnectionManagerShared(boolean) - * @see com.tracelytics.ext.apache.http.conn.HttpClientConnectionManager#closeExpiredConnections() - * - * @param maxIdleTime maxium time persistent connections can stay idle while kept alive - * in the connection pool. Connections whose inactivity period exceeds this value will - * get closed and evicted from the pool. - * @param maxIdleTimeUnit time unit for the above parameter. - * - * @since 4.4 - */ - public final HttpClientBuilder evictIdleConnections(final Long maxIdleTime, final TimeUnit maxIdleTimeUnit) { - this.evictIdleConnections = true; - this.maxIdleTime = maxIdleTime; - this.maxIdleTimeUnit = maxIdleTimeUnit; - return this; - } - - /** - * Produces an instance of {@link ClientExecChain} to be used as a main exec. - *

- * Default implementation produces an instance of {@link MainClientExec} - *

- *

- * For internal use. - *

- * - * @since 4.4 - */ - protected ClientExecChain createMainExec( - final HttpRequestExecutor requestExec, - final HttpClientConnectionManager connManager, - final ConnectionReuseStrategy reuseStrategy, - final ConnectionKeepAliveStrategy keepAliveStrategy, - final HttpProcessor proxyHttpProcessor, - final AuthenticationStrategy targetAuthStrategy, - final AuthenticationStrategy proxyAuthStrategy, - final UserTokenHandler userTokenHandler) - { - return new MainClientExec( - requestExec, - connManager, - reuseStrategy, - keepAliveStrategy, - proxyHttpProcessor, - targetAuthStrategy, - proxyAuthStrategy, - userTokenHandler); - } - - /** - * For internal use. - */ - protected ClientExecChain decorateMainExec(final ClientExecChain mainExec) { - return mainExec; - } - - /** - * For internal use. - */ - protected ClientExecChain decorateProtocolExec(final ClientExecChain protocolExec) { - return protocolExec; - } - - /** - * For internal use. - */ - protected void addCloseable(final Closeable closeable) { - if (closeable == null) { - return; - } - if (closeables == null) { - closeables = new ArrayList(); - } - closeables.add(closeable); - } - - private static String[] split(final String s) { - if (TextUtils.isBlank(s)) { - return null; - } - return s.split(" *, *"); - } - - public CloseableHttpClient build() { - // Create main request executor - // We copy the instance fields to avoid changing them, and rename to avoid accidental use of the wrong version - PublicSuffixMatcher publicSuffixMatcherCopy = this.publicSuffixMatcher; - if (publicSuffixMatcherCopy == null) { - publicSuffixMatcherCopy = PublicSuffixMatcherLoader.getDefault(); - } - - HttpRequestExecutor requestExecCopy = this.requestExec; - if (requestExecCopy == null) { - requestExecCopy = new HttpRequestExecutor(); - } - HttpClientConnectionManager connManagerCopy = this.connManager; - if (connManagerCopy == null) { - LayeredConnectionSocketFactory sslSocketFactoryCopy = this.sslSocketFactory; - if (sslSocketFactoryCopy == null) { - final String[] supportedProtocols = systemProperties ? split( - System.getProperty("https.protocols")) : null; - final String[] supportedCipherSuites = systemProperties ? split( - System.getProperty("https.cipherSuites")) : null; - HostnameVerifier hostnameVerifierCopy = this.hostnameVerifier; - if (hostnameVerifierCopy == null) { - hostnameVerifierCopy = new DefaultHostnameVerifier(publicSuffixMatcherCopy); - } - if (sslcontext != null) { - sslSocketFactoryCopy = new SSLConnectionSocketFactory( - sslcontext, supportedProtocols, supportedCipherSuites, hostnameVerifierCopy); - } else { - if (systemProperties) { - sslSocketFactoryCopy = new SSLConnectionSocketFactory( - (SSLSocketFactory) SSLSocketFactory.getDefault(), - supportedProtocols, supportedCipherSuites, hostnameVerifierCopy); - } else { - sslSocketFactoryCopy = new SSLConnectionSocketFactory( - SSLContexts.createDefault(), - hostnameVerifierCopy); - } - } - } - @SuppressWarnings("resource") - final PoolingHttpClientConnectionManager poolingmgr = new PoolingHttpClientConnectionManager( - RegistryBuilder.create() - .register("http", PlainConnectionSocketFactory.getSocketFactory()) - .register("https", sslSocketFactoryCopy) - .build(), - null, - null, - null, - connTimeToLive, - connTimeToLiveTimeUnit != null ? connTimeToLiveTimeUnit : TimeUnit.MILLISECONDS); - if (defaultSocketConfig != null) { - poolingmgr.setDefaultSocketConfig(defaultSocketConfig); - } - if (defaultConnectionConfig != null) { - poolingmgr.setDefaultConnectionConfig(defaultConnectionConfig); - } - if (systemProperties) { - String s = System.getProperty("http.keepAlive", "true"); - if ("true".equalsIgnoreCase(s)) { - s = System.getProperty("http.maxConnections", "5"); - final int max = Integer.parseInt(s); - poolingmgr.setDefaultMaxPerRoute(max); - poolingmgr.setMaxTotal(2 * max); - } - } - if (maxConnTotal > 0) { - poolingmgr.setMaxTotal(maxConnTotal); - } - if (maxConnPerRoute > 0) { - poolingmgr.setDefaultMaxPerRoute(maxConnPerRoute); - } - connManagerCopy = poolingmgr; - } - ConnectionReuseStrategy reuseStrategyCopy = this.reuseStrategy; - if (reuseStrategyCopy == null) { - if (systemProperties) { - final String s = System.getProperty("http.keepAlive", "true"); - if ("true".equalsIgnoreCase(s)) { - reuseStrategyCopy = DefaultConnectionReuseStrategy.INSTANCE; - } else { - reuseStrategyCopy = NoConnectionReuseStrategy.INSTANCE; - } - } else { - reuseStrategyCopy = DefaultConnectionReuseStrategy.INSTANCE; - } - } - ConnectionKeepAliveStrategy keepAliveStrategyCopy = this.keepAliveStrategy; - if (keepAliveStrategyCopy == null) { - keepAliveStrategyCopy = DefaultConnectionKeepAliveStrategy.INSTANCE; - } - AuthenticationStrategy targetAuthStrategyCopy = this.targetAuthStrategy; - if (targetAuthStrategyCopy == null) { - targetAuthStrategyCopy = TargetAuthenticationStrategy.INSTANCE; - } - AuthenticationStrategy proxyAuthStrategyCopy = this.proxyAuthStrategy; - if (proxyAuthStrategyCopy == null) { - proxyAuthStrategyCopy = ProxyAuthenticationStrategy.INSTANCE; - } - UserTokenHandler userTokenHandlerCopy = this.userTokenHandler; - if (userTokenHandlerCopy == null) { - if (!connectionStateDisabled) { - userTokenHandlerCopy = DefaultUserTokenHandler.INSTANCE; - } else { - userTokenHandlerCopy = NoopUserTokenHandler.INSTANCE; - } - } - - String userAgentCopy = this.userAgent; - if (userAgentCopy == null) { - if (systemProperties) { - userAgentCopy = System.getProperty("http.agent"); - } - if (userAgentCopy == null) { - userAgentCopy = VersionInfo.getUserAgent("Apache-HttpClient", - "com.tracelytics.ext.apache.http.client", getClass()); - } - } - - ClientExecChain execChain = createMainExec( - requestExecCopy, - connManagerCopy, - reuseStrategyCopy, - keepAliveStrategyCopy, - new ImmutableHttpProcessor(new RequestTargetHost(), new RequestUserAgent(userAgentCopy)), - targetAuthStrategyCopy, - proxyAuthStrategyCopy, - userTokenHandlerCopy); - - execChain = decorateMainExec(execChain); - - HttpProcessor httpprocessorCopy = this.httpprocessor; - if (httpprocessorCopy == null) { - - final HttpProcessorBuilder b = HttpProcessorBuilder.create(); - if (requestFirst != null) { - for (final HttpRequestInterceptor i: requestFirst) { - b.addFirst(i); - } - } - if (responseFirst != null) { - for (final HttpResponseInterceptor i: responseFirst) { - b.addFirst(i); - } - } - b.addAll( - new RequestDefaultHeaders(defaultHeaders), - new RequestContent(), - new RequestTargetHost(), - new RequestClientConnControl(), - new RequestUserAgent(userAgentCopy), - new RequestExpectContinue()); - if (!cookieManagementDisabled) { - b.add(new RequestAddCookies()); - } - if (!contentCompressionDisabled) { - if (contentDecoderMap != null) { - final List encodings = new ArrayList(contentDecoderMap.keySet()); - Collections.sort(encodings); - b.add(new RequestAcceptEncoding(encodings)); - } else { - b.add(new RequestAcceptEncoding()); - } - } - if (!authCachingDisabled) { - b.add(new RequestAuthCache()); - } - if (!cookieManagementDisabled) { - b.add(new ResponseProcessCookies()); - } - if (!contentCompressionDisabled) { - if (contentDecoderMap != null) { - final RegistryBuilder b2 = RegistryBuilder.create(); - for (Map.Entry entry: contentDecoderMap.entrySet()) { - b2.register(entry.getKey(), entry.getValue()); - } - b.add(new ResponseContentEncoding(b2.build())); - } else { - b.add(new ResponseContentEncoding()); - } - } - if (requestLast != null) { - for (final HttpRequestInterceptor i: requestLast) { - b.addLast(i); - } - } - if (responseLast != null) { - for (final HttpResponseInterceptor i: responseLast) { - b.addLast(i); - } - } - httpprocessorCopy = b.build(); - } - execChain = new ProtocolExec(execChain, httpprocessorCopy); - - execChain = decorateProtocolExec(execChain); - - // Add request retry executor, if not disabled - if (!automaticRetriesDisabled) { - HttpRequestRetryHandler retryHandlerCopy = this.retryHandler; - if (retryHandlerCopy == null) { - retryHandlerCopy = DefaultHttpRequestRetryHandler.INSTANCE; - } - execChain = new RetryExec(execChain, retryHandlerCopy); - } - - HttpRoutePlanner routePlannerCopy = this.routePlanner; - if (routePlannerCopy == null) { - SchemePortResolver schemePortResolverCopy = this.schemePortResolver; - if (schemePortResolverCopy == null) { - schemePortResolverCopy = DefaultSchemePortResolver.INSTANCE; - } - if (proxy != null) { - routePlannerCopy = new DefaultProxyRoutePlanner(proxy, schemePortResolverCopy); - } else if (systemProperties) { - routePlannerCopy = new SystemDefaultRoutePlanner( - schemePortResolverCopy, ProxySelector.getDefault()); - } else { - routePlannerCopy = new DefaultRoutePlanner(schemePortResolverCopy); - } - } - // Add redirect executor, if not disabled - if (!redirectHandlingDisabled) { - RedirectStrategy redirectStrategyCopy = this.redirectStrategy; - if (redirectStrategyCopy == null) { - redirectStrategyCopy = DefaultRedirectStrategy.INSTANCE; - } - execChain = new RedirectExec(execChain, routePlannerCopy, redirectStrategyCopy); - } - - // Optionally, add service unavailable retry executor - final ServiceUnavailableRetryStrategy serviceUnavailStrategyCopy = this.serviceUnavailStrategy; - if (serviceUnavailStrategyCopy != null) { - execChain = new ServiceUnavailableRetryExec(execChain, serviceUnavailStrategyCopy); - } - // Optionally, add connection back-off executor - if (this.backoffManager != null && this.connectionBackoffStrategy != null) { - execChain = new BackoffStrategyExec(execChain, this.connectionBackoffStrategy, this.backoffManager); - } - - Lookup authSchemeRegistryCopy = this.authSchemeRegistry; - if (authSchemeRegistryCopy == null) { - authSchemeRegistryCopy = RegistryBuilder.create() - .register(AuthSchemes.BASIC, new BasicSchemeFactory()) - .register(AuthSchemes.DIGEST, new DigestSchemeFactory()) - .register(AuthSchemes.NTLM, new NTLMSchemeFactory()) - .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()) - .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()) - .build(); - } - Lookup cookieSpecRegistryCopy = this.cookieSpecRegistry; - if (cookieSpecRegistryCopy == null) { - final CookieSpecProvider defaultProvider = new DefaultCookieSpecProvider(publicSuffixMatcherCopy); - final CookieSpecProvider laxStandardProvider = new RFC6265CookieSpecProvider( - RFC6265CookieSpecProvider.CompatibilityLevel.RELAXED, publicSuffixMatcherCopy); - final CookieSpecProvider strictStandardProvider = new RFC6265CookieSpecProvider( - RFC6265CookieSpecProvider.CompatibilityLevel.STRICT, publicSuffixMatcherCopy); - cookieSpecRegistryCopy = RegistryBuilder.create() - .register(CookieSpecs.DEFAULT, defaultProvider) - .register("best-match", defaultProvider) - .register("compatibility", defaultProvider) - .register(CookieSpecs.STANDARD, laxStandardProvider) - .register(CookieSpecs.STANDARD_STRICT, strictStandardProvider) - .register(CookieSpecs.NETSCAPE, new NetscapeDraftSpecProvider()) - .register(CookieSpecs.IGNORE_COOKIES, new IgnoreSpecProvider()) - .build(); - } - - CookieStore defaultCookieStore = this.cookieStore; - if (defaultCookieStore == null) { - defaultCookieStore = new BasicCookieStore(); - } - - CredentialsProvider defaultCredentialsProvider = this.credentialsProvider; - if (defaultCredentialsProvider == null) { - if (systemProperties) { - defaultCredentialsProvider = new SystemDefaultCredentialsProvider(); - } else { - defaultCredentialsProvider = new BasicCredentialsProvider(); - } - } - - List closeablesCopy = closeables != null ? new ArrayList(closeables) : null; - if (!this.connManagerShared) { - if (closeablesCopy == null) { - closeablesCopy = new ArrayList(1); - } - final HttpClientConnectionManager cm = connManagerCopy; - - if (evictExpiredConnections || evictIdleConnections) { - final IdleConnectionEvictor connectionEvictor = new IdleConnectionEvictor(cm, - maxIdleTime > 0 ? maxIdleTime : 10, maxIdleTimeUnit != null ? maxIdleTimeUnit : TimeUnit.SECONDS); - closeablesCopy.add(new Closeable() { - - @Override - public void close() throws IOException { - connectionEvictor.shutdown(); - } - - }); - connectionEvictor.start(); - } - closeablesCopy.add(new Closeable() { - - @Override - public void close() throws IOException { - cm.shutdown(); - } - - }); - } - - return new InternalHttpClient( - execChain, - connManagerCopy, - routePlannerCopy, - cookieSpecRegistryCopy, - authSchemeRegistryCopy, - defaultCookieStore, - defaultCredentialsProvider, - defaultRequestConfig != null ? defaultRequestConfig : RequestConfig.DEFAULT, - closeablesCopy); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/HttpClients.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/HttpClients.java deleted file mode 100644 index bb217311..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/HttpClients.java +++ /dev/null @@ -1,86 +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 com.tracelytics.ext.apache.http.impl.client; - -import com.tracelytics.ext.apache.http.annotation.Immutable; - -import com.tracelytics.ext.apache.http.conn.HttpClientConnectionManager; -import com.tracelytics.ext.apache.http.impl.conn.PoolingHttpClientConnectionManager; - -/** - * Factory methods for {@link CloseableHttpClient} instances. - * @since 4.3 - */ -@Immutable -public class HttpClients { - - private HttpClients() { - super(); - } - - /** - * Creates builder object for construction of custom - * {@link CloseableHttpClient} instances. - */ - public static HttpClientBuilder custom() { - return HttpClientBuilder.create(); - } - - /** - * Creates {@link CloseableHttpClient} instance with default - * configuration. - */ - public static CloseableHttpClient createDefault() { - return HttpClientBuilder.create().build(); - } - - /** - * Creates {@link CloseableHttpClient} instance with default - * configuration based on ssytem properties. - */ - public static CloseableHttpClient createSystem() { - return HttpClientBuilder.create().useSystemProperties().build(); - } - - /** - * Creates {@link CloseableHttpClient} instance that implements - * the most basic HTTP protocol support. - */ - public static CloseableHttpClient createMinimal() { - return new MinimalHttpClient(new PoolingHttpClientConnectionManager()); - } - - /** - * Creates {@link CloseableHttpClient} instance that implements - * the most basic HTTP protocol support. - */ - public static CloseableHttpClient createMinimal(final HttpClientConnectionManager connManager) { - return new MinimalHttpClient(connManager); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/HttpRequestFutureTask.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/HttpRequestFutureTask.java deleted file mode 100644 index 27e3ab3d..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/HttpRequestFutureTask.java +++ /dev/null @@ -1,118 +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 com.tracelytics.ext.apache.http.impl.client; - -import java.util.concurrent.FutureTask; - -import com.tracelytics.ext.apache.http.client.methods.HttpUriRequest; - -/** - * FutureTask implementation that wraps a HttpAsyncClientCallable and exposes various task - * specific metrics. - * - * @param - */ -public class HttpRequestFutureTask extends FutureTask { - - private final HttpUriRequest request; - private final HttpRequestTaskCallable callable; - - public HttpRequestFutureTask( - final HttpUriRequest request, - final HttpRequestTaskCallable httpCallable) { - super(httpCallable); - this.request = request; - this.callable = httpCallable; - } - - /* - * (non-Javadoc) - * @see java.util.concurrent.FutureTask#cancel(boolean) - */ - @Override - public boolean cancel(final boolean mayInterruptIfRunning) { - callable.cancel(); - if (mayInterruptIfRunning) { - request.abort(); - } - return super.cancel(mayInterruptIfRunning); - } - - /** - * @return the time in millis the task was scheduled. - */ - public long scheduledTime() { - return callable.getScheduled(); - } - - /** - * @return the time in millis the task was started. - */ - public long startedTime() { - return callable.getStarted(); - } - - /** - * @return the time in millis the task was finished/cancelled. - */ - public long endedTime() { - if (isDone()) { - return callable.getEnded(); - } else { - throw new IllegalStateException("Task is not done yet"); - } - } - - /** - * @return the time in millis it took to make the request (excluding the time it was - * scheduled to be executed). - */ - public long requestDuration() { - if (isDone()) { - return endedTime() - startedTime(); - } else { - throw new IllegalStateException("Task is not done yet"); - } - } - - /** - * @return the time in millis it took to execute the task from the moment it was scheduled. - */ - public long taskDuration() { - if (isDone()) { - return endedTime() - scheduledTime(); - } else { - throw new IllegalStateException("Task is not done yet"); - } - } - - @Override - public String toString() { - return request.getRequestLine().getUri(); - } - -} \ No newline at end of file diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/HttpRequestTaskCallable.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/HttpRequestTaskCallable.java deleted file mode 100644 index 7ba67ac3..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/HttpRequestTaskCallable.java +++ /dev/null @@ -1,121 +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 com.tracelytics.ext.apache.http.impl.client; - -import java.util.concurrent.Callable; -import java.util.concurrent.atomic.AtomicBoolean; - -import com.tracelytics.ext.apache.http.concurrent.FutureCallback; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -import com.tracelytics.ext.apache.http.client.HttpClient; -import com.tracelytics.ext.apache.http.client.ResponseHandler; -import com.tracelytics.ext.apache.http.client.methods.HttpUriRequest; - -class HttpRequestTaskCallable implements Callable { - - private final HttpUriRequest request; - private final HttpClient httpclient; - private final AtomicBoolean cancelled = new AtomicBoolean(false); - - private final long scheduled = System.currentTimeMillis(); - private long started = -1; - private long ended = -1; - - private final HttpContext context; - private final ResponseHandler responseHandler; - private final FutureCallback callback; - - private final FutureRequestExecutionMetrics metrics; - - HttpRequestTaskCallable( - final HttpClient httpClient, - final HttpUriRequest request, - final HttpContext context, - final ResponseHandler responseHandler, - final FutureCallback callback, - final FutureRequestExecutionMetrics metrics) { - this.httpclient = httpClient; - this.responseHandler = responseHandler; - this.request = request; - this.context = context; - this.callback = callback; - this.metrics = metrics; - } - - public long getScheduled() { - return scheduled; - } - - public long getStarted() { - return started; - } - - public long getEnded() { - return ended; - } - - @Override - public V call() throws Exception { - if (!cancelled.get()) { - try { - metrics.getActiveConnections().incrementAndGet(); - started = System.currentTimeMillis(); - try { - metrics.getScheduledConnections().decrementAndGet(); - final V result = httpclient.execute(request, responseHandler, context); - ended = System.currentTimeMillis(); - metrics.getSuccessfulConnections().increment(started); - if (callback != null) { - callback.completed(result); - } - return result; - } catch (final Exception e) { - metrics.getFailedConnections().increment(started); - ended = System.currentTimeMillis(); - if (callback != null) { - callback.failed(e); - } - throw e; - } - } finally { - metrics.getRequests().increment(started); - metrics.getTasks().increment(started); - metrics.getActiveConnections().decrementAndGet(); - } - } else { - throw new IllegalStateException("call has been cancelled for request " + request.getURI()); - } - } - - public void cancel() { - cancelled.set(true); - if (callback != null) { - callback.cancelled(); - } - } -} \ No newline at end of file diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/IdleConnectionEvictor.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/IdleConnectionEvictor.java deleted file mode 100644 index 99e73cb5..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/IdleConnectionEvictor.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 com.tracelytics.ext.apache.http.impl.client; - -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; - -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.conn.HttpClientConnectionManager; - -/** - * This class maintains a background thread to enforce an eviction policy for expired / idle - * persistent connections kept alive in the connection pool. - * - * @since 4.4 - */ -public final class IdleConnectionEvictor { - - private final HttpClientConnectionManager connectionManager; - private final ThreadFactory threadFactory; - private final Thread thread; - private final long sleepTimeMs; - private final long maxIdleTimeMs; - - private volatile Exception exception; - - public IdleConnectionEvictor( - final HttpClientConnectionManager connectionManager, - final ThreadFactory threadFactory, - final long sleepTime, final TimeUnit sleepTimeUnit, - final long maxIdleTime, final TimeUnit maxIdleTimeUnit) { - this.connectionManager = Args.notNull(connectionManager, "Connection manager"); - this.threadFactory = threadFactory != null ? threadFactory : new DefaultThreadFactory(); - this.sleepTimeMs = sleepTimeUnit != null ? sleepTimeUnit.toMillis(sleepTime) : sleepTime; - this.maxIdleTimeMs = maxIdleTimeUnit != null ? maxIdleTimeUnit.toMillis(maxIdleTime) : maxIdleTime; - this.thread = this.threadFactory.newThread(new Runnable() { - @Override - public void run() { - try { - while (!Thread.currentThread().isInterrupted()) { - Thread.sleep(sleepTimeMs); - connectionManager.closeExpiredConnections(); - if (maxIdleTimeMs > 0) { - connectionManager.closeIdleConnections(maxIdleTimeMs, TimeUnit.MILLISECONDS); - } - } - } catch (Exception ex) { - exception = ex; - } - - } - }); - } - - public IdleConnectionEvictor( - final HttpClientConnectionManager connectionManager, - final long sleepTime, final TimeUnit sleepTimeUnit, - final long maxIdleTime, final TimeUnit maxIdleTimeUnit) { - this(connectionManager, null, sleepTime, sleepTimeUnit, maxIdleTime, maxIdleTimeUnit); - } - - public IdleConnectionEvictor( - final HttpClientConnectionManager connectionManager, - final long maxIdleTime, final TimeUnit maxIdleTimeUnit) { - this(connectionManager, null, - maxIdleTime > 0 ? maxIdleTime : 5, maxIdleTimeUnit != null ? maxIdleTimeUnit : TimeUnit.SECONDS, - maxIdleTime, maxIdleTimeUnit); - } - - public void start() { - thread.start(); - } - - public void shutdown() { - thread.interrupt(); - } - - public boolean isRunning() { - return thread.isAlive(); - } - - public void awaitTermination(final long time, final TimeUnit tunit) throws InterruptedException { - thread.join((tunit != null ? tunit : TimeUnit.MILLISECONDS).toMillis(time)); - } - - static class DefaultThreadFactory implements ThreadFactory { - - @Override - public Thread newThread(final Runnable r) { - final Thread t = new Thread(r, "Connection evictor"); - t.setDaemon(true); - return t; - } - - }; - - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/InternalHttpClient.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/InternalHttpClient.java deleted file mode 100644 index 481b9de2..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/InternalHttpClient.java +++ /dev/null @@ -1,255 +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 com.tracelytics.ext.apache.http.impl.client; - -import java.io.Closeable; -import java.io.IOException; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.auth.AuthSchemeProvider; -import com.tracelytics.ext.apache.http.auth.AuthState; -import com.tracelytics.ext.apache.http.client.ClientProtocolException; -import com.tracelytics.ext.apache.http.client.CookieStore; -import com.tracelytics.ext.apache.http.client.CredentialsProvider; -import com.tracelytics.ext.apache.http.client.config.RequestConfig; -import com.tracelytics.ext.apache.http.client.methods.CloseableHttpResponse; -import com.tracelytics.ext.apache.http.client.methods.Configurable; -import com.tracelytics.ext.apache.http.client.methods.HttpExecutionAware; -import com.tracelytics.ext.apache.http.client.methods.HttpRequestWrapper; -import com.tracelytics.ext.apache.http.client.params.ClientPNames; -import com.tracelytics.ext.apache.http.client.params.HttpClientParamConfig; -import com.tracelytics.ext.apache.http.client.protocol.HttpClientContext; -import com.tracelytics.ext.apache.http.config.Lookup; -import com.tracelytics.ext.apache.http.conn.ClientConnectionManager; -import com.tracelytics.ext.apache.http.conn.ClientConnectionRequest; -import com.tracelytics.ext.apache.http.conn.HttpClientConnectionManager; -import com.tracelytics.ext.apache.http.conn.ManagedClientConnection; -import com.tracelytics.ext.apache.http.conn.routing.HttpRoute; -import com.tracelytics.ext.apache.http.conn.routing.HttpRoutePlanner; -import com.tracelytics.ext.apache.http.conn.scheme.SchemeRegistry; -import com.tracelytics.ext.apache.http.cookie.CookieSpecProvider; -import com.tracelytics.ext.apache.http.impl.execchain.ClientExecChain; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.params.HttpParamsNames; -import com.tracelytics.ext.apache.http.protocol.BasicHttpContext; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Internal class. - * - * @since 4.3 - */ -@ThreadSafe -@SuppressWarnings("deprecation") -class InternalHttpClient extends CloseableHttpClient implements Configurable { - - private final Logger log = Logger.getLogger(getClass().getName()); - - private final ClientExecChain execChain; - private final HttpClientConnectionManager connManager; - private final HttpRoutePlanner routePlanner; - private final Lookup cookieSpecRegistry; - private final Lookup authSchemeRegistry; - private final CookieStore cookieStore; - private final CredentialsProvider credentialsProvider; - private final RequestConfig defaultConfig; - private final List closeables; - - public InternalHttpClient( - final ClientExecChain execChain, - final HttpClientConnectionManager connManager, - final HttpRoutePlanner routePlanner, - final Lookup cookieSpecRegistry, - final Lookup authSchemeRegistry, - final CookieStore cookieStore, - final CredentialsProvider credentialsProvider, - final RequestConfig defaultConfig, - final List closeables) { - super(); - Args.notNull(execChain, "HTTP client exec chain"); - Args.notNull(connManager, "HTTP connection manager"); - Args.notNull(routePlanner, "HTTP route planner"); - this.execChain = execChain; - this.connManager = connManager; - this.routePlanner = routePlanner; - this.cookieSpecRegistry = cookieSpecRegistry; - this.authSchemeRegistry = authSchemeRegistry; - this.cookieStore = cookieStore; - this.credentialsProvider = credentialsProvider; - this.defaultConfig = defaultConfig; - this.closeables = closeables; - } - - private HttpRoute determineRoute( - final HttpHost target, - final HttpRequest request, - final HttpContext context) throws HttpException { - HttpHost host = target; - if (host == null) { - host = (HttpHost) request.getParams().getParameter(ClientPNames.DEFAULT_HOST); - } - return this.routePlanner.determineRoute(host, request, context); - } - - private void setupContext(final HttpClientContext context) { - if (context.getAttribute(HttpClientContext.TARGET_AUTH_STATE) == null) { - context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, new AuthState()); - } - if (context.getAttribute(HttpClientContext.PROXY_AUTH_STATE) == null) { - context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, new AuthState()); - } - if (context.getAttribute(HttpClientContext.AUTHSCHEME_REGISTRY) == null) { - context.setAttribute(HttpClientContext.AUTHSCHEME_REGISTRY, this.authSchemeRegistry); - } - if (context.getAttribute(HttpClientContext.COOKIESPEC_REGISTRY) == null) { - context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry); - } - if (context.getAttribute(HttpClientContext.COOKIE_STORE) == null) { - context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore); - } - if (context.getAttribute(HttpClientContext.CREDS_PROVIDER) == null) { - context.setAttribute(HttpClientContext.CREDS_PROVIDER, this.credentialsProvider); - } - if (context.getAttribute(HttpClientContext.REQUEST_CONFIG) == null) { - context.setAttribute(HttpClientContext.REQUEST_CONFIG, this.defaultConfig); - } - } - - @Override - protected CloseableHttpResponse doExecute( - final HttpHost target, - final HttpRequest request, - final HttpContext context) throws IOException, ClientProtocolException { - Args.notNull(request, "HTTP request"); - HttpExecutionAware execAware = null; - if (request instanceof HttpExecutionAware) { - execAware = (HttpExecutionAware) request; - } - try { - final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(request, target); - final HttpClientContext localcontext = HttpClientContext.adapt( - context != null ? context : new BasicHttpContext()); - RequestConfig config = null; - if (request instanceof Configurable) { - config = ((Configurable) request).getConfig(); - } - if (config == null) { - final HttpParams params = request.getParams(); - if (params instanceof HttpParamsNames) { - if (!((HttpParamsNames) params).getNames().isEmpty()) { - config = HttpClientParamConfig.getRequestConfig(params); - } - } else { - config = HttpClientParamConfig.getRequestConfig(params); - } - } - if (config != null) { - localcontext.setRequestConfig(config); - } - setupContext(localcontext); - final HttpRoute route = determineRoute(target, wrapper, localcontext); - return this.execChain.execute(route, wrapper, localcontext, execAware); - } catch (final HttpException httpException) { - throw new ClientProtocolException(httpException); - } - } - - @Override - public RequestConfig getConfig() { - return this.defaultConfig; - } - - @Override - public void close() { - if (this.closeables != null) { - for (final Closeable closeable: this.closeables) { - try { - closeable.close(); - } catch (final IOException ex) { - this.log.log(Level.WARNING, ex.getMessage(), ex); - } - } - } - } - - @Override - public HttpParams getParams() { - throw new UnsupportedOperationException(); - } - - @Override - public ClientConnectionManager getConnectionManager() { - - return new ClientConnectionManager() { - - @Override - public void shutdown() { - connManager.shutdown(); - } - - @Override - public ClientConnectionRequest requestConnection( - final HttpRoute route, final Object state) { - throw new UnsupportedOperationException(); - } - - @Override - public void releaseConnection( - final ManagedClientConnection conn, - final long validDuration, final TimeUnit timeUnit) { - throw new UnsupportedOperationException(); - } - - @Override - public SchemeRegistry getSchemeRegistry() { - throw new UnsupportedOperationException(); - } - - @Override - public void closeIdleConnections(final long idletime, final TimeUnit tunit) { - connManager.closeIdleConnections(idletime, tunit); - } - - @Override - public void closeExpiredConnections() { - connManager.closeExpiredConnections(); - } - - }; - - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/LaxRedirectStrategy.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/LaxRedirectStrategy.java deleted file mode 100644 index 3ddd0c4f..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/LaxRedirectStrategy.java +++ /dev/null @@ -1,66 +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 com.tracelytics.ext.apache.http.impl.client; - -import com.tracelytics.ext.apache.http.annotation.Immutable; - -import com.tracelytics.ext.apache.http.client.methods.HttpGet; -import com.tracelytics.ext.apache.http.client.methods.HttpHead; -import com.tracelytics.ext.apache.http.client.methods.HttpPost; - -/** - * Lax {@link com.tracelytics.ext.apache.http.client.RedirectStrategy} implementation - * that automatically redirects all HEAD, GET and POST requests. - * This strategy relaxes restrictions on automatic redirection of - * POST methods imposed by the HTTP specification. - * - * @since 4.2 - */ -@Immutable -public class LaxRedirectStrategy extends DefaultRedirectStrategy { - - /** - * Redirectable methods. - */ - private static final String[] REDIRECT_METHODS = new String[] { - HttpGet.METHOD_NAME, - HttpPost.METHOD_NAME, - HttpHead.METHOD_NAME - }; - - @Override - protected boolean isRedirectable(final String method) { - for (final String m: REDIRECT_METHODS) { - if (m.equalsIgnoreCase(method)) { - return true; - } - } - return false; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/MinimalHttpClient.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/MinimalHttpClient.java deleted file mode 100644 index f91ba6d2..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/MinimalHttpClient.java +++ /dev/null @@ -1,166 +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 com.tracelytics.ext.apache.http.impl.client; - -import java.io.IOException; -import java.util.concurrent.TimeUnit; - -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.impl.DefaultConnectionReuseStrategy; -import com.tracelytics.ext.apache.http.params.BasicHttpParams; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.protocol.BasicHttpContext; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.protocol.HttpRequestExecutor; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.client.ClientProtocolException; -import com.tracelytics.ext.apache.http.client.config.RequestConfig; -import com.tracelytics.ext.apache.http.client.methods.CloseableHttpResponse; -import com.tracelytics.ext.apache.http.client.methods.Configurable; -import com.tracelytics.ext.apache.http.client.methods.HttpExecutionAware; -import com.tracelytics.ext.apache.http.client.methods.HttpRequestWrapper; -import com.tracelytics.ext.apache.http.client.protocol.HttpClientContext; -import com.tracelytics.ext.apache.http.conn.ClientConnectionManager; -import com.tracelytics.ext.apache.http.conn.ClientConnectionRequest; -import com.tracelytics.ext.apache.http.conn.HttpClientConnectionManager; -import com.tracelytics.ext.apache.http.conn.ManagedClientConnection; -import com.tracelytics.ext.apache.http.conn.routing.HttpRoute; -import com.tracelytics.ext.apache.http.conn.scheme.SchemeRegistry; -import com.tracelytics.ext.apache.http.impl.execchain.MinimalClientExec; - -/** - * Internal class. - * - * @since 4.3 - */ -@ThreadSafe -@SuppressWarnings("deprecation") -class MinimalHttpClient extends CloseableHttpClient { - - private final HttpClientConnectionManager connManager; - private final MinimalClientExec requestExecutor; - private final HttpParams params; - - public MinimalHttpClient( - final HttpClientConnectionManager connManager) { - super(); - this.connManager = Args.notNull(connManager, "HTTP connection manager"); - this.requestExecutor = new MinimalClientExec( - new HttpRequestExecutor(), - connManager, - DefaultConnectionReuseStrategy.INSTANCE, - DefaultConnectionKeepAliveStrategy.INSTANCE); - this.params = new BasicHttpParams(); - } - - @Override - protected CloseableHttpResponse doExecute( - final HttpHost target, - final HttpRequest request, - final HttpContext context) throws IOException, ClientProtocolException { - Args.notNull(target, "Target host"); - Args.notNull(request, "HTTP request"); - HttpExecutionAware execAware = null; - if (request instanceof HttpExecutionAware) { - execAware = (HttpExecutionAware) request; - } - try { - final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(request); - final HttpClientContext localcontext = HttpClientContext.adapt( - context != null ? context : new BasicHttpContext()); - final HttpRoute route = new HttpRoute(target); - RequestConfig config = null; - if (request instanceof Configurable) { - config = ((Configurable) request).getConfig(); - } - if (config != null) { - localcontext.setRequestConfig(config); - } - return this.requestExecutor.execute(route, wrapper, localcontext, execAware); - } catch (final HttpException httpException) { - throw new ClientProtocolException(httpException); - } - } - - @Override - public HttpParams getParams() { - return this.params; - } - - @Override - public void close() { - this.connManager.shutdown(); - } - - @Override - public ClientConnectionManager getConnectionManager() { - - return new ClientConnectionManager() { - - @Override - public void shutdown() { - connManager.shutdown(); - } - - @Override - public ClientConnectionRequest requestConnection( - final HttpRoute route, final Object state) { - throw new UnsupportedOperationException(); - } - - @Override - public void releaseConnection( - final ManagedClientConnection conn, - final long validDuration, final TimeUnit timeUnit) { - throw new UnsupportedOperationException(); - } - - @Override - public SchemeRegistry getSchemeRegistry() { - throw new UnsupportedOperationException(); - } - - @Override - public void closeIdleConnections(final long idletime, final TimeUnit tunit) { - connManager.closeIdleConnections(idletime, tunit); - } - - @Override - public void closeExpiredConnections() { - connManager.closeExpiredConnections(); - } - - }; - - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/NoopUserTokenHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/NoopUserTokenHandler.java deleted file mode 100644 index c36f5b22..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/NoopUserTokenHandler.java +++ /dev/null @@ -1,49 +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 com.tracelytics.ext.apache.http.impl.client; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -import com.tracelytics.ext.apache.http.client.UserTokenHandler; - -/** - * Noop implementation of {@link UserTokenHandler} that always returns {@code null}. - * - * @since 4.3 - */ -@Immutable -public class NoopUserTokenHandler implements UserTokenHandler { - - public static final NoopUserTokenHandler INSTANCE = new NoopUserTokenHandler(); - - @Override - public Object getUserToken(final HttpContext context) { - return null; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/NullBackoffStrategy.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/NullBackoffStrategy.java deleted file mode 100644 index fab8e9fb..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/NullBackoffStrategy.java +++ /dev/null @@ -1,50 +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 com.tracelytics.ext.apache.http.impl.client; - -import com.tracelytics.ext.apache.http.HttpResponse; - -import com.tracelytics.ext.apache.http.client.ConnectionBackoffStrategy; - -/** - * This is a {@link ConnectionBackoffStrategy} that never backs off, - * for compatibility with existing behavior. - * - * @since 4.2 - */ -public class NullBackoffStrategy implements ConnectionBackoffStrategy { - - @Override - public boolean shouldBackoff(final Throwable t) { - return false; - } - - @Override - public boolean shouldBackoff(final HttpResponse resp) { - return false; - } -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/ProxyAuthenticationStrategy.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/ProxyAuthenticationStrategy.java deleted file mode 100644 index 58aa8e0b..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/ProxyAuthenticationStrategy.java +++ /dev/null @@ -1,58 +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 com.tracelytics.ext.apache.http.impl.client; - -import java.util.Collection; - -import com.tracelytics.ext.apache.http.HttpStatus; -import com.tracelytics.ext.apache.http.annotation.Immutable; - -import com.tracelytics.ext.apache.http.auth.AUTH; -import com.tracelytics.ext.apache.http.client.config.RequestConfig; - -/** - * Default {@link com.tracelytics.ext.apache.http.client.AuthenticationStrategy} implementation - * for proxy host authentication. - * - * @since 4.2 - */ -@Immutable -public class ProxyAuthenticationStrategy extends AuthenticationStrategyImpl { - - public static final ProxyAuthenticationStrategy INSTANCE = new ProxyAuthenticationStrategy(); - - public ProxyAuthenticationStrategy() { - super(HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED, AUTH.PROXY_AUTH); - } - - @Override - Collection getPreferredAuthSchemes(final RequestConfig config) { - return config.getProxyPreferredAuthSchemes(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/ProxyClient.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/ProxyClient.java deleted file mode 100644 index d5bc41bd..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/ProxyClient.java +++ /dev/null @@ -1,255 +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 com.tracelytics.ext.apache.http.impl.client; - -import java.io.IOException; -import java.net.Socket; - -import com.tracelytics.ext.apache.http.ConnectionReuseStrategy; -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.HttpVersion; -import com.tracelytics.ext.apache.http.config.ConnectionConfig; -import com.tracelytics.ext.apache.http.entity.BufferedHttpEntity; -import com.tracelytics.ext.apache.http.impl.DefaultConnectionReuseStrategy; -import com.tracelytics.ext.apache.http.message.BasicHttpRequest; -import com.tracelytics.ext.apache.http.params.BasicHttpParams; -import com.tracelytics.ext.apache.http.params.HttpParamConfig; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.protocol.BasicHttpContext; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.protocol.HttpCoreContext; -import com.tracelytics.ext.apache.http.protocol.HttpProcessor; -import com.tracelytics.ext.apache.http.protocol.HttpRequestExecutor; -import com.tracelytics.ext.apache.http.protocol.ImmutableHttpProcessor; -import com.tracelytics.ext.apache.http.protocol.RequestTargetHost; -import com.tracelytics.ext.apache.http.protocol.RequestUserAgent; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.EntityUtils; - -import com.tracelytics.ext.apache.http.auth.AUTH; -import com.tracelytics.ext.apache.http.auth.AuthSchemeRegistry; -import com.tracelytics.ext.apache.http.auth.AuthScope; -import com.tracelytics.ext.apache.http.auth.AuthState; -import com.tracelytics.ext.apache.http.auth.Credentials; -import com.tracelytics.ext.apache.http.client.config.AuthSchemes; -import com.tracelytics.ext.apache.http.client.config.RequestConfig; -import com.tracelytics.ext.apache.http.client.params.HttpClientParamConfig; -import com.tracelytics.ext.apache.http.client.protocol.HttpClientContext; -import com.tracelytics.ext.apache.http.client.protocol.RequestClientConnControl; -import com.tracelytics.ext.apache.http.conn.HttpConnectionFactory; -import com.tracelytics.ext.apache.http.conn.ManagedHttpClientConnection; -import com.tracelytics.ext.apache.http.conn.routing.HttpRoute; -import com.tracelytics.ext.apache.http.conn.routing.RouteInfo.LayerType; -import com.tracelytics.ext.apache.http.conn.routing.RouteInfo.TunnelType; -import com.tracelytics.ext.apache.http.impl.auth.BasicSchemeFactory; -import com.tracelytics.ext.apache.http.impl.auth.DigestSchemeFactory; -import com.tracelytics.ext.apache.http.impl.auth.HttpAuthenticator; -import com.tracelytics.ext.apache.http.impl.auth.KerberosSchemeFactory; -import com.tracelytics.ext.apache.http.impl.auth.NTLMSchemeFactory; -import com.tracelytics.ext.apache.http.impl.auth.SPNegoSchemeFactory; -import com.tracelytics.ext.apache.http.impl.conn.ManagedHttpClientConnectionFactory; -import com.tracelytics.ext.apache.http.impl.execchain.TunnelRefusedException; - -/** - * ProxyClient can be used to establish a tunnel via an HTTP proxy. - */ -@SuppressWarnings("deprecation") -public class ProxyClient { - - private final HttpConnectionFactory connFactory; - private final ConnectionConfig connectionConfig; - private final RequestConfig requestConfig; - private final HttpProcessor httpProcessor; - private final HttpRequestExecutor requestExec; - private final ProxyAuthenticationStrategy proxyAuthStrategy; - private final HttpAuthenticator authenticator; - private final AuthState proxyAuthState; - private final AuthSchemeRegistry authSchemeRegistry; - private final ConnectionReuseStrategy reuseStrategy; - - /** - * @since 4.3 - */ - public ProxyClient( - final HttpConnectionFactory connFactory, - final ConnectionConfig connectionConfig, - final RequestConfig requestConfig) { - super(); - 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( - new RequestTargetHost(), new RequestClientConnControl(), new RequestUserAgent()); - this.requestExec = new HttpRequestExecutor(); - this.proxyAuthStrategy = new ProxyAuthenticationStrategy(); - this.authenticator = new HttpAuthenticator(); - this.proxyAuthState = new AuthState(); - this.authSchemeRegistry = new AuthSchemeRegistry(); - this.authSchemeRegistry.register(AuthSchemes.BASIC, new BasicSchemeFactory()); - this.authSchemeRegistry.register(AuthSchemes.DIGEST, new DigestSchemeFactory()); - this.authSchemeRegistry.register(AuthSchemes.NTLM, new NTLMSchemeFactory()); - this.authSchemeRegistry.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()); - this.authSchemeRegistry.register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()); - this.reuseStrategy = new DefaultConnectionReuseStrategy(); - } - - /** - * @deprecated (4.3) use {@link ProxyClient#ProxyClient(HttpConnectionFactory, ConnectionConfig, RequestConfig)} - */ - @Deprecated - public ProxyClient(final HttpParams params) { - this(null, - HttpParamConfig.getConnectionConfig(params), - HttpClientParamConfig.getRequestConfig(params)); - } - - /** - * @since 4.3 - */ - public ProxyClient(final RequestConfig requestConfig) { - this(null, null, requestConfig); - } - - public ProxyClient() { - this(null, null, null); - } - - /** - * @deprecated (4.3) do not use. - */ - @Deprecated - public HttpParams getParams() { - return new BasicHttpParams(); - } - - /** - * @deprecated (4.3) do not use. - */ - @Deprecated - public AuthSchemeRegistry getAuthSchemeRegistry() { - return this.authSchemeRegistry; - } - - public Socket tunnel( - final HttpHost proxy, - final HttpHost target, - final Credentials credentials) throws IOException, HttpException { - Args.notNull(proxy, "Proxy host"); - Args.notNull(target, "Target host"); - Args.notNull(credentials, "Credentials"); - HttpHost host = target; - if (host.getPort() <= 0) { - host = new HttpHost(host.getHostName(), 80, host.getSchemeName()); - } - final HttpRoute route = new HttpRoute( - host, - this.requestConfig.getLocalAddress(), - proxy, false, TunnelType.TUNNELLED, LayerType.PLAIN); - - final ManagedHttpClientConnection conn = this.connFactory.create( - route, this.connectionConfig); - final HttpContext context = new BasicHttpContext(); - HttpResponse response; - - final HttpRequest connect = new BasicHttpRequest( - "CONNECT", host.toHostString(), HttpVersion.HTTP_1_1); - - 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); - context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, this.proxyAuthState); - context.setAttribute(HttpClientContext.CREDS_PROVIDER, credsProvider); - context.setAttribute(HttpClientContext.AUTHSCHEME_REGISTRY, this.authSchemeRegistry); - context.setAttribute(HttpClientContext.REQUEST_CONFIG, this.requestConfig); - - this.requestExec.preProcess(connect, this.httpProcessor, context); - - for (;;) { - if (!conn.isOpen()) { - final Socket socket = new Socket(proxy.getHostName(), proxy.getPort()); - conn.bind(socket); - } - - this.authenticator.generateAuthResponse(connect, this.proxyAuthState, context); - - response = this.requestExec.execute(connect, conn, context); - - final int status = response.getStatusLine().getStatusCode(); - if (status < 200) { - throw new HttpException("Unexpected response to CONNECT request: " + - response.getStatusLine()); - } - if (this.authenticator.isAuthenticationRequested(proxy, response, - this.proxyAuthStrategy, this.proxyAuthState, context)) { - if (this.authenticator.handleAuthChallenge(proxy, response, - this.proxyAuthStrategy, this.proxyAuthState, context)) { - // Retry request - if (this.reuseStrategy.keepAlive(response, context)) { - // Consume response content - final HttpEntity entity = response.getEntity(); - EntityUtils.consume(entity); - } else { - conn.close(); - } - // discard previous auth header - connect.removeHeaders(AUTH.PROXY_AUTH_RESP); - } else { - break; - } - } else { - break; - } - } - - final int status = response.getStatusLine().getStatusCode(); - - if (status > 299) { - - // Buffer response content - final HttpEntity entity = response.getEntity(); - if (entity != null) { - response.setEntity(new BufferedHttpEntity(entity)); - } - - conn.close(); - throw new TunnelRefusedException("CONNECT refused by proxy: " + - response.getStatusLine(), response); - } - return conn.getSocket(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/RedirectLocations.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/RedirectLocations.java deleted file mode 100644 index 2ee263e1..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/RedirectLocations.java +++ /dev/null @@ -1,227 +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 com.tracelytics.ext.apache.http.impl.client; - -import java.net.URI; -import java.util.AbstractList; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import com.tracelytics.ext.apache.http.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; - private final List all; - - public RedirectLocations() { - super(); - this.unique = new HashSet(); - this.all = new ArrayList(); - } - - /** - * Test if the URI is present in the collection. - */ - public boolean contains(final URI uri) { - return this.unique.contains(uri); - } - - /** - * Adds a new URI to the collection. - */ - public void add(final URI uri) { - this.unique.add(uri); - this.all.add(uri); - } - - /** - * Removes a URI from the collection. - */ - public boolean remove(final URI uri) { - final boolean removed = this.unique.remove(uri); - if (removed) { - final Iterator it = this.all.iterator(); - while (it.hasNext()) { - final URI current = it.next(); - if (current.equals(uri)) { - it.remove(); - } - } - } - return removed; - } - - /** - * Returns all redirect {@link URI}s in the order they were added to the collection. - * - * @return list of all URIs - * - * @since 4.1 - */ - public List getAll() { - return new ArrayList(this.all); - } - - /** - * Returns the URI at the specified position in this list. - * - * @param index - * index of the location to return - * @return the URI at the specified position in this list - * @throws IndexOutOfBoundsException - * if the index is out of range ( - * {@code index < 0 || index >= size()}) - * @since 4.3 - */ - @Override - public URI get(final int index) { - return this.all.get(index); - } - - /** - * Returns the number of elements in this list. If this list contains more - * than {@code Integer.MAX_VALUE} elements, returns - * {@code Integer.MAX_VALUE}. - * - * @return the number of elements in this list - * @since 4.3 - */ - @Override - public int size() { - return this.all.size(); - } - - /** - * Replaces the URI at the specified position in this list with the - * specified element (must be a URI). - * - * @param index - * index of the element to replace - * @param element - * URI to be stored at the specified position - * @return the URI previously at the specified position - * @throws UnsupportedOperationException - * if the {@code set} operation is not supported by this list - * @throws ClassCastException - * if the element is not a {@link URI} - * @throws NullPointerException - * if the specified element is null and this list does not - * permit null elements - * @throws IndexOutOfBoundsException - * if the index is out of range ( - * {@code index < 0 || index >= size()}) - * @since 4.3 - */ - @Override - public Object set(final int index, final Object element) { - final URI removed = this.all.set(index, (URI) element); - this.unique.remove(removed); - this.unique.add((URI) element); - if (this.all.size() != this.unique.size()) { - this.unique.addAll(this.all); - } - return removed; - } - - /** - * Inserts the specified element at the specified position in this list - * (must be a URI). Shifts the URI currently at that position (if any) and - * any subsequent URIs to the right (adds one to their indices). - * - * @param index - * index at which the specified element is to be inserted - * @param element - * URI to be inserted - * @throws UnsupportedOperationException - * if the {@code add} operation is not supported by this list - * @throws ClassCastException - * if the element is not a {@link URI} - * @throws NullPointerException - * if the specified element is null and this list does not - * permit null elements - * @throws IndexOutOfBoundsException - * if the index is out of range ( - * {@code index < 0 || index > size()}) - * @since 4.3 - */ - @Override - public void add(final int index, final Object element) { - this.all.add(index, (URI) element); - this.unique.add((URI) element); - } - - /** - * Removes the URI at the specified position in this list. Shifts any - * subsequent URIs to the left (subtracts one from their indices). Returns - * the URI that was removed from the list. - * - * @param index - * the index of the URI to be removed - * @return the URI previously at the specified position - * @throws IndexOutOfBoundsException - * if the index is out of range ( - * {@code index < 0 || index >= size()}) - * @since 4.3 - */ - @Override - public URI remove(final int index) { - final URI removed = this.all.remove(index); - this.unique.remove(removed); - if (this.all.size() != this.unique.size()) { - this.unique.addAll(this.all); - } - return removed; - } - - /** - * Returns {@code true} if this collection contains the specified element. - * More formally, returns {@code true} if and only if this collection - * contains at least one element {@code e} such that - * {@code (o==null ? e==null : o.equals(e))}. - * - * @param o element whose presence in this collection is to be tested - * @return {@code true} if this collection contains the specified - * element - */ - @Override - public boolean contains(final Object o) { - return this.unique.contains(o); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/RequestWrapper.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/RequestWrapper.java deleted file mode 100644 index 9465d743..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/RequestWrapper.java +++ /dev/null @@ -1,171 +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 com.tracelytics.ext.apache.http.impl.client; - -import java.net.URI; -import java.net.URISyntaxException; - -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.ProtocolException; -import com.tracelytics.ext.apache.http.ProtocolVersion; -import com.tracelytics.ext.apache.http.RequestLine; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.message.AbstractHttpMessage; -import com.tracelytics.ext.apache.http.message.BasicRequestLine; -import com.tracelytics.ext.apache.http.params.HttpProtocolParams; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.client.methods.HttpUriRequest; - -/** - * A wrapper class for {@link HttpRequest}s that can be used to change - * properties of the current request without modifying the original - * object. - *

- * This class is also capable of resetting the request headers to - * the state of the original request. - *

- * - * @since 4.0 - * - * @deprecated (4.3) do not use. - */ -@NotThreadSafe -@Deprecated -public class RequestWrapper extends AbstractHttpMessage implements HttpUriRequest { - - private final HttpRequest original; - - private URI uri; - private String method; - private ProtocolVersion version; - private int execCount; - - public RequestWrapper(final HttpRequest request) throws ProtocolException { - super(); - Args.notNull(request, "HTTP request"); - this.original = request; - setParams(request.getParams()); - setHeaders(request.getAllHeaders()); - // Make a copy of the original URI - if (request instanceof HttpUriRequest) { - this.uri = ((HttpUriRequest) request).getURI(); - this.method = ((HttpUriRequest) request).getMethod(); - this.version = null; - } else { - final RequestLine requestLine = request.getRequestLine(); - try { - this.uri = new URI(requestLine.getUri()); - } catch (final URISyntaxException ex) { - throw new ProtocolException("Invalid request URI: " - + requestLine.getUri(), ex); - } - this.method = requestLine.getMethod(); - this.version = request.getProtocolVersion(); - } - this.execCount = 0; - } - - public void resetHeaders() { - // Make a copy of original headers - this.headergroup.clear(); - setHeaders(this.original.getAllHeaders()); - } - - @Override - public String getMethod() { - return this.method; - } - - public void setMethod(final String method) { - Args.notNull(method, "Method name"); - this.method = method; - } - - @Override - public ProtocolVersion getProtocolVersion() { - if (this.version == null) { - this.version = HttpProtocolParams.getVersion(getParams()); - } - return this.version; - } - - public void setProtocolVersion(final ProtocolVersion version) { - this.version = version; - } - - - @Override - public URI getURI() { - return this.uri; - } - - public void setURI(final URI uri) { - this.uri = uri; - } - - @Override - public RequestLine getRequestLine() { - final ProtocolVersion ver = getProtocolVersion(); - String uritext = null; - if (uri != null) { - uritext = uri.toASCIIString(); - } - if (uritext == null || uritext.isEmpty()) { - uritext = "/"; - } - return new BasicRequestLine(getMethod(), uritext, ver); - } - - @Override - public void abort() throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isAborted() { - return false; - } - - public HttpRequest getOriginal() { - return this.original; - } - - public boolean isRepeatable() { - return true; - } - - public int getExecCount() { - return this.execCount; - } - - public void incrementExecCount() { - this.execCount++; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/StandardHttpRequestRetryHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/StandardHttpRequestRetryHandler.java deleted file mode 100644 index 786366e7..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/StandardHttpRequestRetryHandler.java +++ /dev/null @@ -1,81 +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 com.tracelytics.ext.apache.http.impl.client; - -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * {@link com.tracelytics.ext.apache.http.client.HttpRequestRetryHandler} which assumes - * that all requested HTTP methods which should be idempotent according - * to RFC-2616 are in fact idempotent and can be retried. - *

- * According to RFC-2616 section 9.1.2 the idempotent HTTP methods are: - * GET, HEAD, PUT, DELETE, OPTIONS, and TRACE - *

- * - * @since 4.2 - */ -@Immutable -public class StandardHttpRequestRetryHandler extends DefaultHttpRequestRetryHandler { - - private final Map idempotentMethods; - - /** - * Default constructor - */ - public StandardHttpRequestRetryHandler(final int retryCount, final boolean requestSentRetryEnabled) { - super(retryCount, requestSentRetryEnabled); - this.idempotentMethods = new ConcurrentHashMap(); - this.idempotentMethods.put("GET", Boolean.TRUE); - this.idempotentMethods.put("HEAD", Boolean.TRUE); - this.idempotentMethods.put("PUT", Boolean.TRUE); - this.idempotentMethods.put("DELETE", Boolean.TRUE); - this.idempotentMethods.put("OPTIONS", Boolean.TRUE); - this.idempotentMethods.put("TRACE", Boolean.TRUE); - } - - /** - * Default constructor - */ - public StandardHttpRequestRetryHandler() { - this(3, false); - } - - @Override - protected boolean handleAsIdempotent(final HttpRequest request) { - final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ROOT); - final Boolean b = this.idempotentMethods.get(method); - return b != null && b.booleanValue(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/SystemClock.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/SystemClock.java deleted file mode 100644 index e3291d83..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/SystemClock.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 com.tracelytics.ext.apache.http.impl.client; - -/** - * The actual system clock. - * - * @since 4.2 - */ -class SystemClock implements Clock { - - @Override - public long getCurrentTime() { - return System.currentTimeMillis(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/SystemDefaultCredentialsProvider.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/SystemDefaultCredentialsProvider.java deleted file mode 100644 index de0631aa..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/SystemDefaultCredentialsProvider.java +++ /dev/null @@ -1,152 +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 com.tracelytics.ext.apache.http.impl.client; - -import java.net.Authenticator; -import java.net.PasswordAuthentication; -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.auth.AuthScope; -import com.tracelytics.ext.apache.http.auth.Credentials; -import com.tracelytics.ext.apache.http.auth.NTCredentials; -import com.tracelytics.ext.apache.http.auth.UsernamePasswordCredentials; -import com.tracelytics.ext.apache.http.client.CredentialsProvider; -import com.tracelytics.ext.apache.http.client.config.AuthSchemes; - -/** - * Implementation of {@link CredentialsProvider} backed by standard - * JRE {@link Authenticator}. - * - * @since 4.3 - */ -@ThreadSafe -public class SystemDefaultCredentialsProvider implements CredentialsProvider { - - private static final Map SCHEME_MAP; - - static { - SCHEME_MAP = new ConcurrentHashMap(); - SCHEME_MAP.put(AuthSchemes.BASIC.toUpperCase(Locale.ROOT), "Basic"); - SCHEME_MAP.put(AuthSchemes.DIGEST.toUpperCase(Locale.ROOT), "Digest"); - SCHEME_MAP.put(AuthSchemes.NTLM.toUpperCase(Locale.ROOT), "NTLM"); - SCHEME_MAP.put(AuthSchemes.SPNEGO.toUpperCase(Locale.ROOT), "SPNEGO"); - SCHEME_MAP.put(AuthSchemes.KERBEROS.toUpperCase(Locale.ROOT), "Kerberos"); - } - - private static String translateScheme(final String key) { - if (key == null) { - return null; - } - final String s = SCHEME_MAP.get(key); - return s != null ? s : key; - } - - private final BasicCredentialsProvider internal; - - /** - * Default constructor. - */ - public SystemDefaultCredentialsProvider() { - super(); - this.internal = new BasicCredentialsProvider(); - } - - @Override - public void setCredentials(final AuthScope authscope, final Credentials credentials) { - internal.setCredentials(authscope, credentials); - } - - private static PasswordAuthentication getSystemCreds( - final AuthScope authscope, - final Authenticator.RequestorType requestorType) { - 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"); - return Authenticator.requestPasswordAuthentication( - hostname, - null, - port, - protocol, - null, - translateScheme(authscope.getScheme()), - null, - requestorType); - } - - @Override - public Credentials getCredentials(final AuthScope authscope) { - Args.notNull(authscope, "Auth scope"); - final Credentials localcreds = internal.getCredentials(authscope); - if (localcreds != null) { - return localcreds; - } - if (authscope.getHost() != null) { - PasswordAuthentication systemcreds = getSystemCreds( - authscope, Authenticator.RequestorType.SERVER); - if (systemcreds == null) { - systemcreds = getSystemCreds( - authscope, Authenticator.RequestorType.PROXY); - } - if (systemcreds != null) { - final String domain = System.getProperty("http.auth.ntlm.domain"); - if (domain != null) { - return new NTCredentials( - systemcreds.getUserName(), - new String(systemcreds.getPassword()), - null, domain); - } else { - if (AuthSchemes.NTLM.equalsIgnoreCase(authscope.getScheme())) { - // Domian may be specified in a fully qualified user name - return new NTCredentials( - systemcreds.getUserName(), - new String(systemcreds.getPassword()), - null, null); - } else { - return new UsernamePasswordCredentials( - systemcreds.getUserName(), - new String(systemcreds.getPassword())); - } - } - } - } - return null; - } - - @Override - public void clear() { - internal.clear(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/TargetAuthenticationStrategy.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/TargetAuthenticationStrategy.java deleted file mode 100644 index 8d9e7178..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/TargetAuthenticationStrategy.java +++ /dev/null @@ -1,58 +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 com.tracelytics.ext.apache.http.impl.client; - -import java.util.Collection; - -import com.tracelytics.ext.apache.http.HttpStatus; -import com.tracelytics.ext.apache.http.annotation.Immutable; - -import com.tracelytics.ext.apache.http.auth.AUTH; -import com.tracelytics.ext.apache.http.client.config.RequestConfig; - -/** - * Default {@link com.tracelytics.ext.apache.http.client.AuthenticationStrategy} implementation - * for proxy host authentication. - * - * @since 4.2 - */ -@Immutable -public class TargetAuthenticationStrategy extends AuthenticationStrategyImpl { - - public static final TargetAuthenticationStrategy INSTANCE = new TargetAuthenticationStrategy(); - - public TargetAuthenticationStrategy() { - super(HttpStatus.SC_UNAUTHORIZED, AUTH.WWW_AUTH); - } - - @Override - Collection getPreferredAuthSchemes(final RequestConfig config) { - return config.getTargetPreferredAuthSchemes(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/package-info.java deleted file mode 100644 index 58c3b727..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/client/package-info.java +++ /dev/null @@ -1,52 +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 - * . - * - */ - -/** - * Default HTTP client implementation. - *

- * The usual execution flow can be demonstrated by the code snippet below: - *

- *
- * CloseableHttpClient httpclient = HttpClients.createDefault();
- * try {
- *      HttpGet httpGet = new HttpGet("http://targethost/homepage");
- *      CloseableHttpResponse response = httpclient.execute(httpGet);
- *      try {
- *          System.out.println(response.getStatusLine());
- *          HttpEntity entity = response.getEntity();
- *          // do something useful with the response body
- *          // and ensure it is fully consumed
- *          EntityUtils.consume(entity);
- *      } finally {
- *          response.close();
- *      }
- * } finally {
- *      httpclient.close();
- * }
- * 
- */ -package com.tracelytics.ext.apache.http.impl.client; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/BasicHttpClientConnectionManager.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/BasicHttpClientConnectionManager.java deleted file mode 100644 index 0f65dff6..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/BasicHttpClientConnectionManager.java +++ /dev/null @@ -1,395 +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 com.tracelytics.ext.apache.http.impl.conn; - -import java.io.Closeable; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.util.Date; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.tracelytics.ext.apache.http.HttpClientConnection; -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.annotation.GuardedBy; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.config.ConnectionConfig; -import com.tracelytics.ext.apache.http.config.Lookup; -import com.tracelytics.ext.apache.http.config.Registry; -import com.tracelytics.ext.apache.http.config.RegistryBuilder; -import com.tracelytics.ext.apache.http.config.SocketConfig; -import com.tracelytics.ext.apache.http.conn.ConnectionRequest; -import com.tracelytics.ext.apache.http.conn.DnsResolver; -import com.tracelytics.ext.apache.http.conn.HttpClientConnectionManager; -import com.tracelytics.ext.apache.http.conn.HttpClientConnectionOperator; -import com.tracelytics.ext.apache.http.conn.HttpConnectionFactory; -import com.tracelytics.ext.apache.http.conn.ManagedHttpClientConnection; -import com.tracelytics.ext.apache.http.conn.SchemePortResolver; -import com.tracelytics.ext.apache.http.conn.routing.HttpRoute; -import com.tracelytics.ext.apache.http.conn.socket.ConnectionSocketFactory; -import com.tracelytics.ext.apache.http.conn.socket.PlainConnectionSocketFactory; -import com.tracelytics.ext.apache.http.conn.ssl.SSLConnectionSocketFactory; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.Asserts; -import com.tracelytics.ext.apache.http.util.LangUtils; - -/** - * A connection manager for a single connection. This connection manager maintains only one active - * connection. Even though this class is fully thread-safe it ought to be used by one execution - * thread only, as only one thread a time can lease the connection at a time. - *

- * This connection manager will make an effort to reuse the connection for subsequent requests - * with the same {@link HttpRoute route}. It will, however, close the existing connection and - * open it for the given route, if the route of the persistent connection does not match that - * of the connection request. If the connection has been already been allocated - * {@link IllegalStateException} is thrown. - *

- *

- * This connection manager implementation should be used inside an EJB container instead of - * {@link PoolingHttpClientConnectionManager}. - *

- * - * @since 4.3 - */ -@ThreadSafe -public class BasicHttpClientConnectionManager implements HttpClientConnectionManager, Closeable { - - private final Logger log = Logger.getLogger(getClass().getName()); - - 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; - - private static Registry getDefaultRegistry() { - return RegistryBuilder.create() - .register("http", PlainConnectionSocketFactory.getSocketFactory()) - .register("https", SSLConnectionSocketFactory.getSocketFactory()) - .build(); - } - - public BasicHttpClientConnectionManager( - final Lookup socketFactoryRegistry, - final HttpConnectionFactory connFactory, - final SchemePortResolver schemePortResolver, - final DnsResolver dnsResolver) { - this( - new DefaultHttpClientConnectionOperator(socketFactoryRegistry, schemePortResolver, dnsResolver), - connFactory - ); - } - - /** - * @since 4.4 - */ - public BasicHttpClientConnectionManager( - final HttpClientConnectionOperator httpClientConnectionOperator, - final HttpConnectionFactory connFactory) { - super(); - this.connectionOperator = Args.notNull(httpClientConnectionOperator, "Connection operator"); - this.connFactory = connFactory != null ? connFactory : ManagedHttpClientConnectionFactory.INSTANCE; - this.expiry = Long.MAX_VALUE; - this.socketConfig = SocketConfig.DEFAULT; - this.connConfig = ConnectionConfig.DEFAULT; - this.isShutdown = new AtomicBoolean(false); - } - - public BasicHttpClientConnectionManager( - final Lookup socketFactoryRegistry, - final HttpConnectionFactory connFactory) { - this(socketFactoryRegistry, connFactory, null, null); - } - - public BasicHttpClientConnectionManager( - final Lookup socketFactoryRegistry) { - this(socketFactoryRegistry, null, null, null); - } - - public BasicHttpClientConnectionManager() { - this(getDefaultRegistry(), null, null, null); - } - - @Override - protected void finalize() throws Throwable { - try { - shutdown(); - } finally { // Make sure we call overridden method even if shutdown barfs - super.finalize(); - } - } - - @Override - public void close() { - shutdown(); - } - - HttpRoute getRoute() { - return route; - } - - Object getState() { - return state; - } - - public synchronized SocketConfig getSocketConfig() { - return socketConfig; - } - - public synchronized void setSocketConfig(final SocketConfig socketConfig) { - this.socketConfig = socketConfig != null ? socketConfig : SocketConfig.DEFAULT; - } - - public synchronized ConnectionConfig getConnectionConfig() { - return connConfig; - } - - public synchronized void setConnectionConfig(final ConnectionConfig connConfig) { - this.connConfig = connConfig != null ? connConfig : ConnectionConfig.DEFAULT; - } - - @Override - public final ConnectionRequest requestConnection( - final HttpRoute route, - final Object state) { - Args.notNull(route, "Route"); - return new ConnectionRequest() { - - @Override - public boolean cancel() { - // Nothing to abort, since requests are immediate. - return false; - } - - @Override - public HttpClientConnection get(final long timeout, final TimeUnit tunit) { - return BasicHttpClientConnectionManager.this.getConnection( - route, state); - } - - }; - } - - private void closeConnection() { - if (this.conn != null) { - this.log.log(Level.FINE, "Closing connection"); - try { - this.conn.close(); - } catch (final IOException iox) { - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "I/O exception closing connection", iox); - } - } - this.conn = null; - } - } - - private void shutdownConnection() { - if (this.conn != null) { - this.log.log(Level.FINE, "Shutting down connection"); - try { - this.conn.shutdown(); - } catch (final IOException iox) { - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "I/O exception shutting down connection", iox); - } - } - this.conn = null; - } - } - - private void checkExpiry() { - if (this.conn != null && System.currentTimeMillis() >= this.expiry) { - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Connection expired @ " + new Date(this.expiry)); - } - closeConnection(); - } - } - - synchronized HttpClientConnection getConnection(final HttpRoute route, final Object state) { - Asserts.check(!this.isShutdown.get(), "Connection manager has been shut down"); - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Get connection for route " + route); - } - Asserts.check(!this.leased, "Connection is still allocated"); - if (!LangUtils.equals(this.route, route) || !LangUtils.equals(this.state, state)) { - closeConnection(); - } - this.route = route; - this.state = state; - checkExpiry(); - if (this.conn == null) { - this.conn = this.connFactory.create(route, this.connConfig); - } - this.leased = true; - return this.conn; - } - - @Override - public synchronized void releaseConnection( - final HttpClientConnection conn, - final Object state, - final long keepalive, final TimeUnit tunit) { - Args.notNull(conn, "Connection"); - Asserts.check(conn == this.conn, "Connection not obtained from this manager"); - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Releasing connection " + conn); - } - if (this.isShutdown.get()) { - return; - } - try { - this.updated = System.currentTimeMillis(); - if (!this.conn.isOpen()) { - this.conn = null; - this.route = null; - this.conn = null; - this.expiry = Long.MAX_VALUE; - } else { - this.state = state; - if (this.log.isLoggable(Level.FINE)) { - final String s; - if (keepalive > 0) { - s = "for " + keepalive + " " + tunit; - } else { - s = "indefinitely"; - } - this.log.log(Level.FINE, "Connection can be kept alive " + s); - } - if (keepalive > 0) { - this.expiry = this.updated + tunit.toMillis(keepalive); - } else { - this.expiry = Long.MAX_VALUE; - } - } - } finally { - this.leased = false; - } - } - - @Override - public void connect( - final HttpClientConnection conn, - final HttpRoute route, - final int connectTimeout, - final HttpContext context) throws IOException { - Args.notNull(conn, "Connection"); - Args.notNull(route, "HTTP route"); - Asserts.check(conn == this.conn, "Connection not obtained from this manager"); - final HttpHost host; - if (route.getProxyHost() != null) { - host = route.getProxyHost(); - } else { - host = route.getTargetHost(); - } - final InetSocketAddress localAddress = route.getLocalSocketAddress(); - this.connectionOperator.connect(this.conn, host, localAddress, - connectTimeout, this.socketConfig, context); - } - - @Override - public void upgrade( - final HttpClientConnection conn, - final HttpRoute route, - final HttpContext context) throws IOException { - Args.notNull(conn, "Connection"); - Args.notNull(route, "HTTP route"); - Asserts.check(conn == this.conn, "Connection not obtained from this manager"); - this.connectionOperator.upgrade(this.conn, route.getTargetHost(), context); - } - - @Override - public void routeComplete( - final HttpClientConnection conn, - final HttpRoute route, - final HttpContext context) throws IOException { - } - - @Override - public synchronized void closeExpiredConnections() { - if (this.isShutdown.get()) { - return; - } - if (!this.leased) { - checkExpiry(); - } - } - - @Override - public synchronized void closeIdleConnections(final long idletime, final TimeUnit tunit) { - Args.notNull(tunit, "Time unit"); - if (this.isShutdown.get()) { - return; - } - if (!this.leased) { - long time = tunit.toMillis(idletime); - if (time < 0) { - time = 0; - } - final long deadline = System.currentTimeMillis() - time; - if (this.updated <= deadline) { - closeConnection(); - } - } - } - - @Override - public synchronized void shutdown() { - if (this.isShutdown.compareAndSet(false, true)) { - shutdownConnection(); - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/CPool.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/CPool.java deleted file mode 100644 index 0abda00c..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/CPool.java +++ /dev/null @@ -1,71 +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 com.tracelytics.ext.apache.http.impl.conn; - -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; -import java.util.logging.Logger; - -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.conn.ManagedHttpClientConnection; -import com.tracelytics.ext.apache.http.conn.routing.HttpRoute; -import com.tracelytics.ext.apache.http.pool.AbstractConnPool; -import com.tracelytics.ext.apache.http.pool.ConnFactory; - -/** - * @since 4.3 - */ -@ThreadSafe -class CPool extends AbstractConnPool { - - private static final AtomicLong COUNTER = new AtomicLong(); - - private final Logger log = Logger.getLogger(CPool.class.getName()); - 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(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/CPoolEntry.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/CPoolEntry.java deleted file mode 100644 index 170fcbf1..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/CPoolEntry.java +++ /dev/null @@ -1,102 +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 com.tracelytics.ext.apache.http.impl.conn; - -import java.io.IOException; -import java.util.Date; -import java.util.concurrent.TimeUnit; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.tracelytics.ext.apache.http.HttpClientConnection; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.conn.ManagedHttpClientConnection; -import com.tracelytics.ext.apache.http.conn.routing.HttpRoute; -import com.tracelytics.ext.apache.http.pool.PoolEntry; - -/** - * @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.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "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.log(Level.FINE, "I/O error closing connection", ex); - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/CPoolProxy.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/CPoolProxy.java deleted file mode 100644 index 9192ffc2..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/CPoolProxy.java +++ /dev/null @@ -1,270 +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 com.tracelytics.ext.apache.http.impl.conn; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.Socket; - -import javax.net.ssl.SSLSession; - -import com.tracelytics.ext.apache.http.HttpClientConnection; -import com.tracelytics.ext.apache.http.HttpConnectionMetrics; -import com.tracelytics.ext.apache.http.HttpEntityEnclosingRequest; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -import com.tracelytics.ext.apache.http.conn.ManagedHttpClientConnection; - -/** - * @since 4.3 - */ -@NotThreadSafe -class CPoolProxy implements ManagedHttpClientConnection, HttpContext { - - private volatile CPoolEntry poolEntry; - - CPoolProxy(final CPoolEntry entry) { - super(); - this.poolEntry = entry; - } - - CPoolEntry getPoolEntry() { - return this.poolEntry; - } - - CPoolEntry detach() { - final CPoolEntry local = this.poolEntry; - this.poolEntry = null; - return local; - } - - ManagedHttpClientConnection getConnection() { - final CPoolEntry local = this.poolEntry; - if (local == null) { - return null; - } - return local.getConnection(); - } - - ManagedHttpClientConnection getValidConnection() { - final ManagedHttpClientConnection conn = getConnection(); - if (conn == null) { - throw new ConnectionShutdownException(); - } - return conn; - } - - @Override - public void close() throws IOException { - final CPoolEntry local = this.poolEntry; - if (local != null) { - local.closeConnection(); - } - } - - @Override - public void shutdown() throws IOException { - final CPoolEntry local = this.poolEntry; - if (local != null) { - local.shutdownConnection(); - } - } - - @Override - public boolean isOpen() { - final CPoolEntry local = this.poolEntry; - if (local != null) { - return !local.isClosed(); - } else { - return false; - } - } - - @Override - public boolean isStale() { - final HttpClientConnection conn = getConnection(); - if (conn != null) { - return conn.isStale(); - } else { - return true; - } - } - - @Override - public void setSocketTimeout(final int timeout) { - getValidConnection().setSocketTimeout(timeout); - } - - @Override - public int getSocketTimeout() { - return getValidConnection().getSocketTimeout(); - } - - @Override - public String getId() { - return getValidConnection().getId(); - } - - @Override - public void bind(final Socket socket) throws IOException { - getValidConnection().bind(socket); - } - - @Override - public Socket getSocket() { - return getValidConnection().getSocket(); - } - - @Override - public SSLSession getSSLSession() { - return getValidConnection().getSSLSession(); - } - - @Override - public boolean isResponseAvailable(final int timeout) throws IOException { - return getValidConnection().isResponseAvailable(timeout); - } - - @Override - public void sendRequestHeader(final HttpRequest request) throws HttpException, IOException { - getValidConnection().sendRequestHeader(request); - } - - @Override - public void sendRequestEntity(final HttpEntityEnclosingRequest request) throws HttpException, IOException { - getValidConnection().sendRequestEntity(request); - } - - @Override - public HttpResponse receiveResponseHeader() throws HttpException, IOException { - return getValidConnection().receiveResponseHeader(); - } - - @Override - public void receiveResponseEntity(final HttpResponse response) throws HttpException, IOException { - getValidConnection().receiveResponseEntity(response); - } - - @Override - public void flush() throws IOException { - getValidConnection().flush(); - } - - @Override - public HttpConnectionMetrics getMetrics() { - return getValidConnection().getMetrics(); - } - - @Override - public InetAddress getLocalAddress() { - return getValidConnection().getLocalAddress(); - } - - @Override - public int getLocalPort() { - return getValidConnection().getLocalPort(); - } - - @Override - public InetAddress getRemoteAddress() { - return getValidConnection().getRemoteAddress(); - } - - @Override - public int getRemotePort() { - return getValidConnection().getRemotePort(); - } - - @Override - public Object getAttribute(final String id) { - final ManagedHttpClientConnection conn = getValidConnection(); - if (conn instanceof HttpContext) { - return ((HttpContext) conn).getAttribute(id); - } else { - return null; - } - } - - @Override - public void setAttribute(final String id, final Object obj) { - final ManagedHttpClientConnection conn = getValidConnection(); - if (conn instanceof HttpContext) { - ((HttpContext) conn).setAttribute(id, obj); - } - } - - @Override - public Object removeAttribute(final String id) { - final ManagedHttpClientConnection conn = getValidConnection(); - if (conn instanceof HttpContext) { - return ((HttpContext) conn).removeAttribute(id); - } else { - return null; - } - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("CPoolProxy{"); - final ManagedHttpClientConnection conn = getConnection(); - if (conn != null) { - sb.append(conn); - } else { - sb.append("detached"); - } - sb.append('}'); - return sb.toString(); - } - - public static HttpClientConnection newProxy(final CPoolEntry poolEntry) { - return new CPoolProxy(poolEntry); - } - - private 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/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/ConnectionShutdownException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/ConnectionShutdownException.java deleted file mode 100644 index 58c350b9..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/ConnectionShutdownException.java +++ /dev/null @@ -1,50 +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 com.tracelytics.ext.apache.http.impl.conn; - -import com.tracelytics.ext.apache.http.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; - - /** - * Creates a new ConnectionShutdownException with a {@code null} detail message. - */ - public ConnectionShutdownException() { - super(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/DefaultHttpClientConnectionOperator.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/DefaultHttpClientConnectionOperator.java deleted file mode 100644 index 2a1b1ed6..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/DefaultHttpClientConnectionOperator.java +++ /dev/null @@ -1,189 +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 com.tracelytics.ext.apache.http.impl.conn; - -import java.io.IOException; -import java.net.ConnectException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.NoRouteToHostException; -import java.net.Socket; -import java.net.SocketTimeoutException; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.client.protocol.HttpClientContext; -import com.tracelytics.ext.apache.http.config.Lookup; -import com.tracelytics.ext.apache.http.config.SocketConfig; -import com.tracelytics.ext.apache.http.conn.ConnectTimeoutException; -import com.tracelytics.ext.apache.http.conn.DnsResolver; -import com.tracelytics.ext.apache.http.conn.HttpClientConnectionOperator; -import com.tracelytics.ext.apache.http.conn.HttpHostConnectException; -import com.tracelytics.ext.apache.http.conn.ManagedHttpClientConnection; -import com.tracelytics.ext.apache.http.conn.SchemePortResolver; -import com.tracelytics.ext.apache.http.conn.UnsupportedSchemeException; -import com.tracelytics.ext.apache.http.conn.socket.ConnectionSocketFactory; -import com.tracelytics.ext.apache.http.conn.socket.LayeredConnectionSocketFactory; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Default implementation of {@link HttpClientConnectionOperator} used as default in Http client, - * when no instance provided by user to {@link BasicHttpClientConnectionManager} or {@link - * PoolingHttpClientConnectionManager} constructor. - * - * @since 4.4 - */ -@Immutable -public class DefaultHttpClientConnectionOperator implements HttpClientConnectionOperator { - - static final String SOCKET_FACTORY_REGISTRY = "http.socket-factory-registry"; - - private final Logger log = Logger.getLogger(getClass().getName()); - - private final Lookup socketFactoryRegistry; - private final SchemePortResolver schemePortResolver; - private final DnsResolver dnsResolver; - - public DefaultHttpClientConnectionOperator( - final Lookup socketFactoryRegistry, - final SchemePortResolver schemePortResolver, - final DnsResolver dnsResolver) { - super(); - Args.notNull(socketFactoryRegistry, "Socket factory registry"); - this.socketFactoryRegistry = socketFactoryRegistry; - this.schemePortResolver = schemePortResolver != null ? schemePortResolver : - DefaultSchemePortResolver.INSTANCE; - this.dnsResolver = dnsResolver != null ? dnsResolver : - SystemDefaultDnsResolver.INSTANCE; - } - - @SuppressWarnings("unchecked") - private Lookup getSocketFactoryRegistry(final HttpContext context) { - Lookup reg = (Lookup) context.getAttribute( - SOCKET_FACTORY_REGISTRY); - if (reg == null) { - reg = this.socketFactoryRegistry; - } - return reg; - } - - @Override - public void connect( - final ManagedHttpClientConnection conn, - final HttpHost host, - final InetSocketAddress localAddress, - final int connectTimeout, - final SocketConfig socketConfig, - final HttpContext context) throws IOException { - final Lookup registry = getSocketFactoryRegistry(context); - final ConnectionSocketFactory sf = registry.lookup(host.getSchemeName()); - if (sf == null) { - throw new UnsupportedSchemeException(host.getSchemeName() + - " protocol is not supported"); - } - final InetAddress[] addresses = host.getAddress() != null ? - new InetAddress[] { host.getAddress() } : this.dnsResolver.resolve(host.getHostName()); - final int port = this.schemePortResolver.resolve(host); - for (int i = 0; i < addresses.length; i++) { - final InetAddress address = addresses[i]; - final boolean last = i == addresses.length - 1; - - Socket sock = sf.createSocket(context); - sock.setSoTimeout(socketConfig.getSoTimeout()); - sock.setReuseAddress(socketConfig.isSoReuseAddress()); - sock.setTcpNoDelay(socketConfig.isTcpNoDelay()); - sock.setKeepAlive(socketConfig.isSoKeepAlive()); - final int linger = socketConfig.getSoLinger(); - if (linger >= 0) { - sock.setSoLinger(true, linger); - } - conn.bind(sock); - - final InetSocketAddress remoteAddress = new InetSocketAddress(address, port); - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Connecting to " + remoteAddress); - } - try { - sock = sf.connectSocket( - connectTimeout, sock, host, remoteAddress, localAddress, context); - conn.bind(sock); - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Connection established " + conn); - } - return; - } catch (final SocketTimeoutException ex) { - if (last) { - throw new ConnectTimeoutException(ex, host, addresses); - } - } catch (final ConnectException ex) { - if (last) { - final String msg = ex.getMessage(); - if ("Connection timed out".equals(msg)) { - throw new ConnectTimeoutException(ex, host, addresses); - } else { - throw new HttpHostConnectException(ex, host, addresses); - } - } - } catch (final NoRouteToHostException ex) { - if (last) { - throw ex; - } - } - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Connect to " + remoteAddress + " timed out. " + - "Connection will be retried using another IP address"); - } - } - } - - @Override - public void upgrade( - final ManagedHttpClientConnection conn, - final HttpHost host, - final HttpContext context) throws IOException { - final HttpClientContext clientContext = HttpClientContext.adapt(context); - final Lookup registry = getSocketFactoryRegistry(clientContext); - final ConnectionSocketFactory sf = registry.lookup(host.getSchemeName()); - if (sf == null) { - throw new UnsupportedSchemeException(host.getSchemeName() + - " protocol is not supported"); - } - if (!(sf instanceof LayeredConnectionSocketFactory)) { - throw new UnsupportedSchemeException(host.getSchemeName() + - " protocol does not support connection upgrade"); - } - final LayeredConnectionSocketFactory lsf = (LayeredConnectionSocketFactory) sf; - Socket sock = conn.getSocket(); - final int port = this.schemePortResolver.resolve(host); - sock = lsf.createLayeredSocket(sock, host.getHostName(), port, context); - conn.bind(sock); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/DefaultHttpResponseParser.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/DefaultHttpResponseParser.java deleted file mode 100644 index 9451bc7d..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/DefaultHttpResponseParser.java +++ /dev/null @@ -1,168 +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 com.tracelytics.ext.apache.http.impl.conn; - -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.HttpResponseFactory; -import com.tracelytics.ext.apache.http.NoHttpResponseException; -import com.tracelytics.ext.apache.http.ProtocolException; -import com.tracelytics.ext.apache.http.StatusLine; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.config.MessageConstraints; -import com.tracelytics.ext.apache.http.impl.DefaultHttpResponseFactory; -import com.tracelytics.ext.apache.http.impl.io.AbstractMessageParser; -import com.tracelytics.ext.apache.http.io.SessionInputBuffer; -import com.tracelytics.ext.apache.http.message.LineParser; -import com.tracelytics.ext.apache.http.message.ParserCursor; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -/** - * Lenient HTTP response parser implementation that can skip malformed data until - * a valid HTTP response message head is encountered. - * - * @since 4.2 - */ -@SuppressWarnings("deprecation") -@NotThreadSafe -public class DefaultHttpResponseParser extends AbstractMessageParser { - - private final Logger log = Logger.getLogger(getClass().getName()); - - private final HttpResponseFactory responseFactory; - private final CharArrayBuffer lineBuf; - - /** - * @deprecated (4.3) use {@link DefaultHttpResponseParser#DefaultHttpResponseParser( - * SessionInputBuffer, LineParser, HttpResponseFactory, MessageConstraints)} - */ - @Deprecated - public DefaultHttpResponseParser( - final SessionInputBuffer buffer, - final LineParser parser, - final HttpResponseFactory responseFactory, - final HttpParams params) { - super(buffer, parser, params); - Args.notNull(responseFactory, "Response factory"); - this.responseFactory = responseFactory; - this.lineBuf = new CharArrayBuffer(128); - } - - /** - * Creates new instance of DefaultHttpResponseParser. - * - * @param buffer the session input buffer. - * @param lineParser the line parser. If {@code null} - * {@link com.tracelytics.ext.apache.http.message.BasicLineParser#INSTANCE} will be used. - * @param responseFactory HTTP response factory. If {@code null} - * {@link DefaultHttpResponseFactory#INSTANCE} will be used. - * @param constraints the message constraints. If {@code null} - * {@link MessageConstraints#DEFAULT} will be used. - * - * @since 4.3 - */ - public DefaultHttpResponseParser( - final SessionInputBuffer buffer, - final LineParser lineParser, - final HttpResponseFactory responseFactory, - final MessageConstraints constraints) { - super(buffer, lineParser, constraints); - this.responseFactory = responseFactory != null ? responseFactory : - DefaultHttpResponseFactory.INSTANCE; - this.lineBuf = new CharArrayBuffer(128); - } - - /** - * Creates new instance of DefaultHttpResponseParser. - * - * @param buffer the session input buffer. - * @param constraints the message constraints. If {@code null} - * {@link MessageConstraints#DEFAULT} will be used. - * - * @since 4.3 - */ - public DefaultHttpResponseParser( - final SessionInputBuffer buffer, final MessageConstraints constraints) { - this(buffer, null, null, constraints); - } - - /** - * Creates new instance of DefaultHttpResponseParser. - * - * @param buffer the session input buffer. - * - * @since 4.3 - */ - public DefaultHttpResponseParser(final SessionInputBuffer buffer) { - this(buffer, null, null, MessageConstraints.DEFAULT); - } - - @Override - protected HttpResponse parseHead( - final SessionInputBuffer sessionBuffer) throws IOException, HttpException { - //read out the HTTP status string - int count = 0; - ParserCursor cursor = null; - do { - // clear the buffer - this.lineBuf.clear(); - final int i = sessionBuffer.readLine(this.lineBuf); - if (i == -1 && count == 0) { - // The server just dropped connection on us - throw new NoHttpResponseException("The target server failed to respond"); - } - cursor = new ParserCursor(0, this.lineBuf.length()); - if (lineParser.hasProtocolVersion(this.lineBuf, cursor)) { - // Got one - break; - } else if (i == -1 || reject(this.lineBuf, count)) { - // Giving up - throw new ProtocolException("The server failed to respond with a " + - "valid HTTP response"); - } - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Garbage in response: " + this.lineBuf.toString()); - } - count++; - } while(true); - //create the status line from the status string - final StatusLine statusline = lineParser.parseStatusLine(this.lineBuf, cursor); - return this.responseFactory.newHttpResponse(statusline, null); - } - - protected boolean reject(final CharArrayBuffer line, final int count) { - return false; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/DefaultHttpResponseParserFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/DefaultHttpResponseParserFactory.java deleted file mode 100644 index e85a5d24..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/DefaultHttpResponseParserFactory.java +++ /dev/null @@ -1,78 +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 com.tracelytics.ext.apache.http.impl.conn; - -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.HttpResponseFactory; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.config.MessageConstraints; -import com.tracelytics.ext.apache.http.impl.DefaultHttpResponseFactory; -import com.tracelytics.ext.apache.http.io.HttpMessageParser; -import com.tracelytics.ext.apache.http.io.HttpMessageParserFactory; -import com.tracelytics.ext.apache.http.io.SessionInputBuffer; -import com.tracelytics.ext.apache.http.message.BasicLineParser; -import com.tracelytics.ext.apache.http.message.LineParser; - -/** - * Default factory for response message parsers. - * - * @since 4.3 - */ -@Immutable -public class DefaultHttpResponseParserFactory implements HttpMessageParserFactory { - - public static final DefaultHttpResponseParserFactory INSTANCE = new DefaultHttpResponseParserFactory(); - - private final LineParser lineParser; - private final HttpResponseFactory responseFactory; - - public DefaultHttpResponseParserFactory( - final LineParser lineParser, - final HttpResponseFactory responseFactory) { - super(); - this.lineParser = lineParser != null ? lineParser : BasicLineParser.INSTANCE; - this.responseFactory = responseFactory != null ? responseFactory - : DefaultHttpResponseFactory.INSTANCE; - } - - public DefaultHttpResponseParserFactory( - final HttpResponseFactory responseFactory) { - this(null, responseFactory); - } - - public DefaultHttpResponseParserFactory() { - this(null, null); - } - - @Override - public HttpMessageParser create(final SessionInputBuffer buffer, - final MessageConstraints constraints) { - return new DefaultHttpResponseParser(buffer, lineParser, responseFactory, constraints); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/DefaultManagedHttpClientConnection.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/DefaultManagedHttpClientConnection.java deleted file mode 100644 index f1db30ef..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/DefaultManagedHttpClientConnection.java +++ /dev/null @@ -1,141 +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 com.tracelytics.ext.apache.http.impl.conn; - -import java.io.IOException; -import java.io.InterruptedIOException; -import java.net.Socket; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CharsetEncoder; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocket; - -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.config.MessageConstraints; -import com.tracelytics.ext.apache.http.entity.ContentLengthStrategy; -import com.tracelytics.ext.apache.http.impl.DefaultBHttpClientConnection; -import com.tracelytics.ext.apache.http.io.HttpMessageParserFactory; -import com.tracelytics.ext.apache.http.io.HttpMessageWriterFactory; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -import com.tracelytics.ext.apache.http.conn.ManagedHttpClientConnection; - -/** - * Default {@link ManagedHttpClientConnection} implementation. - * @since 4.3 - */ -@NotThreadSafe -public class DefaultManagedHttpClientConnection extends DefaultBHttpClientConnection - implements ManagedHttpClientConnection, HttpContext { - - private final String id; - private final Map attributes; - - 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 ContentLengthStrategy incomingContentStrategy, - final ContentLengthStrategy outgoingContentStrategy, - final HttpMessageWriterFactory requestWriterFactory, - final HttpMessageParserFactory responseParserFactory) { - super(buffersize, fragmentSizeHint, chardecoder, charencoder, - constraints, incomingContentStrategy, outgoingContentStrategy, - requestWriterFactory, responseParserFactory); - this.id = id; - this.attributes = new ConcurrentHashMap(); - } - - public DefaultManagedHttpClientConnection( - final String id, - final int buffersize) { - this(id, buffersize, buffersize, null, null, null, null, null, null, null); - } - - @Override - public String getId() { - return this.id; - } - - @Override - public void shutdown() throws IOException { - this.shutdown = true; - super.shutdown(); - } - - @Override - public Object getAttribute(final String id) { - return this.attributes.get(id); - } - - @Override - public Object removeAttribute(final String id) { - return this.attributes.remove(id); - } - - @Override - public void setAttribute(final String id, final Object obj) { - this.attributes.put(id, obj); - } - - @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"); - } - super.bind(socket); - } - - @Override - public Socket getSocket() { - return super.getSocket(); - } - - @Override - public SSLSession getSSLSession() { - final Socket socket = super.getSocket(); - if (socket instanceof SSLSocket) { - return ((SSLSocket) socket).getSession(); - } else { - return null; - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/DefaultProxyRoutePlanner.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/DefaultProxyRoutePlanner.java deleted file mode 100644 index 2e73e443..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/DefaultProxyRoutePlanner.java +++ /dev/null @@ -1,67 +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 com.tracelytics.ext.apache.http.impl.conn; - -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.conn.SchemePortResolver; - -/** - * Implementation of an {@link com.tracelytics.ext.apache.http.conn.routing.HttpRoutePlanner} - * that routes requests through a default proxy. - * - * @since 4.3 - */ -@Immutable -public class DefaultProxyRoutePlanner extends DefaultRoutePlanner { - - private final HttpHost proxy; - - public DefaultProxyRoutePlanner(final HttpHost proxy, final SchemePortResolver schemePortResolver) { - super(schemePortResolver); - this.proxy = Args.notNull(proxy, "Proxy host"); - } - - public DefaultProxyRoutePlanner(final HttpHost proxy) { - this(proxy, null); - } - - @Override - protected HttpHost determineProxy( - final HttpHost target, - final HttpRequest request, - final HttpContext context) throws HttpException { - return proxy; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/DefaultRoutePlanner.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/DefaultRoutePlanner.java deleted file mode 100644 index fd72d4e2..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/DefaultRoutePlanner.java +++ /dev/null @@ -1,114 +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 com.tracelytics.ext.apache.http.impl.conn; - -import java.net.InetAddress; - -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.ProtocolException; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.client.config.RequestConfig; -import com.tracelytics.ext.apache.http.client.protocol.HttpClientContext; -import com.tracelytics.ext.apache.http.conn.SchemePortResolver; -import com.tracelytics.ext.apache.http.conn.UnsupportedSchemeException; -import com.tracelytics.ext.apache.http.conn.routing.HttpRoute; -import com.tracelytics.ext.apache.http.conn.routing.HttpRoutePlanner; - -/** - * Default implementation of an {@link HttpRoutePlanner}. It will not make use of - * any Java system properties, nor of system or browser proxy settings. - * - * @since 4.3 - */ -@Immutable -public class DefaultRoutePlanner implements HttpRoutePlanner { - - private final SchemePortResolver schemePortResolver; - - public DefaultRoutePlanner(final SchemePortResolver schemePortResolver) { - super(); - this.schemePortResolver = schemePortResolver != null ? schemePortResolver : - DefaultSchemePortResolver.INSTANCE; - } - - @Override - public HttpRoute determineRoute( - final HttpHost host, - final HttpRequest request, - final HttpContext context) throws HttpException { - Args.notNull(request, "Request"); - if (host == null) { - throw new ProtocolException("Target host is not specified"); - } - final HttpClientContext clientContext = HttpClientContext.adapt(context); - final RequestConfig config = clientContext.getRequestConfig(); - final InetAddress local = config.getLocalAddress(); - HttpHost proxy = config.getProxy(); - if (proxy == null) { - proxy = determineProxy(host, request, context); - } - - final HttpHost target; - if (host.getPort() <= 0) { - try { - target = new HttpHost( - host.getHostName(), - this.schemePortResolver.resolve(host), - host.getSchemeName()); - } catch (final UnsupportedSchemeException ex) { - throw new HttpException(ex.getMessage()); - } - } else { - target = host; - } - final boolean secure = target.getSchemeName().equalsIgnoreCase("https"); - if (proxy == null) { - return new HttpRoute(target, local, secure); - } else { - return new HttpRoute(target, local, proxy, secure); - } - } - - /** - * This implementation returns null. - * - * @throws HttpException may be thrown if overridden - */ - protected HttpHost determineProxy( - final HttpHost target, - final HttpRequest request, - final HttpContext context) throws HttpException { - return null; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/DefaultSchemePortResolver.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/DefaultSchemePortResolver.java deleted file mode 100644 index b87024c8..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/DefaultSchemePortResolver.java +++ /dev/null @@ -1,63 +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 com.tracelytics.ext.apache.http.impl.conn; - -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.conn.SchemePortResolver; -import com.tracelytics.ext.apache.http.conn.UnsupportedSchemeException; - -/** - * Default {@link SchemePortResolver}. - * - * @since 4.3 - */ -@Immutable -public class DefaultSchemePortResolver implements SchemePortResolver { - - public static final DefaultSchemePortResolver INSTANCE = new DefaultSchemePortResolver(); - - @Override - public int resolve(final HttpHost host) throws UnsupportedSchemeException { - Args.notNull(host, "HTTP host"); - final int port = host.getPort(); - if (port > 0) { - return port; - } - final String name = host.getSchemeName(); - if (name.equalsIgnoreCase("http")) { - return 80; - } else if (name.equalsIgnoreCase("https")) { - return 443; - } else { - throw new UnsupportedSchemeException(name + " protocol is not supported"); - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/InMemoryDnsResolver.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/InMemoryDnsResolver.java deleted file mode 100644 index a6a30fd0..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/InMemoryDnsResolver.java +++ /dev/null @@ -1,95 +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 com.tracelytics.ext.apache.http.impl.conn; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.Arrays; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.tracelytics.ext.apache.http.conn.DnsResolver; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * In-memory {@link DnsResolver} implementation. - * - * @since 4.2 - */ -public class InMemoryDnsResolver implements DnsResolver { - - /** Logger associated to this class. */ - private final Logger log = Logger.getLogger(InMemoryDnsResolver.class.getName()); - - /** - * In-memory collection that will hold the associations between a host name - * and an array of InetAddress instances. - */ - private final Map dnsMap; - - /** - * Builds a DNS resolver that will resolve the host names against a - * collection held in-memory. - */ - public InMemoryDnsResolver() { - dnsMap = new ConcurrentHashMap(); - } - - /** - * Associates the given array of IP addresses to the given host in this DNS overrider. - * The IP addresses are assumed to be already resolved. - * - * @param host - * The host name to be associated with the given IP. - * @param ips - * array of IP addresses to be resolved by this DNS overrider to the given - * host name. - */ - public void add(final String host, final InetAddress... ips) { - Args.notNull(host, "Host name"); - Args.notNull(ips, "Array of IP addresses"); - dnsMap.put(host, ips); - } - - /** - * {@inheritDoc} - */ - @Override - public InetAddress[] resolve(final String host) throws UnknownHostException { - final InetAddress[] resolvedAddresses = dnsMap.get(host); - if (log.isLoggable(Level.INFO)) { - log.log(Level.INFO, "Resolving " + host + " to " + Arrays.deepToString(resolvedAddresses)); - } - if(resolvedAddresses == null){ - throw new UnknownHostException(host + " cannot be resolved"); - } - return resolvedAddresses; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/LoggingInputStream.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/LoggingInputStream.java deleted file mode 100644 index 588031fe..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/LoggingInputStream.java +++ /dev/null @@ -1,145 +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 com.tracelytics.ext.apache.http.impl.conn; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; - -import java.io.IOException; -import java.io.InputStream; - -/** - * Internal class. - * - * @since 4.3 - */ -@NotThreadSafe -class LoggingInputStream extends InputStream { - - private final InputStream in; - private final Wire wire; - - public LoggingInputStream(final InputStream in, final Wire wire) { - super(); - this.in = in; - this.wire = wire; - } - - @Override - public int read() throws IOException { - try { - final int b = in.read(); - if (b == -1) { - wire.input("end of stream"); - } else { - wire.input(b); - } - return b; - } catch (IOException ex) { - wire.input("[read] I/O error: " + ex.getMessage()); - throw ex; - } - } - - @Override - public int read(final byte[] b) throws IOException { - try { - final int bytesRead = in.read(b); - if (bytesRead == -1) { - wire.input("end of stream"); - } else if (bytesRead > 0) { - wire.input(b, 0, bytesRead); - } - return bytesRead; - } catch (IOException ex) { - wire.input("[read] I/O error: " + ex.getMessage()); - throw ex; - } - } - - @Override - public int read(final byte[] b, final int off, final int len) throws IOException { - try { - final int bytesRead = in.read(b, off, len); - if (bytesRead == -1) { - wire.input("end of stream"); - } else if (bytesRead > 0) { - wire.input(b, off, bytesRead); - } - return bytesRead; - } catch (IOException ex) { - wire.input("[read] I/O error: " + ex.getMessage()); - throw ex; - } - } - - @Override - public long skip(final long n) throws IOException { - try { - return super.skip(n); - } catch (IOException ex) { - wire.input("[skip] I/O error: " + ex.getMessage()); - throw ex; - } - } - - @Override - public int available() throws IOException { - try { - return in.available(); - } catch (IOException ex) { - wire.input("[available] I/O error : " + ex.getMessage()); - throw ex; - } - } - - @Override - public void mark(final int readlimit) { - super.mark(readlimit); - } - - @Override - public void reset() throws IOException { - super.reset(); - } - - @Override - public boolean markSupported() { - return false; - } - - @Override - public void close() throws IOException { - try { - in.close(); - } catch (IOException ex) { - wire.input("[close] I/O error: " + ex.getMessage()); - throw ex; - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/LoggingManagedHttpClientConnection.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/LoggingManagedHttpClientConnection.java deleted file mode 100644 index db7dee12..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/LoggingManagedHttpClientConnection.java +++ /dev/null @@ -1,133 +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 com.tracelytics.ext.apache.http.impl.conn; - -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 java.util.logging.Level; -import java.util.logging.Logger; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.config.MessageConstraints; -import com.tracelytics.ext.apache.http.entity.ContentLengthStrategy; -import com.tracelytics.ext.apache.http.io.HttpMessageParserFactory; -import com.tracelytics.ext.apache.http.io.HttpMessageWriterFactory; - -@NotThreadSafe -class LoggingManagedHttpClientConnection extends DefaultManagedHttpClientConnection { - - private final Logger log; - private final Logger headerlog; - private final Wire wire; - - public LoggingManagedHttpClientConnection( - final String id, - final Logger log, - final Logger headerlog, - final Logger wirelog, - final int buffersize, - final int fragmentSizeHint, - final CharsetDecoder chardecoder, - final CharsetEncoder charencoder, - final MessageConstraints constraints, - final ContentLengthStrategy incomingContentStrategy, - final ContentLengthStrategy outgoingContentStrategy, - final HttpMessageWriterFactory requestWriterFactory, - final HttpMessageParserFactory responseParserFactory) { - super(id, buffersize, fragmentSizeHint, chardecoder, charencoder, - constraints, incomingContentStrategy, outgoingContentStrategy, - requestWriterFactory, responseParserFactory); - this.log = log; - this.headerlog = headerlog; - this.wire = new Wire(wirelog, id); - } - - @Override - public void close() throws IOException { - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, getId() + ": Close connection"); - } - super.close(); - } - - @Override - public void shutdown() throws IOException { - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, getId() + ": Shutdown connection"); - } - super.shutdown(); - } - - @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; - } - - @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) { - if (response != null && this.headerlog.isLoggable(Level.FINE)) { - this.headerlog.log(Level.FINE, getId() + " << " + response.getStatusLine().toString()); - final Header[] headers = response.getAllHeaders(); - for (final Header header : headers) { - this.headerlog.log(Level.FINE, getId() + " << " + header.toString()); - } - } - } - - @Override - protected void onRequestSubmitted(final HttpRequest request) { - if (request != null && this.headerlog.isLoggable(Level.FINE)) { - this.headerlog.log(Level.FINE, getId() + " >> " + request.getRequestLine().toString()); - final Header[] headers = request.getAllHeaders(); - for (final Header header : headers) { - this.headerlog.log(Level.FINE, getId() + " >> " + header.toString()); - } - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/LoggingOutputStream.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/LoggingOutputStream.java deleted file mode 100644 index 8c401253..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/LoggingOutputStream.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 com.tracelytics.ext.apache.http.impl.conn; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; - -import java.io.IOException; -import java.io.OutputStream; - -/** - * Internal class. - * - * @since 4.3 - */ -@NotThreadSafe -class LoggingOutputStream extends OutputStream { - - private final OutputStream out; - private final Wire wire; - - public LoggingOutputStream(final OutputStream out, final Wire wire) { - super(); - this.out = out; - this.wire = wire; - } - - @Override - public void write(final int b) throws IOException { - try { - wire.output(b); - } catch (IOException ex) { - wire.output("[write] I/O error: " + ex.getMessage()); - throw ex; - } - } - - @Override - public void write(final byte[] b) throws IOException { - try { - wire.output(b); - out.write(b); - } catch (IOException ex) { - wire.output("[write] I/O error: " + ex.getMessage()); - throw ex; - } - } - - @Override - public void write(final byte[] b, final int off, final int len) throws IOException { - try { - wire.output(b, off, len); - out.write(b, off, len); - } catch (IOException ex) { - wire.output("[write] I/O error: " + ex.getMessage()); - throw ex; - } - } - - @Override - public void flush() throws IOException { - try { - out.flush(); - } catch (IOException ex) { - wire.output("[flush] I/O error: " + ex.getMessage()); - throw ex; - } - } - - @Override - public void close() throws IOException { - try { - out.close(); - } catch (IOException ex) { - wire.output("[close] I/O error: " + ex.getMessage()); - throw ex; - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/ManagedHttpClientConnectionFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/ManagedHttpClientConnectionFactory.java deleted file mode 100644 index 48618ff0..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/ManagedHttpClientConnectionFactory.java +++ /dev/null @@ -1,141 +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 com.tracelytics.ext.apache.http.impl.conn; - -import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CharsetEncoder; -import java.nio.charset.CodingErrorAction; -import java.util.concurrent.atomic.AtomicLong; -import java.util.logging.Logger; - -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.config.ConnectionConfig; -import com.tracelytics.ext.apache.http.conn.HttpConnectionFactory; -import com.tracelytics.ext.apache.http.conn.ManagedHttpClientConnection; -import com.tracelytics.ext.apache.http.conn.routing.HttpRoute; -import com.tracelytics.ext.apache.http.entity.ContentLengthStrategy; -import com.tracelytics.ext.apache.http.impl.entity.LaxContentLengthStrategy; -import com.tracelytics.ext.apache.http.impl.entity.StrictContentLengthStrategy; -import com.tracelytics.ext.apache.http.impl.io.DefaultHttpRequestWriterFactory; -import com.tracelytics.ext.apache.http.io.HttpMessageParserFactory; -import com.tracelytics.ext.apache.http.io.HttpMessageWriterFactory; - -/** - * Factory for {@link ManagedHttpClientConnection} instances. - * @since 4.3 - */ -@Immutable -public class ManagedHttpClientConnectionFactory - implements HttpConnectionFactory { - - private static final AtomicLong COUNTER = new AtomicLong(); - - public static final ManagedHttpClientConnectionFactory INSTANCE = new ManagedHttpClientConnectionFactory(); - - private final Logger log = Logger.getLogger(DefaultManagedHttpClientConnection.class.getName()); - private final Logger headerlog = Logger.getLogger("com.tracelytics.ext.apache.http.headers"); - private final Logger wirelog = Logger.getLogger("com.tracelytics.ext.apache.http.wire"); - - private final HttpMessageWriterFactory requestWriterFactory; - private final HttpMessageParserFactory responseParserFactory; - private final ContentLengthStrategy incomingContentStrategy; - private final ContentLengthStrategy outgoingContentStrategy; - - /** - * @since 4.4 - */ - public ManagedHttpClientConnectionFactory( - final HttpMessageWriterFactory requestWriterFactory, - final HttpMessageParserFactory responseParserFactory, - final ContentLengthStrategy incomingContentStrategy, - final ContentLengthStrategy outgoingContentStrategy) { - super(); - this.requestWriterFactory = requestWriterFactory != null ? requestWriterFactory : - DefaultHttpRequestWriterFactory.INSTANCE; - this.responseParserFactory = responseParserFactory != null ? responseParserFactory : - DefaultHttpResponseParserFactory.INSTANCE; - this.incomingContentStrategy = incomingContentStrategy != null ? incomingContentStrategy : - LaxContentLengthStrategy.INSTANCE; - this.outgoingContentStrategy = outgoingContentStrategy != null ? outgoingContentStrategy : - StrictContentLengthStrategy.INSTANCE; - } - - public ManagedHttpClientConnectionFactory( - final HttpMessageWriterFactory requestWriterFactory, - final HttpMessageParserFactory responseParserFactory) { - this(requestWriterFactory, responseParserFactory, null, null); - } - - public ManagedHttpClientConnectionFactory( - final HttpMessageParserFactory responseParserFactory) { - this(null, responseParserFactory); - } - - public ManagedHttpClientConnectionFactory() { - this(null, null); - } - - @Override - public ManagedHttpClientConnection create(final HttpRoute route, final ConnectionConfig config) { - final ConnectionConfig cconfig = config != null ? config : ConnectionConfig.DEFAULT; - CharsetDecoder chardecoder = null; - CharsetEncoder charencoder = null; - final Charset charset = cconfig.getCharset(); - final CodingErrorAction malformedInputAction = cconfig.getMalformedInputAction() != null ? - cconfig.getMalformedInputAction() : CodingErrorAction.REPORT; - final CodingErrorAction unmappableInputAction = cconfig.getUnmappableInputAction() != null ? - cconfig.getUnmappableInputAction() : CodingErrorAction.REPORT; - if (charset != null) { - chardecoder = charset.newDecoder(); - chardecoder.onMalformedInput(malformedInputAction); - chardecoder.onUnmappableCharacter(unmappableInputAction); - charencoder = charset.newEncoder(); - charencoder.onMalformedInput(malformedInputAction); - charencoder.onUnmappableCharacter(unmappableInputAction); - } - final String id = "http-outgoing-" + Long.toString(COUNTER.getAndIncrement()); - return new LoggingManagedHttpClientConnection( - id, - log, - headerlog, - wirelog, - cconfig.getBufferSize(), - cconfig.getFragmentSizeHint(), - chardecoder, - charencoder, - cconfig.getMessageConstraints(), - incomingContentStrategy, - outgoingContentStrategy, - requestWriterFactory, - responseParserFactory); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/PoolingHttpClientConnectionManager.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/PoolingHttpClientConnectionManager.java deleted file mode 100644 index 60a4043a..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/PoolingHttpClientConnectionManager.java +++ /dev/null @@ -1,596 +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 com.tracelytics.ext.apache.http.impl.conn; - -import java.io.Closeable; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.tracelytics.ext.apache.http.HttpClientConnection; -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.config.ConnectionConfig; -import com.tracelytics.ext.apache.http.config.Lookup; -import com.tracelytics.ext.apache.http.config.Registry; -import com.tracelytics.ext.apache.http.config.RegistryBuilder; -import com.tracelytics.ext.apache.http.config.SocketConfig; -import com.tracelytics.ext.apache.http.conn.ConnectionPoolTimeoutException; -import com.tracelytics.ext.apache.http.conn.ConnectionRequest; -import com.tracelytics.ext.apache.http.conn.DnsResolver; -import com.tracelytics.ext.apache.http.conn.HttpClientConnectionManager; -import com.tracelytics.ext.apache.http.conn.HttpClientConnectionOperator; -import com.tracelytics.ext.apache.http.conn.HttpConnectionFactory; -import com.tracelytics.ext.apache.http.conn.ManagedHttpClientConnection; -import com.tracelytics.ext.apache.http.conn.SchemePortResolver; -import com.tracelytics.ext.apache.http.conn.routing.HttpRoute; -import com.tracelytics.ext.apache.http.conn.socket.ConnectionSocketFactory; -import com.tracelytics.ext.apache.http.conn.socket.PlainConnectionSocketFactory; -import com.tracelytics.ext.apache.http.conn.ssl.SSLConnectionSocketFactory; -import com.tracelytics.ext.apache.http.pool.ConnFactory; -import com.tracelytics.ext.apache.http.pool.ConnPoolControl; -import com.tracelytics.ext.apache.http.pool.PoolStats; -import com.tracelytics.ext.apache.http.protocol.HttpContext; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.Asserts; - -/** - * {@code ClientConnectionPoolManager} maintains a pool of - * {@link HttpClientConnection}s and is able to service connection requests - * from multiple execution threads. Connections are pooled on a per route - * basis. A request for a route which already the manager has persistent - * connections for available in the pool will be services by leasing - * a connection from the pool rather than creating a brand new connection. - *

- * {@code ClientConnectionPoolManager} maintains a maximum limit of connection - * on a per route basis and in total. Per default this implementation will - * create no more than than 2 concurrent connections per given route - * and no more 20 connections in total. For many real-world applications - * these limits may prove too constraining, especially if they use HTTP - * as a transport protocol for their services. Connection limits, however, - * can be adjusted using {@link ConnPoolControl} methods. - *

- *

- * The handling of stale connections was changed in version 4.4. - * Previously, the code would check every connection by default before re-using it. - * The code now only checks the connection if the elapsed time since - * the last use of the connection exceeds the timeout that has been set. - * The default timeout is set to 5000ms - see - * {@link #PoolingHttpClientConnectionManager(HttpClientConnectionOperator, HttpConnectionFactory, long, TimeUnit)} - *

- * - * @since 4.3 - */ -@ThreadSafe -public class PoolingHttpClientConnectionManager - implements HttpClientConnectionManager, ConnPoolControl, Closeable { - - private final Logger log = Logger.getLogger(getClass().getName()); - - private final ConfigData configData; - private final CPool pool; - private final HttpClientConnectionOperator connectionOperator; - private final AtomicBoolean isShutDown; - - private static Registry getDefaultRegistry() { - return RegistryBuilder.create() - .register("http", PlainConnectionSocketFactory.getSocketFactory()) - .register("https", SSLConnectionSocketFactory.getSocketFactory()) - .build(); - } - - public PoolingHttpClientConnectionManager() { - this(getDefaultRegistry()); - } - - public PoolingHttpClientConnectionManager(final long timeToLive, final TimeUnit tunit) { - this(getDefaultRegistry(), null, null ,null, timeToLive, tunit); - } - - public PoolingHttpClientConnectionManager( - final Registry socketFactoryRegistry) { - this(socketFactoryRegistry, null, null); - } - - public PoolingHttpClientConnectionManager( - final Registry socketFactoryRegistry, - final DnsResolver dnsResolver) { - this(socketFactoryRegistry, null, dnsResolver); - } - - public PoolingHttpClientConnectionManager( - final Registry socketFactoryRegistry, - final HttpConnectionFactory connFactory) { - this(socketFactoryRegistry, connFactory, null); - } - - public PoolingHttpClientConnectionManager( - final HttpConnectionFactory connFactory) { - this(getDefaultRegistry(), connFactory, null); - } - - public PoolingHttpClientConnectionManager( - final Registry socketFactoryRegistry, - final HttpConnectionFactory connFactory, - final DnsResolver dnsResolver) { - this(socketFactoryRegistry, connFactory, null, dnsResolver, -1, TimeUnit.MILLISECONDS); - } - - public PoolingHttpClientConnectionManager( - final Registry socketFactoryRegistry, - final HttpConnectionFactory connFactory, - final SchemePortResolver schemePortResolver, - final DnsResolver dnsResolver, - final long timeToLive, final TimeUnit tunit) { - this( - new DefaultHttpClientConnectionOperator(socketFactoryRegistry, schemePortResolver, dnsResolver), - connFactory, - timeToLive, tunit - ); - } - - /** - * @since 4.4 - */ - public PoolingHttpClientConnectionManager( - final HttpClientConnectionOperator httpClientConnectionOperator, - final HttpConnectionFactory connFactory, - final long timeToLive, final TimeUnit tunit) { - super(); - this.configData = new ConfigData(); - this.pool = new CPool(new InternalConnectionFactory( - this.configData, connFactory), 2, 20, timeToLive, tunit); - this.pool.setValidateAfterInactivity(5000); - this.connectionOperator = Args.notNull(httpClientConnectionOperator, "HttpClientConnectionOperator"); - this.isShutDown = new AtomicBoolean(false); - } - - /** - * Visible for test. - */ - PoolingHttpClientConnectionManager( - final CPool 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.isShutDown = new AtomicBoolean(false); - } - - @Override - protected void finalize() throws Throwable { - try { - shutdown(); - } finally { - super.finalize(); - } - } - - @Override - public void close() { - shutdown(); - } - - private String format(final HttpRoute route, final Object state) { - final StringBuilder buf = new StringBuilder(); - buf.append("[route: ").append(route).append("]"); - if (state != null) { - buf.append("[state: ").append(state).append("]"); - } - return buf.toString(); - } - - private String formatStats(final HttpRoute route) { - final StringBuilder buf = new StringBuilder(); - final PoolStats totals = this.pool.getTotalStats(); - final PoolStats stats = this.pool.getStats(route); - buf.append("[total kept alive: ").append(totals.getAvailable()).append("; "); - buf.append("route allocated: ").append(stats.getLeased() + stats.getAvailable()); - buf.append(" of ").append(stats.getMax()).append("; "); - buf.append("total allocated: ").append(totals.getLeased() + totals.getAvailable()); - buf.append(" of ").append(totals.getMax()).append("]"); - return buf.toString(); - } - - private String format(final CPoolEntry entry) { - final StringBuilder buf = new StringBuilder(); - buf.append("[id: ").append(entry.getId()).append("]"); - buf.append("[route: ").append(entry.getRoute()).append("]"); - final Object state = entry.getState(); - if (state != null) { - buf.append("[state: ").append(state).append("]"); - } - return buf.toString(); - } - - @Override - public ConnectionRequest requestConnection( - final HttpRoute route, - final Object state) { - Args.notNull(route, "HTTP route"); - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Connection request: " + format(route, state) + formatStats(route)); - } - final Future future = this.pool.lease(route, state, null); - return new ConnectionRequest() { - - @Override - public boolean cancel() { - return future.cancel(true); - } - - @Override - public HttpClientConnection get( - final long timeout, - final TimeUnit tunit) throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException { - return leaseConnection(future, timeout, tunit); - } - - }; - - } - - protected HttpClientConnection leaseConnection( - final Future future, - final long timeout, - final TimeUnit tunit) throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException { - final CPoolEntry 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.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Connection leased: " + format(entry) + formatStats(entry.getRoute())); - } - return CPoolProxy.newProxy(entry); - } catch (final TimeoutException ex) { - throw new ConnectionPoolTimeoutException("Timeout waiting for connection from pool"); - } - } - - @Override - public void releaseConnection( - final HttpClientConnection managedConn, - final Object state, - final long keepalive, final TimeUnit tunit) { - Args.notNull(managedConn, "Managed connection"); - synchronized (managedConn) { - final CPoolEntry entry = CPoolProxy.detach(managedConn); - if (entry == null) { - return; - } - final ManagedHttpClientConnection conn = entry.getConnection(); - try { - if (conn.isOpen()) { - final TimeUnit effectiveUnit = tunit != null ? tunit : TimeUnit.MILLISECONDS; - entry.setState(state); - entry.updateExpiry(keepalive, effectiveUnit); - if (this.log.isLoggable(Level.FINE)) { - final String s; - if (keepalive > 0) { - s = "for " + (double) effectiveUnit.toMillis(keepalive) / 1000 + " seconds"; - } else { - s = "indefinitely"; - } - this.log.log(Level.FINE, "Connection " + format(entry) + " can be kept alive " + s); - } - } - } finally { - this.pool.release(entry, conn.isOpen() && entry.isRouteComplete()); - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Connection released: " + format(entry) + formatStats(entry.getRoute())); - } - } - } - } - - @Override - public void connect( - final HttpClientConnection managedConn, - final HttpRoute route, - final int connectTimeout, - final HttpContext context) throws IOException { - Args.notNull(managedConn, "Managed Connection"); - Args.notNull(route, "HTTP route"); - final ManagedHttpClientConnection conn; - synchronized (managedConn) { - final CPoolEntry entry = CPoolProxy.getPoolEntry(managedConn); - conn = entry.getConnection(); - } - final HttpHost host; - if (route.getProxyHost() != null) { - host = route.getProxyHost(); - } else { - host = route.getTargetHost(); - } - final InetSocketAddress localAddress = route.getLocalSocketAddress(); - SocketConfig socketConfig = this.configData.getSocketConfig(host); - if (socketConfig == null) { - socketConfig = this.configData.getDefaultSocketConfig(); - } - if (socketConfig == null) { - socketConfig = SocketConfig.DEFAULT; - } - this.connectionOperator.connect( - conn, host, localAddress, connectTimeout, socketConfig, context); - } - - @Override - public void upgrade( - final HttpClientConnection managedConn, - final HttpRoute route, - final HttpContext context) throws IOException { - Args.notNull(managedConn, "Managed Connection"); - Args.notNull(route, "HTTP route"); - final ManagedHttpClientConnection conn; - synchronized (managedConn) { - final CPoolEntry entry = CPoolProxy.getPoolEntry(managedConn); - conn = entry.getConnection(); - } - this.connectionOperator.upgrade(conn, route.getTargetHost(), context); - } - - @Override - public void routeComplete( - final HttpClientConnection managedConn, - final HttpRoute route, - final HttpContext context) throws IOException { - Args.notNull(managedConn, "Managed Connection"); - Args.notNull(route, "HTTP route"); - synchronized (managedConn) { - final CPoolEntry entry = CPoolProxy.getPoolEntry(managedConn); - entry.markRouteComplete(); - } - } - - @Override - public void shutdown() { - if (this.isShutDown.compareAndSet(false, true)) { - this.log.log(Level.FINE, "Connection manager is shutting down"); - try { - this.pool.shutdown(); - } catch (final IOException ex) { - this.log.log(Level.FINE, "I/O exception shutting down connection manager", ex); - } - this.log.log(Level.FINE, "Connection manager shut down"); - } - } - - @Override - public void closeIdleConnections(final long idleTimeout, final TimeUnit tunit) { - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Closing connections idle longer than " + idleTimeout + " " + tunit); - } - this.pool.closeIdle(idleTimeout, tunit); - } - - @Override - public void closeExpiredConnections() { - this.log.log(Level.FINE, "Closing expired connections"); - this.pool.closeExpired(); - } - - @Override - public int getMaxTotal() { - return this.pool.getMaxTotal(); - } - - @Override - public void setMaxTotal(final int max) { - this.pool.setMaxTotal(max); - } - - @Override - public int getDefaultMaxPerRoute() { - return this.pool.getDefaultMaxPerRoute(); - } - - @Override - public void setDefaultMaxPerRoute(final int max) { - this.pool.setDefaultMaxPerRoute(max); - } - - @Override - public int getMaxPerRoute(final HttpRoute route) { - return this.pool.getMaxPerRoute(route); - } - - @Override - public void setMaxPerRoute(final HttpRoute route, final int max) { - this.pool.setMaxPerRoute(route, max); - } - - @Override - public PoolStats getTotalStats() { - return this.pool.getTotalStats(); - } - - @Override - public PoolStats getStats(final HttpRoute route) { - return this.pool.getStats(route); - } - - /** - * @since 4.4 - */ - public Set getRoutes() { - return this.pool.getRoutes(); - } - - public SocketConfig getDefaultSocketConfig() { - return this.configData.getDefaultSocketConfig(); - } - - public void setDefaultSocketConfig(final SocketConfig defaultSocketConfig) { - this.configData.setDefaultSocketConfig(defaultSocketConfig); - } - - public ConnectionConfig getDefaultConnectionConfig() { - return this.configData.getDefaultConnectionConfig(); - } - - public void setDefaultConnectionConfig(final ConnectionConfig defaultConnectionConfig) { - this.configData.setDefaultConnectionConfig(defaultConnectionConfig); - } - - public SocketConfig getSocketConfig(final HttpHost host) { - return this.configData.getSocketConfig(host); - } - - public void setSocketConfig(final HttpHost host, final SocketConfig socketConfig) { - this.configData.setSocketConfig(host, socketConfig); - } - - public ConnectionConfig getConnectionConfig(final HttpHost host) { - return this.configData.getConnectionConfig(host); - } - - public void setConnectionConfig(final HttpHost host, final ConnectionConfig connectionConfig) { - this.configData.setConnectionConfig(host, connectionConfig); - } - - /** - * @see #setValidateAfterInactivity(int) - * - * @since 4.4 - */ - public int getValidateAfterInactivity() { - return pool.getValidateAfterInactivity(); - } - - /** - * Defines period of inactivity in milliseconds after which persistent connections must - * be re-validated prior to being {@link #leaseConnection(java.util.concurrent.Future, - * long, java.util.concurrent.TimeUnit) leased} to the consumer. Non-positive value passed - * to this method disables connection validation. This check helps detect connections - * that have become stale (half-closed) while kept inactive in the pool. - * - * @see #leaseConnection(java.util.concurrent.Future, long, java.util.concurrent.TimeUnit) - * - * @since 4.4 - */ - public void setValidateAfterInactivity(final int ms) { - pool.setValidateAfterInactivity(ms); - } - - static class ConfigData { - - private final Map socketConfigMap; - private final Map connectionConfigMap; - private volatile SocketConfig defaultSocketConfig; - private volatile ConnectionConfig defaultConnectionConfig; - - ConfigData() { - super(); - this.socketConfigMap = new ConcurrentHashMap(); - this.connectionConfigMap = new ConcurrentHashMap(); - } - - public SocketConfig getDefaultSocketConfig() { - return this.defaultSocketConfig; - } - - public void setDefaultSocketConfig(final SocketConfig defaultSocketConfig) { - this.defaultSocketConfig = defaultSocketConfig; - } - - public ConnectionConfig getDefaultConnectionConfig() { - return this.defaultConnectionConfig; - } - - public void setDefaultConnectionConfig(final ConnectionConfig defaultConnectionConfig) { - this.defaultConnectionConfig = defaultConnectionConfig; - } - - public SocketConfig getSocketConfig(final HttpHost host) { - return this.socketConfigMap.get(host); - } - - public void setSocketConfig(final HttpHost host, final SocketConfig socketConfig) { - this.socketConfigMap.put(host, socketConfig); - } - - public ConnectionConfig getConnectionConfig(final HttpHost host) { - return this.connectionConfigMap.get(host); - } - - public void setConnectionConfig(final HttpHost host, final ConnectionConfig connectionConfig) { - this.connectionConfigMap.put(host, connectionConfig); - } - - } - - 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/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/SystemDefaultDnsResolver.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/SystemDefaultDnsResolver.java deleted file mode 100644 index 24558211..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/SystemDefaultDnsResolver.java +++ /dev/null @@ -1,48 +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 com.tracelytics.ext.apache.http.impl.conn; - -import java.net.InetAddress; -import java.net.UnknownHostException; - -import com.tracelytics.ext.apache.http.conn.DnsResolver; - -/** - * DNS resolver that uses the default OS implementation for resolving host names. - * - * @since 4.2 - */ -public class SystemDefaultDnsResolver implements DnsResolver { - - public static final SystemDefaultDnsResolver INSTANCE = new SystemDefaultDnsResolver(); - - @Override - public InetAddress[] resolve(final String host) throws UnknownHostException { - return InetAddress.getAllByName(host); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/SystemDefaultRoutePlanner.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/SystemDefaultRoutePlanner.java deleted file mode 100644 index 9ce20940..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/SystemDefaultRoutePlanner.java +++ /dev/null @@ -1,133 +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 com.tracelytics.ext.apache.http.impl.conn; - -import java.net.InetSocketAddress; -import java.net.Proxy; -import java.net.ProxySelector; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.List; - -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -import com.tracelytics.ext.apache.http.conn.SchemePortResolver; - -/** - * {@link com.tracelytics.ext.apache.http.conn.routing.HttpRoutePlanner} implementation - * based on {@link ProxySelector}. By default, this class will pick up - * the proxy settings of the JVM, either from system properties - * or from the browser running the application. - * - * @since 4.3 - */ -@Immutable -public class SystemDefaultRoutePlanner extends DefaultRoutePlanner { - - private final ProxySelector proxySelector; - - public SystemDefaultRoutePlanner( - final SchemePortResolver schemePortResolver, - final ProxySelector proxySelector) { - super(schemePortResolver); - this.proxySelector = proxySelector != null ? proxySelector : ProxySelector.getDefault(); - } - - public SystemDefaultRoutePlanner(final ProxySelector proxySelector) { - this(null, proxySelector); - } - - @Override - protected HttpHost determineProxy( - final HttpHost target, - final HttpRequest request, - final HttpContext context) throws HttpException { - final URI targetURI; - try { - targetURI = new URI(target.toURI()); - } catch (final URISyntaxException ex) { - throw new HttpException("Cannot convert host to URI: " + target, ex); - } - final List proxies = this.proxySelector.select(targetURI); - final Proxy p = chooseProxy(proxies); - HttpHost result = null; - if (p.type() == Proxy.Type.HTTP) { - // convert the socket address to an HttpHost - if (!(p.address() instanceof InetSocketAddress)) { - throw new HttpException("Unable to handle non-Inet proxy address: " + p.address()); - } - final InetSocketAddress isa = (InetSocketAddress) p.address(); - // assume default scheme (http) - result = new HttpHost(getHost(isa), isa.getPort()); - } - - return result; - } - - private String getHost(final InetSocketAddress isa) { - - //@@@ Will this work with literal IPv6 addresses, or do we - //@@@ need to wrap these in [] for the string representation? - //@@@ Having it in this method at least allows for easy workarounds. - return isa.isUnresolved() ? - isa.getHostName() : isa.getAddress().getHostAddress(); - - } - - private Proxy chooseProxy(final List proxies) { - Proxy result = null; - // check the list for one we can use - for (int i=0; (result == null) && (i < proxies.size()); i++) { - final Proxy p = proxies.get(i); - switch (p.type()) { - - case DIRECT: - case HTTP: - result = p; - break; - - case SOCKS: - // SOCKS hosts are not handled on the route level. - // The socket may make use of the SOCKS host though. - break; - } - } - if (result == null) { - //@@@ log as warning or info that only a socks proxy is available? - // result can only be null if all proxies are socks proxies - // socks proxies are not handled on the route planning level - result = Proxy.NO_PROXY; - } - return result; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/Wire.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/Wire.java deleted file mode 100644 index 6637dd7b..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/Wire.java +++ /dev/null @@ -1,153 +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 com.tracelytics.ext.apache.http.impl.conn; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Logs data to the wire LOG. - * TODO: make package private. Should not be part of the public API. - * - * @since 4.0 - */ -@Immutable -public class Wire { - - private final Logger log; - private final String id; - - /** - * @since 4.3 - */ - public Wire(final Logger log, final String id) { - this.log = log; - this.id = id; - } - - public Wire(final Logger log) { - this(log, ""); - } - - private void wire(final String header, final InputStream instream) - throws IOException { - final StringBuilder buffer = new StringBuilder(); - int ch; - while ((ch = instream.read()) != -1) { - if (ch == 13) { - buffer.append("[\\r]"); - } else if (ch == 10) { - buffer.append("[\\n]\""); - buffer.insert(0, "\""); - buffer.insert(0, header); - log.log(Level.FINE, id + " " + buffer.toString()); - buffer.setLength(0); - } else if ((ch < 32) || (ch > 127)) { - buffer.append("[0x"); - buffer.append(Integer.toHexString(ch)); - buffer.append("]"); - } else { - buffer.append((char) ch); - } - } - if (buffer.length() > 0) { - buffer.append('\"'); - buffer.insert(0, '\"'); - buffer.insert(0, header); - log.log(Level.FINE, id + " " + buffer.toString()); - } - } - - - public boolean enabled() { - return log.isLoggable(Level.FINE); - } - - public void output(final InputStream outstream) - throws IOException { - Args.notNull(outstream, "Output"); - wire(">> ", outstream); - } - - public void input(final InputStream instream) - throws IOException { - Args.notNull(instream, "Input"); - wire("<< ", instream); - } - - public void output(final byte[] b, final int off, final int len) - throws IOException { - Args.notNull(b, "Output"); - wire(">> ", new ByteArrayInputStream(b, off, len)); - } - - public void input(final byte[] b, final int off, final int len) - throws IOException { - Args.notNull(b, "Input"); - wire("<< ", new ByteArrayInputStream(b, off, len)); - } - - public void output(final byte[] b) - throws IOException { - Args.notNull(b, "Output"); - wire(">> ", new ByteArrayInputStream(b)); - } - - public void input(final byte[] b) - throws IOException { - Args.notNull(b, "Input"); - wire("<< ", new ByteArrayInputStream(b)); - } - - public void output(final int b) - throws IOException { - output(new byte[] {(byte) b}); - } - - public void input(final int b) - throws IOException { - input(new byte[] {(byte) b}); - } - - public void output(final String s) - throws IOException { - Args.notNull(s, "Output"); - output(s.getBytes()); - } - - public void input(final String s) - throws IOException { - Args.notNull(s, "Input"); - input(s.getBytes()); - } -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/package-info.java deleted file mode 100644 index 18a4f2c4..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/conn/package-info.java +++ /dev/null @@ -1,32 +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 - * . - * - */ - -/** - * Default implementations of client connection management - * functions. - */ -package com.tracelytics.ext.apache.http.impl.conn; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/AbstractCookieAttributeHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/AbstractCookieAttributeHandler.java deleted file mode 100644 index 07780210..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/AbstractCookieAttributeHandler.java +++ /dev/null @@ -1,55 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import com.tracelytics.ext.apache.http.annotation.Immutable; - -import com.tracelytics.ext.apache.http.cookie.Cookie; -import com.tracelytics.ext.apache.http.cookie.CookieAttributeHandler; -import com.tracelytics.ext.apache.http.cookie.CookieOrigin; -import com.tracelytics.ext.apache.http.cookie.MalformedCookieException; - -/** - * - * @since 4.0 - */ -@Immutable -public abstract class AbstractCookieAttributeHandler implements CookieAttributeHandler { - - @Override - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - // Do nothing - } - - @Override - public boolean match(final Cookie cookie, final CookieOrigin origin) { - // Always match - return true; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/AbstractCookieSpec.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/AbstractCookieSpec.java deleted file mode 100644 index 3a8dc7f4..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/AbstractCookieSpec.java +++ /dev/null @@ -1,131 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.Asserts; - -import com.tracelytics.ext.apache.http.cookie.CommonCookieAttributeHandler; -import com.tracelytics.ext.apache.http.cookie.CookieAttributeHandler; -import com.tracelytics.ext.apache.http.cookie.CookieSpec; - -/** - * Abstract cookie specification which can delegate the job of parsing, - * validation or matching cookie attributes to a number of arbitrary - * {@link CookieAttributeHandler}s. - * - * - * @since 4.0 - */ -@ThreadSafe -public abstract class AbstractCookieSpec implements CookieSpec { - - /** - * Stores attribute name -> attribute handler mappings - */ - private final Map attribHandlerMap; - - /** - * Default constructor - * */ - public AbstractCookieSpec() { - super(); - this.attribHandlerMap = new ConcurrentHashMap(10); - } - - /** - * @since 4.4 - */ - protected AbstractCookieSpec(final HashMap map) { - super(); - Asserts.notNull(map, "Attribute handler map"); - this.attribHandlerMap = new ConcurrentHashMap(map); - } - - /** - * @since 4.4 - */ - protected AbstractCookieSpec(final CommonCookieAttributeHandler... handlers) { - super(); - this.attribHandlerMap = new ConcurrentHashMap(handlers.length); - for (CommonCookieAttributeHandler handler: handlers) { - this.attribHandlerMap.put(handler.getAttributeName(), handler); - } - } - - /** - * @deprecated (4.4) use {@link #AbstractCookieSpec(java.util.HashMap)} or - * {@link #AbstractCookieSpec(com.tracelytics.ext.apache.http.cookie.CommonCookieAttributeHandler...)} - * constructors instead. - */ - @Deprecated - public void registerAttribHandler( - final String name, final CookieAttributeHandler handler) { - Args.notNull(name, "Attribute name"); - Args.notNull(handler, "Attribute handler"); - this.attribHandlerMap.put(name, handler); - } - - /** - * Finds an attribute handler {@link CookieAttributeHandler} for the - * given attribute. Returns {@code null} if no attribute handler is - * found for the specified attribute. - * - * @param name attribute name. e.g. Domain, Path, etc. - * @return an attribute handler or {@code null} - */ - protected CookieAttributeHandler findAttribHandler(final String name) { - return this.attribHandlerMap.get(name); - } - - /** - * Gets attribute handler {@link CookieAttributeHandler} for the - * given attribute. - * - * @param name attribute name. e.g. Domain, Path, etc. - * @throws IllegalStateException if handler not found for the - * specified attribute. - */ - protected CookieAttributeHandler getAttribHandler(final String name) { - final CookieAttributeHandler handler = findAttribHandler(name); - Asserts.check(handler != null, "Handler not registered for " + - name + " attribute"); - return handler; - } - - protected Collection getAttribHandlers() { - return this.attribHandlerMap.values(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicClientCookie.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicClientCookie.java deleted file mode 100644 index 108f84fa..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicClientCookie.java +++ /dev/null @@ -1,406 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import java.io.Serializable; -import java.util.Date; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.cookie.ClientCookie; -import com.tracelytics.ext.apache.http.cookie.SetCookie; - -/** - * Default implementation of {@link SetCookie}. - * - * @since 4.0 - */ -@NotThreadSafe -public class BasicClientCookie implements SetCookie, ClientCookie, Cloneable, Serializable { - - private static final long serialVersionUID = -3869795591041535538L; - - /** - * Default Constructor taking a name and a value. The value may be null. - * - * @param name The name. - * @param value The value. - */ - public BasicClientCookie(final String name, final String value) { - super(); - Args.notNull(name, "Name"); - this.name = name; - this.attribs = new HashMap(); - this.value = value; - } - - /** - * Returns the name. - * - * @return String name The name - */ - @Override - public String getName() { - return this.name; - } - - /** - * Returns the value. - * - * @return String value The current value. - */ - @Override - public String getValue() { - return this.value; - } - - /** - * Sets the value - * - * @param value - */ - @Override - public void setValue(final String value) { - this.value = value; - } - - /** - * Returns the comment describing the purpose of this cookie, or - * {@code null} if no such comment has been defined. - * - * @return comment - * - * @see #setComment(String) - */ - @Override - public String getComment() { - return cookieComment; - } - - /** - * If a user agent (web browser) presents this cookie to a user, the - * cookie's purpose will be described using this comment. - * - * @param comment - * - * @see #getComment() - */ - @Override - public void setComment(final String comment) { - cookieComment = comment; - } - - - /** - * Returns null. Cookies prior to RFC2965 do not set this attribute - */ - @Override - public String getCommentURL() { - return null; - } - - - /** - * Returns the expiration {@link Date} of the cookie, or {@code null} - * if none exists. - *

Note: the object returned by this method is - * considered immutable. Changing it (e.g. using setTime()) could result - * in undefined behaviour. Do so at your peril.

- * @return Expiration {@link Date}, or {@code null}. - * - * @see #setExpiryDate(java.util.Date) - * - */ - @Override - public Date getExpiryDate() { - return cookieExpiryDate; - } - - /** - * Sets expiration date. - *

Note: the object returned by this method is considered - * immutable. Changing it (e.g. using setTime()) could result in undefined - * behaviour. Do so at your peril.

- * - * @param expiryDate the {@link Date} after which this cookie is no longer valid. - * - * @see #getExpiryDate - * - */ - @Override - public void setExpiryDate (final Date expiryDate) { - cookieExpiryDate = expiryDate; - } - - - /** - * Returns {@code false} if the cookie should be discarded at the end - * of the "session"; {@code true} otherwise. - * - * @return {@code false} if the cookie should be discarded at the end - * of the "session"; {@code true} otherwise - */ - @Override - public boolean isPersistent() { - return (null != cookieExpiryDate); - } - - - /** - * Returns domain attribute of the cookie. - * - * @return the value of the domain attribute - * - * @see #setDomain(java.lang.String) - */ - @Override - public String getDomain() { - return cookieDomain; - } - - /** - * Sets the domain attribute. - * - * @param domain The value of the domain attribute - * - * @see #getDomain - */ - @Override - public void setDomain(final String domain) { - if (domain != null) { - cookieDomain = domain.toLowerCase(Locale.ROOT); - } else { - cookieDomain = null; - } - } - - - /** - * Returns the path attribute of the cookie - * - * @return The value of the path attribute. - * - * @see #setPath(java.lang.String) - */ - @Override - public String getPath() { - return cookiePath; - } - - /** - * Sets the path attribute. - * - * @param path The value of the path attribute - * - * @see #getPath - * - */ - @Override - public void setPath(final String path) { - cookiePath = path; - } - - /** - * @return {@code true} if this cookie should only be sent over secure connections. - * @see #setSecure(boolean) - */ - @Override - public boolean isSecure() { - return isSecure; - } - - /** - * Sets the secure attribute of the cookie. - *

- * When {@code true} the cookie should only be sent - * using a secure protocol (https). This should only be set when - * the cookie's originating server used a secure protocol to set the - * cookie's value. - * - * @param secure The value of the secure attribute - * - * @see #isSecure() - */ - @Override - public void setSecure (final boolean secure) { - isSecure = secure; - } - - - /** - * Returns null. Cookies prior to RFC2965 do not set this attribute - */ - @Override - public int[] getPorts() { - return null; - } - - - /** - * Returns the version of the cookie specification to which this - * cookie conforms. - * - * @return the version of the cookie. - * - * @see #setVersion(int) - * - */ - @Override - public int getVersion() { - return cookieVersion; - } - - /** - * Sets the version of the cookie specification to which this - * cookie conforms. - * - * @param version the version of the cookie. - * - * @see #getVersion - */ - @Override - public void setVersion(final int version) { - cookieVersion = version; - } - - /** - * Returns true if this cookie has expired. - * @param date Current time - * - * @return {@code true} if the cookie has expired. - */ - @Override - public boolean isExpired(final Date date) { - Args.notNull(date, "Date"); - return (cookieExpiryDate != null - && cookieExpiryDate.getTime() <= date.getTime()); - } - - /** - * @since 4.4 - */ - public Date getCreationDate() { - return creationDate; - } - - /** - * @since 4.4 - */ - public void setCreationDate(final Date creationDate) { - this.creationDate = creationDate; - } - - public void setAttribute(final String name, final String value) { - this.attribs.put(name, value); - } - - @Override - public String getAttribute(final String name) { - return this.attribs.get(name); - } - - @Override - public boolean containsAttribute(final String name) { - return this.attribs.containsKey(name); - } - - /** - * @since 4.4 - */ - public boolean removeAttribute(final String name) { - return this.attribs.remove(name) != null; - } - - @Override - public Object clone() throws CloneNotSupportedException { - final BasicClientCookie clone = (BasicClientCookie) super.clone(); - clone.attribs = new HashMap(this.attribs); - return clone; - } - - @Override - public String toString() { - final StringBuilder buffer = new StringBuilder(); - buffer.append("[version: "); - buffer.append(Integer.toString(this.cookieVersion)); - buffer.append("]"); - buffer.append("[name: "); - buffer.append(this.name); - buffer.append("]"); - buffer.append("[value: "); - buffer.append(this.value); - buffer.append("]"); - buffer.append("[domain: "); - buffer.append(this.cookieDomain); - buffer.append("]"); - buffer.append("[path: "); - buffer.append(this.cookiePath); - buffer.append("]"); - buffer.append("[expiry: "); - buffer.append(this.cookieExpiryDate); - buffer.append("]"); - return buffer.toString(); - } - - // ----------------------------------------------------- Instance Variables - - /** Cookie name */ - private final String name; - - /** Cookie attributes as specified by the origin server */ - private Map attribs; - - /** Cookie value */ - private String value; - - /** Comment attribute. */ - private String cookieComment; - - /** Domain attribute. */ - private String cookieDomain; - - /** Expiration {@link Date}. */ - private Date cookieExpiryDate; - - /** Path attribute. */ - private String cookiePath; - - /** My secure flag. */ - private boolean isSecure; - - /** The version of the cookie specification I was created from. */ - private int cookieVersion; - - private Date creationDate; - -} - diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicClientCookie2.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicClientCookie2.java deleted file mode 100644 index 0e3df833..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicClientCookie2.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 com.tracelytics.ext.apache.http.impl.cookie; - -import java.util.Date; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; - -import com.tracelytics.ext.apache.http.cookie.SetCookie2; - -/** - * Default implementation of {@link SetCookie2}. - * - * @since 4.0 - */ -@NotThreadSafe -public class BasicClientCookie2 extends BasicClientCookie implements SetCookie2 { - - private static final long serialVersionUID = -7744598295706617057L; - - private String commentURL; - private int[] ports; - private boolean discard; - - /** - * Default Constructor taking a name and a value. The value may be null. - * - * @param name The name. - * @param value The value. - */ - public BasicClientCookie2(final String name, final String value) { - super(name, value); - } - - @Override - public int[] getPorts() { - return this.ports; - } - - @Override - public void setPorts(final int[] ports) { - this.ports = ports; - } - - @Override - public String getCommentURL() { - return this.commentURL; - } - - @Override - public void setCommentURL(final String commentURL) { - this.commentURL = commentURL; - } - - @Override - public void setDiscard(final boolean discard) { - this.discard = discard; - } - - @Override - public boolean isPersistent() { - return !this.discard && super.isPersistent(); - } - - @Override - public boolean isExpired(final Date date) { - return this.discard || super.isExpired(date); - } - - @Override - public Object clone() throws CloneNotSupportedException { - final BasicClientCookie2 clone = (BasicClientCookie2) super.clone(); - if (this.ports != null) { - clone.ports = this.ports.clone(); - } - return clone; - } - -} - diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicCommentHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicCommentHandler.java deleted file mode 100644 index 5624d1e6..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicCommentHandler.java +++ /dev/null @@ -1,60 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.cookie.ClientCookie; -import com.tracelytics.ext.apache.http.cookie.CommonCookieAttributeHandler; -import com.tracelytics.ext.apache.http.cookie.MalformedCookieException; -import com.tracelytics.ext.apache.http.cookie.SetCookie; - -/** - * - * @since 4.0 - */ -@Immutable -public class BasicCommentHandler extends AbstractCookieAttributeHandler implements CommonCookieAttributeHandler { - - public BasicCommentHandler() { - super(); - } - - @Override - public void parse(final SetCookie cookie, final String value) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - cookie.setComment(value); - } - - @Override - public String getAttributeName() { - return ClientCookie.COMMENT_ATTR; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicDomainHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicDomainHandler.java deleted file mode 100644 index 281d8307..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicDomainHandler.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 com.tracelytics.ext.apache.http.impl.cookie; - -import java.util.Locale; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.TextUtils; - -import com.tracelytics.ext.apache.http.conn.util.InetAddressUtils; -import com.tracelytics.ext.apache.http.cookie.ClientCookie; -import com.tracelytics.ext.apache.http.cookie.CommonCookieAttributeHandler; -import com.tracelytics.ext.apache.http.cookie.Cookie; -import com.tracelytics.ext.apache.http.cookie.CookieOrigin; -import com.tracelytics.ext.apache.http.cookie.CookieRestrictionViolationException; -import com.tracelytics.ext.apache.http.cookie.MalformedCookieException; -import com.tracelytics.ext.apache.http.cookie.SetCookie; - -/** - * - * @since 4.0 - */ -@Immutable -public class BasicDomainHandler implements CommonCookieAttributeHandler { - - public BasicDomainHandler() { - super(); - } - - @Override - public void parse(final SetCookie cookie, final String value) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - if (TextUtils.isBlank(value)) { - throw new MalformedCookieException("Blank or null value for domain attribute"); - } - // Ignore domain attributes ending with '.' per RFC 6265, 4.1.2.3 - if (value.endsWith(".")) { - return; - } - String domain = value; - if (domain.startsWith(".")) { - domain = domain.substring(1); - } - domain = domain.toLowerCase(Locale.ROOT); - cookie.setDomain(domain); - } - - @Override - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - // Validate the cookies domain attribute. NOTE: Domains without - // any dots are allowed to support hosts on private LANs that don't - // have DNS names. Since they have no dots, to domain-match the - // request-host and domain must be identical for the cookie to sent - // back to the origin-server. - final String host = origin.getHost(); - final String domain = cookie.getDomain(); - if (domain == null) { - throw new CookieRestrictionViolationException("Cookie 'domain' may not be null"); - } - if (!host.equals(domain) && !domainMatch(domain, host)) { - throw new CookieRestrictionViolationException( - "Illegal 'domain' attribute \"" + domain + "\". Domain of origin: \"" + host + "\""); - } - } - - static boolean domainMatch(final String domain, final String host) { - if (InetAddressUtils.isIPv4Address(host) || InetAddressUtils.isIPv6Address(host)) { - return false; - } - final String normalizedDomain = domain.startsWith(".") ? domain.substring(1) : domain; - if (host.endsWith(normalizedDomain)) { - final int prefix = host.length() - normalizedDomain.length(); - // Either a full match or a prefix endidng with a '.' - if (prefix == 0) { - return true; - } - if (prefix > 1 && host.charAt(prefix - 1) == '.') { - return true; - } - } - return false; - } - - @Override - public boolean match(final Cookie cookie, final CookieOrigin origin) { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - final String host = origin.getHost(); - String domain = cookie.getDomain(); - if (domain == null) { - return false; - } - if (domain.startsWith(".")) { - domain = domain.substring(1); - } - domain = domain.toLowerCase(Locale.ROOT); - if (host.equals(domain)) { - return true; - } - if (cookie instanceof ClientCookie) { - if (((ClientCookie) cookie).containsAttribute(ClientCookie.DOMAIN_ATTR)) { - return domainMatch(domain, host); - } - } - return false; - } - - @Override - public String getAttributeName() { - return ClientCookie.DOMAIN_ATTR; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicExpiresHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicExpiresHandler.java deleted file mode 100644 index 9cd0a4da..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicExpiresHandler.java +++ /dev/null @@ -1,75 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import java.util.Date; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.client.utils.DateUtils; -import com.tracelytics.ext.apache.http.cookie.ClientCookie; -import com.tracelytics.ext.apache.http.cookie.CommonCookieAttributeHandler; -import com.tracelytics.ext.apache.http.cookie.MalformedCookieException; -import com.tracelytics.ext.apache.http.cookie.SetCookie; - -/** - * - * @since 4.0 - */ -@Immutable -public class BasicExpiresHandler extends AbstractCookieAttributeHandler implements CommonCookieAttributeHandler { - - /** Valid date patterns */ - private final String[] datepatterns; - - public BasicExpiresHandler(final String[] datepatterns) { - Args.notNull(datepatterns, "Array of date patterns"); - this.datepatterns = datepatterns; - } - - @Override - public void parse(final SetCookie cookie, final String value) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - if (value == null) { - throw new MalformedCookieException("Missing value for 'expires' attribute"); - } - final Date expiry = DateUtils.parseDate(value, this.datepatterns); - if (expiry == null) { - throw new MalformedCookieException("Invalid 'expires' attribute: " - + value); - } - cookie.setExpiryDate(expiry); - } - - @Override - public String getAttributeName() { - return ClientCookie.EXPIRES_ATTR; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicMaxAgeHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicMaxAgeHandler.java deleted file mode 100644 index 170efc84..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicMaxAgeHandler.java +++ /dev/null @@ -1,76 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import java.util.Date; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.cookie.ClientCookie; -import com.tracelytics.ext.apache.http.cookie.CommonCookieAttributeHandler; -import com.tracelytics.ext.apache.http.cookie.MalformedCookieException; -import com.tracelytics.ext.apache.http.cookie.SetCookie; - -/** - * - * @since 4.0 - */ -@Immutable -public class BasicMaxAgeHandler extends AbstractCookieAttributeHandler implements CommonCookieAttributeHandler { - - public BasicMaxAgeHandler() { - super(); - } - - @Override - public void parse(final SetCookie cookie, final String value) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - if (value == null) { - throw new MalformedCookieException("Missing value for 'max-age' attribute"); - } - final int age; - try { - age = Integer.parseInt(value); - } catch (final NumberFormatException e) { - throw new MalformedCookieException ("Invalid 'max-age' attribute: " - + value); - } - if (age < 0) { - throw new MalformedCookieException ("Negative 'max-age' attribute: " - + value); - } - cookie.setExpiryDate(new Date(System.currentTimeMillis() + age * 1000L)); - } - - @Override - public String getAttributeName() { - return ClientCookie.MAX_AGE_ATTR; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicPathHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicPathHandler.java deleted file mode 100644 index be89a6d4..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicPathHandler.java +++ /dev/null @@ -1,103 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.TextUtils; - -import com.tracelytics.ext.apache.http.cookie.ClientCookie; -import com.tracelytics.ext.apache.http.cookie.CommonCookieAttributeHandler; -import com.tracelytics.ext.apache.http.cookie.Cookie; -import com.tracelytics.ext.apache.http.cookie.CookieOrigin; -import com.tracelytics.ext.apache.http.cookie.CookieRestrictionViolationException; -import com.tracelytics.ext.apache.http.cookie.MalformedCookieException; -import com.tracelytics.ext.apache.http.cookie.SetCookie; - -/** - * - * @since 4.0 - */ -@Immutable -public class BasicPathHandler implements CommonCookieAttributeHandler { - - public BasicPathHandler() { - super(); - } - - @Override - public void parse( - final SetCookie cookie, final String value) throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - cookie.setPath(!TextUtils.isBlank(value) ? value : "/"); - } - - @Override - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - if (!match(cookie, origin)) { - throw new CookieRestrictionViolationException( - "Illegal 'path' attribute \"" + cookie.getPath() - + "\". Path of origin: \"" + origin.getPath() + "\""); - } - } - - static boolean pathMatch(final String uriPath, final String cookiePath) { - String normalizedCookiePath = cookiePath; - if (normalizedCookiePath == null) { - normalizedCookiePath = "/"; - } - if (normalizedCookiePath.length() > 1 && normalizedCookiePath.endsWith("/")) { - normalizedCookiePath = normalizedCookiePath.substring(0, normalizedCookiePath.length() - 1); - } - if (uriPath.startsWith(normalizedCookiePath)) { - if (normalizedCookiePath.equals("/")) { - return true; - } - if (uriPath.length() == normalizedCookiePath.length()) { - return true; - } - if (uriPath.charAt(normalizedCookiePath.length()) == '/') { - return true; - } - } - return false; - } - - @Override - public boolean match(final Cookie cookie, final CookieOrigin origin) { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - return pathMatch(origin.getPath(), cookie.getPath()); - } - - @Override - public String getAttributeName() { - return ClientCookie.PATH_ATTR; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicSecureHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicSecureHandler.java deleted file mode 100644 index 8b5c51e7..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/BasicSecureHandler.java +++ /dev/null @@ -1,69 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.cookie.ClientCookie; -import com.tracelytics.ext.apache.http.cookie.CommonCookieAttributeHandler; -import com.tracelytics.ext.apache.http.cookie.Cookie; -import com.tracelytics.ext.apache.http.cookie.CookieOrigin; -import com.tracelytics.ext.apache.http.cookie.MalformedCookieException; -import com.tracelytics.ext.apache.http.cookie.SetCookie; - -/** - * - * @since 4.0 - */ -@Immutable -public class BasicSecureHandler extends AbstractCookieAttributeHandler implements CommonCookieAttributeHandler { - - public BasicSecureHandler() { - super(); - } - - @Override - public void parse(final SetCookie cookie, final String value) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - cookie.setSecure(true); - } - - @Override - public boolean match(final Cookie cookie, final CookieOrigin origin) { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - return !cookie.isSecure() || origin.isSecure(); - } - - @Override - public String getAttributeName() { - return ClientCookie.SECURE_ATTR; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/CookieSpecBase.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/CookieSpecBase.java deleted file mode 100644 index 6b44e934..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/CookieSpecBase.java +++ /dev/null @@ -1,143 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; - -import com.tracelytics.ext.apache.http.HeaderElement; -import com.tracelytics.ext.apache.http.NameValuePair; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.cookie.CommonCookieAttributeHandler; -import com.tracelytics.ext.apache.http.cookie.Cookie; -import com.tracelytics.ext.apache.http.cookie.CookieAttributeHandler; -import com.tracelytics.ext.apache.http.cookie.CookieOrigin; -import com.tracelytics.ext.apache.http.cookie.MalformedCookieException; - -/** - * Cookie management functions shared by all specification. - * - * @since 4.0 - */ -@ThreadSafe -public abstract class CookieSpecBase extends AbstractCookieSpec { - - public CookieSpecBase() { - super(); - } - - /** - * @since 4.4 - */ - protected CookieSpecBase(final HashMap map) { - super(map); - } - - /** - * @since 4.4 - */ - protected CookieSpecBase(final CommonCookieAttributeHandler... handlers) { - super(handlers); - } - - protected static String getDefaultPath(final CookieOrigin origin) { - String defaultPath = origin.getPath(); - int lastSlashIndex = defaultPath.lastIndexOf('/'); - if (lastSlashIndex >= 0) { - if (lastSlashIndex == 0) { - //Do not remove the very first slash - lastSlashIndex = 1; - } - defaultPath = defaultPath.substring(0, lastSlashIndex); - } - return defaultPath; - } - - protected static String getDefaultDomain(final CookieOrigin origin) { - return origin.getHost(); - } - - protected List parse(final HeaderElement[] elems, final CookieOrigin origin) - throws MalformedCookieException { - final List cookies = new ArrayList(elems.length); - for (final HeaderElement headerelement : elems) { - final String name = headerelement.getName(); - final String value = headerelement.getValue(); - if (name == null || name.isEmpty()) { - throw new MalformedCookieException("Cookie name may not be empty"); - } - - final BasicClientCookie cookie = new BasicClientCookie(name, value); - cookie.setPath(getDefaultPath(origin)); - cookie.setDomain(getDefaultDomain(origin)); - - // cycle through the parameters - final NameValuePair[] attribs = headerelement.getParameters(); - for (int j = attribs.length - 1; j >= 0; j--) { - final NameValuePair attrib = attribs[j]; - final String s = attrib.getName().toLowerCase(Locale.ROOT); - - cookie.setAttribute(s, attrib.getValue()); - - final CookieAttributeHandler handler = findAttribHandler(s); - if (handler != null) { - handler.parse(cookie, attrib.getValue()); - } - } - cookies.add(cookie); - } - return cookies; - } - - @Override - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - for (final CookieAttributeHandler handler: getAttribHandlers()) { - handler.validate(cookie, origin); - } - } - - @Override - public boolean match(final Cookie cookie, final CookieOrigin origin) { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - for (final CookieAttributeHandler handler: getAttribHandlers()) { - if (!handler.match(cookie, origin)) { - return false; - } - } - return true; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/DefaultCookieSpec.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/DefaultCookieSpec.java deleted file mode 100644 index d1857e08..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/DefaultCookieSpec.java +++ /dev/null @@ -1,222 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import java.util.List; - -import com.tracelytics.ext.apache.http.FormattedHeader; -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HeaderElement; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.message.ParserCursor; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -import com.tracelytics.ext.apache.http.cookie.Cookie; -import com.tracelytics.ext.apache.http.cookie.CookieOrigin; -import com.tracelytics.ext.apache.http.cookie.CookieSpec; -import com.tracelytics.ext.apache.http.cookie.MalformedCookieException; -import com.tracelytics.ext.apache.http.cookie.SM; -import com.tracelytics.ext.apache.http.cookie.SetCookie2; - -/** - * Default cookie specification that picks up the bests matching cookie policy based on - * the format of cookies sent with the HTTP response. - * - * @since 4.4 - */ -@ThreadSafe -public class DefaultCookieSpec implements CookieSpec { - - private final RFC2965Spec strict; - private final RFC2109Spec obsoleteStrict; - private final NetscapeDraftSpec netscapeDraft; - - DefaultCookieSpec( - final RFC2965Spec strict, - final RFC2109Spec obsoleteStrict, - final NetscapeDraftSpec netscapeDraft) { - this.strict = strict; - this.obsoleteStrict = obsoleteStrict; - this.netscapeDraft = netscapeDraft; - } - - public DefaultCookieSpec( - final String[] datepatterns, - final boolean oneHeader) { - super(); - this.strict = new RFC2965Spec(oneHeader, - new RFC2965VersionAttributeHandler(), - new BasicPathHandler(), - new RFC2965DomainAttributeHandler(), - new RFC2965PortAttributeHandler(), - new BasicMaxAgeHandler(), - new BasicSecureHandler(), - new BasicCommentHandler(), - new RFC2965CommentUrlAttributeHandler(), - new RFC2965DiscardAttributeHandler()); - this.obsoleteStrict = new RFC2109Spec(oneHeader, - new RFC2109VersionHandler(), - new BasicPathHandler(), - new RFC2109DomainHandler(), - new BasicMaxAgeHandler(), - new BasicSecureHandler(), - new BasicCommentHandler()); - this.netscapeDraft = new NetscapeDraftSpec( - new BasicDomainHandler(), - new BasicPathHandler(), - new BasicSecureHandler(), - new BasicCommentHandler(), - new BasicExpiresHandler( - datepatterns != null ? datepatterns.clone() : new String[]{NetscapeDraftSpec.EXPIRES_PATTERN})); - } - - public DefaultCookieSpec() { - this(null, false); - } - - @Override - public List parse( - final Header header, - final CookieOrigin origin) throws MalformedCookieException { - Args.notNull(header, "Header"); - Args.notNull(origin, "Cookie origin"); - HeaderElement[] helems = header.getElements(); - boolean versioned = false; - boolean netscape = false; - for (final HeaderElement helem: helems) { - if (helem.getParameterByName("version") != null) { - versioned = true; - } - if (helem.getParameterByName("expires") != null) { - netscape = true; - } - } - if (netscape || !versioned) { - // Need to parse the header again, because Netscape style cookies do not correctly - // support multiple header elements (comma cannot be treated as an element separator) - final NetscapeDraftHeaderParser parser = NetscapeDraftHeaderParser.DEFAULT; - final CharArrayBuffer buffer; - final ParserCursor cursor; - if (header instanceof FormattedHeader) { - buffer = ((FormattedHeader) header).getBuffer(); - cursor = new ParserCursor( - ((FormattedHeader) header).getValuePos(), - buffer.length()); - } else { - final String s = header.getValue(); - if (s == null) { - throw new MalformedCookieException("Header value is null"); - } - buffer = new CharArrayBuffer(s.length()); - buffer.append(s); - cursor = new ParserCursor(0, buffer.length()); - } - helems = new HeaderElement[] { parser.parseHeader(buffer, cursor) }; - return netscapeDraft.parse(helems, origin); - } else { - if (SM.SET_COOKIE2.equals(header.getName())) { - return strict.parse(helems, origin); - } else { - return obsoleteStrict.parse(helems, origin); - } - } - } - - @Override - public void validate( - final Cookie cookie, - final CookieOrigin origin) throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - if (cookie.getVersion() > 0) { - if (cookie instanceof SetCookie2) { - strict.validate(cookie, origin); - } else { - obsoleteStrict.validate(cookie, origin); - } - } else { - netscapeDraft.validate(cookie, origin); - } - } - - @Override - public boolean match(final Cookie cookie, final CookieOrigin origin) { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - if (cookie.getVersion() > 0) { - if (cookie instanceof SetCookie2) { - return strict.match(cookie, origin); - } else { - return obsoleteStrict.match(cookie, origin); - } - } else { - return netscapeDraft.match(cookie, origin); - } - } - - @Override - public List

formatCookies(final List cookies) { - Args.notNull(cookies, "List of cookies"); - int version = Integer.MAX_VALUE; - boolean isSetCookie2 = true; - for (final Cookie cookie: cookies) { - if (!(cookie instanceof SetCookie2)) { - isSetCookie2 = false; - } - if (cookie.getVersion() < version) { - version = cookie.getVersion(); - } - } - if (version > 0) { - if (isSetCookie2) { - return strict.formatCookies(cookies); - } else { - return obsoleteStrict.formatCookies(cookies); - } - } else { - return netscapeDraft.formatCookies(cookies); - } - } - - @Override - public int getVersion() { - return strict.getVersion(); - } - - @Override - public Header getVersionHeader() { - return null; - } - - @Override - public String toString() { - return "default"; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/DefaultCookieSpecProvider.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/DefaultCookieSpecProvider.java deleted file mode 100644 index 4d354723..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/DefaultCookieSpecProvider.java +++ /dev/null @@ -1,135 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -import com.tracelytics.ext.apache.http.conn.util.PublicSuffixMatcher; -import com.tracelytics.ext.apache.http.cookie.Cookie; -import com.tracelytics.ext.apache.http.cookie.CookieOrigin; -import com.tracelytics.ext.apache.http.cookie.CookieSpec; -import com.tracelytics.ext.apache.http.cookie.CookieSpecProvider; -import com.tracelytics.ext.apache.http.cookie.MalformedCookieException; - -/** - * {@link com.tracelytics.ext.apache.http.cookie.CookieSpecProvider} implementation that provides an instance of - * {@link com.tracelytics.ext.apache.http.impl.cookie.DefaultCookieSpec}. The instance returned by this factory can - * be shared by multiple threads. - * - * @since 4.4 - */ -@Immutable -public class DefaultCookieSpecProvider implements CookieSpecProvider { - - public enum CompatibilityLevel { - DEFAULT, - IE_MEDIUM_SECURITY - } - - private final CompatibilityLevel compatibilityLevel; - private final PublicSuffixMatcher publicSuffixMatcher; - private final String[] datepatterns; - private final boolean oneHeader; - - private volatile CookieSpec cookieSpec; - - public DefaultCookieSpecProvider( - final CompatibilityLevel compatibilityLevel, - final PublicSuffixMatcher publicSuffixMatcher, - final String[] datepatterns, - final boolean oneHeader) { - super(); - this.compatibilityLevel = compatibilityLevel != null ? compatibilityLevel : CompatibilityLevel.DEFAULT; - this.publicSuffixMatcher = publicSuffixMatcher; - this.datepatterns = datepatterns; - this.oneHeader = oneHeader; - } - - public DefaultCookieSpecProvider( - final CompatibilityLevel compatibilityLevel, - final PublicSuffixMatcher publicSuffixMatcher) { - this(compatibilityLevel, publicSuffixMatcher, null, false); - } - - public DefaultCookieSpecProvider(final PublicSuffixMatcher publicSuffixMatcher) { - this(CompatibilityLevel.DEFAULT, publicSuffixMatcher, null, false); - } - - public DefaultCookieSpecProvider() { - this(CompatibilityLevel.DEFAULT, null, null, false); - } - - @Override - public CookieSpec create(final HttpContext context) { - if (cookieSpec == null) { - synchronized (this) { - if (cookieSpec == null) { - final RFC2965Spec strict = new RFC2965Spec(this.oneHeader, - new RFC2965VersionAttributeHandler(), - new BasicPathHandler(), - PublicSuffixDomainFilter.decorate( - new RFC2965DomainAttributeHandler(), this.publicSuffixMatcher), - new RFC2965PortAttributeHandler(), - new BasicMaxAgeHandler(), - new BasicSecureHandler(), - new BasicCommentHandler(), - new RFC2965CommentUrlAttributeHandler(), - new RFC2965DiscardAttributeHandler()); - final RFC2109Spec obsoleteStrict = new RFC2109Spec(this.oneHeader, - new RFC2109VersionHandler(), - new BasicPathHandler(), - PublicSuffixDomainFilter.decorate( - new RFC2109DomainHandler(), this.publicSuffixMatcher), - new BasicMaxAgeHandler(), - new BasicSecureHandler(), - new BasicCommentHandler()); - final NetscapeDraftSpec netscapeDraft = new NetscapeDraftSpec( - PublicSuffixDomainFilter.decorate( - new BasicDomainHandler(), this.publicSuffixMatcher), - this.compatibilityLevel == CompatibilityLevel.IE_MEDIUM_SECURITY ? - new BasicPathHandler() { - @Override - public void validate( - final Cookie cookie, - final CookieOrigin origin) throws MalformedCookieException { - // No validation - } - } : new BasicPathHandler(), - new BasicSecureHandler(), - new BasicCommentHandler(), - new BasicExpiresHandler(this.datepatterns != null ? this.datepatterns.clone() : - new String[]{NetscapeDraftSpec.EXPIRES_PATTERN})); - this.cookieSpec = new DefaultCookieSpec(strict, obsoleteStrict, netscapeDraft); - } - } - } - return this.cookieSpec; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/IgnoreSpec.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/IgnoreSpec.java deleted file mode 100644 index 47e4fc27..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/IgnoreSpec.java +++ /dev/null @@ -1,68 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import java.util.Collections; -import java.util.List; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; - -import com.tracelytics.ext.apache.http.cookie.Cookie; -import com.tracelytics.ext.apache.http.cookie.CookieOrigin; -import com.tracelytics.ext.apache.http.cookie.MalformedCookieException; - -/** - * CookieSpec that ignores all cookies - * - * @since 4.1 - */ -@ThreadSafe -public class IgnoreSpec extends CookieSpecBase { - - @Override - public int getVersion() { - return 0; - } - - @Override - public List parse(final Header header, final CookieOrigin origin) - throws MalformedCookieException { - return Collections.emptyList(); - } - - @Override - public List
formatCookies(final List cookies) { - return Collections.emptyList(); - } - - @Override - public Header getVersionHeader() { - return null; - } -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/IgnoreSpecProvider.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/IgnoreSpecProvider.java deleted file mode 100644 index e89c2247..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/IgnoreSpecProvider.java +++ /dev/null @@ -1,62 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -import com.tracelytics.ext.apache.http.cookie.CookieSpec; -import com.tracelytics.ext.apache.http.cookie.CookieSpecProvider; - -/** - * {@link com.tracelytics.ext.apache.http.cookie.CookieSpecProvider} implementation that ignores all cookies. - * - * @since 4.4 - */ -@Immutable -public class IgnoreSpecProvider implements CookieSpecProvider { - - private volatile CookieSpec cookieSpec; - - public IgnoreSpecProvider() { - super(); - } - - @Override - public CookieSpec create(final HttpContext context) { - if (cookieSpec == null) { - synchronized (this) { - if (cookieSpec == null) { - this.cookieSpec = new IgnoreSpec(); - } - } - } - return this.cookieSpec; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/LaxExpiresHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/LaxExpiresHandler.java deleted file mode 100644 index 0b76e99e..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/LaxExpiresHandler.java +++ /dev/null @@ -1,221 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import java.util.BitSet; -import java.util.Calendar; -import java.util.Locale; -import java.util.Map; -import java.util.TimeZone; -import java.util.concurrent.ConcurrentHashMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.message.ParserCursor; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.cookie.ClientCookie; -import com.tracelytics.ext.apache.http.cookie.CommonCookieAttributeHandler; -import com.tracelytics.ext.apache.http.cookie.MalformedCookieException; -import com.tracelytics.ext.apache.http.cookie.SetCookie; - -/** - * - * @since 4.4 - */ -@Immutable -public class LaxExpiresHandler extends AbstractCookieAttributeHandler implements CommonCookieAttributeHandler { - - static final TimeZone UTC = TimeZone.getTimeZone("UTC"); - - private static final BitSet DELIMS; - static { - final BitSet bitSet = new BitSet(); - bitSet.set(0x9); - for (int b = 0x20; b <= 0x2f; b++) { - bitSet.set(b); - } - for (int b = 0x3b; b <= 0x40; b++) { - bitSet.set(b); - } - for (int b = 0x5b; b <= 0x60; b++) { - bitSet.set(b); - } - for (int b = 0x7b; b <= 0x7e; b++) { - bitSet.set(b); - } - DELIMS = bitSet; - } - private static final Map MONTHS; - static { - final ConcurrentHashMap map = new ConcurrentHashMap(12); - map.put("jan", Calendar.JANUARY); - map.put("feb", Calendar.FEBRUARY); - map.put("mar", Calendar.MARCH); - map.put("apr", Calendar.APRIL); - map.put("may", Calendar.MAY); - map.put("jun", Calendar.JUNE); - map.put("jul", Calendar.JULY); - map.put("aug", Calendar.AUGUST); - map.put("sep", Calendar.SEPTEMBER); - map.put("oct", Calendar.OCTOBER); - map.put("nov", Calendar.NOVEMBER); - map.put("dec", Calendar.DECEMBER); - MONTHS = map; - } - - private final static Pattern TIME_PATTERN = Pattern.compile( - "^([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})([^0-9].*)?$"); - private final static Pattern DAY_OF_MONTH_PATTERN = Pattern.compile( - "^([0-9]{1,2})([^0-9].*)?$"); - private final static Pattern MONTH_PATTERN = Pattern.compile( - "^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)(.*)?$", Pattern.CASE_INSENSITIVE); - private final static Pattern YEAR_PATTERN = Pattern.compile( - "^([0-9]{2,4})([^0-9].*)?$"); - - public LaxExpiresHandler() { - super(); - } - - @Override - public void parse(final SetCookie cookie, final String value) throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - final ParserCursor cursor = new ParserCursor(0, value.length()); - final StringBuilder content = new StringBuilder(); - - int second = 0, minute = 0, hour = 0, day = 0, month = 0, year = 0; - boolean foundTime = false, foundDayOfMonth = false, foundMonth = false, foundYear = false; - try { - while (!cursor.atEnd()) { - skipDelims(value, cursor); - content.setLength(0); - copyContent(value, cursor, content); - - if (content.length() == 0) { - break; - } - if (!foundTime) { - final Matcher matcher = TIME_PATTERN.matcher(content); - if (matcher.matches()) { - foundTime = true; - hour = Integer.parseInt(matcher.group(1)); - minute = Integer.parseInt(matcher.group(2)); - second =Integer.parseInt(matcher.group(3)); - continue; - } - } - if (!foundDayOfMonth) { - final Matcher matcher = DAY_OF_MONTH_PATTERN.matcher(content); - if (matcher.matches()) { - foundDayOfMonth = true; - day = Integer.parseInt(matcher.group(1)); - continue; - } - } - if (!foundMonth) { - final Matcher matcher = MONTH_PATTERN.matcher(content); - if (matcher.matches()) { - foundMonth = true; - month = MONTHS.get(matcher.group(1).toLowerCase(Locale.ROOT)); - continue; - } - } - if (!foundYear) { - final Matcher matcher = YEAR_PATTERN.matcher(content); - if (matcher.matches()) { - foundYear = true; - year = Integer.parseInt(matcher.group(1)); - continue; - } - } - } - } catch (NumberFormatException ignore) { - throw new MalformedCookieException("Invalid 'expires' attribute: " + value); - } - if (!foundTime || !foundDayOfMonth || !foundMonth || !foundYear) { - throw new MalformedCookieException("Invalid 'expires' attribute: " + value); - } - if (year >= 70 && year <= 99) { - year = 1900 + year; - } - if (year >= 0 && year <= 69) { - year = 2000 + year; - } - if (day < 1 || day > 31 || year < 1601 || hour > 23 || minute > 59 || second > 59) { - throw new MalformedCookieException("Invalid 'expires' attribute: " + value); - } - - final Calendar c = Calendar.getInstance(); - c.setTimeZone(UTC); - c.setTimeInMillis(0L); - c.set(Calendar.SECOND, second); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, day); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - cookie.setExpiryDate(c.getTime()); - } - - private void skipDelims(final CharSequence buf, final ParserCursor cursor) { - int pos = cursor.getPos(); - final int indexFrom = cursor.getPos(); - final int indexTo = cursor.getUpperBound(); - for (int i = indexFrom; i < indexTo; i++) { - final char current = buf.charAt(i); - if (DELIMS.get(current)) { - pos++; - } else { - break; - } - } - cursor.updatePos(pos); - } - - private void copyContent(final CharSequence buf, final ParserCursor cursor, final StringBuilder dst) { - int pos = cursor.getPos(); - final int indexFrom = cursor.getPos(); - final int indexTo = cursor.getUpperBound(); - for (int i = indexFrom; i < indexTo; i++) { - final char current = buf.charAt(i); - if (DELIMS.get(current)) { - break; - } else { - pos++; - dst.append(current); - } - } - cursor.updatePos(pos); - } - - @Override - public String getAttributeName() { - return ClientCookie.MAX_AGE_ATTR; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/LaxMaxAgeHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/LaxMaxAgeHandler.java deleted file mode 100644 index 2cd45f79..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/LaxMaxAgeHandler.java +++ /dev/null @@ -1,80 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import java.util.Date; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.TextUtils; - -import com.tracelytics.ext.apache.http.cookie.ClientCookie; -import com.tracelytics.ext.apache.http.cookie.CommonCookieAttributeHandler; -import com.tracelytics.ext.apache.http.cookie.MalformedCookieException; -import com.tracelytics.ext.apache.http.cookie.SetCookie; - -/** - * - * @since 4.4 - */ -@Immutable -public class LaxMaxAgeHandler extends AbstractCookieAttributeHandler implements CommonCookieAttributeHandler { - - private final static Pattern MAX_AGE_PATTERN = Pattern.compile("^\\-?[0-9]+$"); - - public LaxMaxAgeHandler() { - super(); - } - - @Override - public void parse(final SetCookie cookie, final String value) throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - if (TextUtils.isBlank(value)) { - return; - } - final Matcher matcher = MAX_AGE_PATTERN.matcher(value); - if (matcher.matches()) { - final int age; - try { - age = Integer.parseInt(value); - } catch (final NumberFormatException e) { - return; - } - final Date expiryDate = age >= 0 ? new Date(System.currentTimeMillis() + age * 1000L) : - new Date(Long.MIN_VALUE); - cookie.setExpiryDate(expiryDate); - } - } - - @Override - public String getAttributeName() { - return ClientCookie.MAX_AGE_ATTR; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/NetscapeDomainHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/NetscapeDomainHandler.java deleted file mode 100644 index 07f8ee8b..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/NetscapeDomainHandler.java +++ /dev/null @@ -1,126 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import java.util.Locale; -import java.util.StringTokenizer; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.TextUtils; - -import com.tracelytics.ext.apache.http.cookie.ClientCookie; -import com.tracelytics.ext.apache.http.cookie.Cookie; -import com.tracelytics.ext.apache.http.cookie.CookieOrigin; -import com.tracelytics.ext.apache.http.cookie.CookieRestrictionViolationException; -import com.tracelytics.ext.apache.http.cookie.MalformedCookieException; -import com.tracelytics.ext.apache.http.cookie.SetCookie; - -/** - * - * @since 4.0 - */ -@Immutable -public class NetscapeDomainHandler extends BasicDomainHandler { - - public NetscapeDomainHandler() { - super(); - } - - @Override - public void parse(final SetCookie cookie, final String value) throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - if (TextUtils.isBlank(value)) { - throw new MalformedCookieException("Blank or null value for domain attribute"); - } - cookie.setDomain(value); - } - - @Override - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - final String host = origin.getHost(); - final String domain = cookie.getDomain(); - if (!host.equals(domain) && !BasicDomainHandler.domainMatch(domain, host)) { - throw new CookieRestrictionViolationException( - "Illegal domain attribute \"" + domain + "\". Domain of origin: \"" + host + "\""); - } - if (host.contains(".")) { - final int domainParts = new StringTokenizer(domain, ".").countTokens(); - - if (isSpecialDomain(domain)) { - if (domainParts < 2) { - throw new CookieRestrictionViolationException("Domain attribute \"" - + domain - + "\" violates the Netscape cookie specification for " - + "special domains"); - } - } else { - if (domainParts < 3) { - throw new CookieRestrictionViolationException("Domain attribute \"" - + domain - + "\" violates the Netscape cookie specification"); - } - } - } - } - - /** - * Checks if the given domain is in one of the seven special - * top level domains defined by the Netscape cookie specification. - * @param domain The domain. - * @return True if the specified domain is "special" - */ - private static boolean isSpecialDomain(final String domain) { - final String ucDomain = domain.toUpperCase(Locale.ROOT); - return ucDomain.endsWith(".COM") - || ucDomain.endsWith(".EDU") - || ucDomain.endsWith(".NET") - || ucDomain.endsWith(".GOV") - || ucDomain.endsWith(".MIL") - || ucDomain.endsWith(".ORG") - || ucDomain.endsWith(".INT"); - } - - @Override - public boolean match(final Cookie cookie, final CookieOrigin origin) { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - final String host = origin.getHost(); - final String domain = cookie.getDomain(); - if (domain == null) { - return false; - } - return host.endsWith(domain); - } - - @Override - public String getAttributeName() { - return ClientCookie.DOMAIN_ATTR; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/NetscapeDraftHeaderParser.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/NetscapeDraftHeaderParser.java deleted file mode 100644 index bd8acdbf..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/NetscapeDraftHeaderParser.java +++ /dev/null @@ -1,102 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import java.util.ArrayList; -import java.util.BitSet; -import java.util.List; - -import com.tracelytics.ext.apache.http.HeaderElement; -import com.tracelytics.ext.apache.http.NameValuePair; -import com.tracelytics.ext.apache.http.ParseException; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.message.BasicHeaderElement; -import com.tracelytics.ext.apache.http.message.BasicNameValuePair; -import com.tracelytics.ext.apache.http.message.ParserCursor; -import com.tracelytics.ext.apache.http.message.TokenParser; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -/** - * - * @since 4.0 - */ -@Immutable -public class NetscapeDraftHeaderParser { - - public final static NetscapeDraftHeaderParser DEFAULT = new NetscapeDraftHeaderParser(); - - private final static char PARAM_DELIMITER = ';'; - - // IMPORTANT! - // These private static variables must be treated as immutable and never exposed outside this class - private static final BitSet TOKEN_DELIMS = TokenParser.INIT_BITSET('=', PARAM_DELIMITER); - private static final BitSet VALUE_DELIMS = TokenParser.INIT_BITSET(PARAM_DELIMITER); - - private final TokenParser tokenParser; - - public NetscapeDraftHeaderParser() { - super(); - this.tokenParser = TokenParser.INSTANCE; - } - - public HeaderElement parseHeader( - final CharArrayBuffer buffer, - final ParserCursor cursor) throws ParseException { - Args.notNull(buffer, "Char array buffer"); - Args.notNull(cursor, "Parser cursor"); - final NameValuePair nvp = parseNameValuePair(buffer, cursor); - final List params = new ArrayList(); - while (!cursor.atEnd()) { - final NameValuePair param = parseNameValuePair(buffer, cursor); - params.add(param); - } - return new BasicHeaderElement( - nvp.getName(), - nvp.getValue(), params.toArray(new NameValuePair[params.size()])); - } - - private NameValuePair parseNameValuePair( - final CharArrayBuffer buffer, final ParserCursor cursor) { - final String name = tokenParser.parseToken(buffer, cursor, TOKEN_DELIMS); - if (cursor.atEnd()) { - return new BasicNameValuePair(name, null); - } - final int delim = buffer.charAt(cursor.getPos()); - cursor.updatePos(cursor.getPos() + 1); - if (delim != '=') { - return new BasicNameValuePair(name, null); - } - final String value = tokenParser.parseToken(buffer, cursor, VALUE_DELIMS); - if (!cursor.atEnd()) { - cursor.updatePos(cursor.getPos() + 1); - } - return new BasicNameValuePair(name, value); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/NetscapeDraftSpec.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/NetscapeDraftSpec.java deleted file mode 100644 index 63c36478..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/NetscapeDraftSpec.java +++ /dev/null @@ -1,175 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import java.util.ArrayList; -import java.util.List; - -import com.tracelytics.ext.apache.http.FormattedHeader; -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HeaderElement; -import com.tracelytics.ext.apache.http.annotation.Obsolete; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.message.BufferedHeader; -import com.tracelytics.ext.apache.http.message.ParserCursor; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -import com.tracelytics.ext.apache.http.cookie.CommonCookieAttributeHandler; -import com.tracelytics.ext.apache.http.cookie.Cookie; -import com.tracelytics.ext.apache.http.cookie.CookieOrigin; -import com.tracelytics.ext.apache.http.cookie.MalformedCookieException; -import com.tracelytics.ext.apache.http.cookie.SM; - -/** - * This {@link com.tracelytics.ext.apache.http.cookie.CookieSpec} implementation conforms to - * the original draft specification published by Netscape Communications. - * It should be avoided unless absolutely necessary for compatibility with - * legacy applications. - *

- * Rendered obsolete by {@link com.tracelytics.ext.apache.http.impl.cookie.RFC6265LaxSpec}. - * - * @since 4.0 - * @see com.tracelytics.ext.apache.http.impl.cookie.RFC6265LaxSpec - */ -@Obsolete -@ThreadSafe -public class NetscapeDraftSpec extends CookieSpecBase { - - protected static final String EXPIRES_PATTERN = "EEE, dd-MMM-yy HH:mm:ss z"; - - /** Default constructor */ - public NetscapeDraftSpec(final String[] datepatterns) { - super(new BasicPathHandler(), - new NetscapeDomainHandler(), - new BasicSecureHandler(), - new BasicCommentHandler(), - new BasicExpiresHandler( - datepatterns != null ? datepatterns.clone() : new String[]{EXPIRES_PATTERN})); - } - - NetscapeDraftSpec(final CommonCookieAttributeHandler... handlers) { - super(handlers); - } - - public NetscapeDraftSpec() { - this((String[]) null); - } - - /** - * Parses the Set-Cookie value into an array of {@code Cookie}s. - * - *

Syntax of the Set-Cookie HTTP Response Header:

- * - *

This is the format a CGI script would use to add to - * the HTTP headers a new piece of data which is to be stored by - * the client for later retrieval.

- * - *
-      *  Set-Cookie: NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME; secure
-      * 
- * - *

Please note that the Netscape draft specification does not fully conform to the HTTP - * header format. Comma character if present in {@code Set-Cookie} will not be treated - * as a header element separator

- * - * @see - * The Cookie Spec. - * - * @param header the {@code Set-Cookie} received from the server - * @return an array of {@code Cookie}s parsed from the Set-Cookie value - * @throws MalformedCookieException if an exception occurs during parsing - */ - @Override - public List parse(final Header header, final CookieOrigin origin) - throws MalformedCookieException { - Args.notNull(header, "Header"); - Args.notNull(origin, "Cookie origin"); - if (!header.getName().equalsIgnoreCase(SM.SET_COOKIE)) { - throw new MalformedCookieException("Unrecognized cookie header '" - + header.toString() + "'"); - } - final NetscapeDraftHeaderParser parser = NetscapeDraftHeaderParser.DEFAULT; - final CharArrayBuffer buffer; - final ParserCursor cursor; - if (header instanceof FormattedHeader) { - buffer = ((FormattedHeader) header).getBuffer(); - cursor = new ParserCursor( - ((FormattedHeader) header).getValuePos(), - buffer.length()); - } else { - final String s = header.getValue(); - if (s == null) { - throw new MalformedCookieException("Header value is null"); - } - buffer = new CharArrayBuffer(s.length()); - buffer.append(s); - cursor = new ParserCursor(0, buffer.length()); - } - return parse(new HeaderElement[] { parser.parseHeader(buffer, cursor) }, origin); - } - - @Override - public List
formatCookies(final List cookies) { - Args.notEmpty(cookies, "List of cookies"); - final CharArrayBuffer buffer = new CharArrayBuffer(20 * cookies.size()); - buffer.append(SM.COOKIE); - buffer.append(": "); - for (int i = 0; i < cookies.size(); i++) { - final Cookie cookie = cookies.get(i); - if (i > 0) { - buffer.append("; "); - } - buffer.append(cookie.getName()); - final String s = cookie.getValue(); - if (s != null) { - buffer.append("="); - buffer.append(s); - } - } - final List
headers = new ArrayList
(1); - headers.add(new BufferedHeader(buffer)); - return headers; - } - - @Override - public int getVersion() { - return 0; - } - - @Override - public Header getVersionHeader() { - return null; - } - - @Override - public String toString() { - return "netscape"; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/NetscapeDraftSpecProvider.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/NetscapeDraftSpecProvider.java deleted file mode 100644 index 6748f7ea..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/NetscapeDraftSpecProvider.java +++ /dev/null @@ -1,76 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.annotation.Obsolete; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -import com.tracelytics.ext.apache.http.cookie.CookieSpec; -import com.tracelytics.ext.apache.http.cookie.CookieSpecProvider; - -/** - * {@link com.tracelytics.ext.apache.http.cookie.CookieSpecProvider} implementation that provides an instance of - * {@link NetscapeDraftSpec}. The instance returned by this factory - * can be shared by multiple threads. - *

- * Rendered obsolete by {@link com.tracelytics.ext.apache.http.impl.cookie.RFC6265CookieSpecProvider} - * - * @since 4.4 - * @see com.tracelytics.ext.apache.http.impl.cookie.RFC6265CookieSpecProvider - */ -@Obsolete -@Immutable -public class NetscapeDraftSpecProvider implements CookieSpecProvider { - - private final String[] datepatterns; - - private volatile CookieSpec cookieSpec; - - public NetscapeDraftSpecProvider(final String[] datepatterns) { - super(); - this.datepatterns = datepatterns; - } - - public NetscapeDraftSpecProvider() { - this(null); - } - - @Override - public CookieSpec create(final HttpContext context) { - if (cookieSpec == null) { - synchronized (this) { - if (cookieSpec == null) { - this.cookieSpec = new NetscapeDraftSpec(this.datepatterns); - } - } - } - return this.cookieSpec; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/PublicSuffixDomainFilter.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/PublicSuffixDomainFilter.java deleted file mode 100644 index 0d11b951..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/PublicSuffixDomainFilter.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 com.tracelytics.ext.apache.http.impl.cookie; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.conn.util.PublicSuffixList; -import com.tracelytics.ext.apache.http.conn.util.PublicSuffixMatcher; -import com.tracelytics.ext.apache.http.cookie.CommonCookieAttributeHandler; -import com.tracelytics.ext.apache.http.cookie.Cookie; -import com.tracelytics.ext.apache.http.cookie.CookieOrigin; -import com.tracelytics.ext.apache.http.cookie.MalformedCookieException; -import com.tracelytics.ext.apache.http.cookie.SetCookie; - -/** - * Wraps a {@link com.tracelytics.ext.apache.http.cookie.CookieAttributeHandler} and leverages its match method - * to never match a suffix from a black list. May be used to provide additional security for - * cross-site attack types by preventing cookies from apparent domains that are not publicly - * available. - * - * @see com.tracelytics.ext.apache.http.conn.util.PublicSuffixList - * @see com.tracelytics.ext.apache.http.conn.util.PublicSuffixMatcher - * - * @since 4.4 - */ -@Immutable // dependencies are expected to be immutable or thread-safe -public class PublicSuffixDomainFilter implements CommonCookieAttributeHandler { - - private final CommonCookieAttributeHandler handler; - private final PublicSuffixMatcher publicSuffixMatcher; - - public PublicSuffixDomainFilter( - final CommonCookieAttributeHandler handler, final PublicSuffixMatcher publicSuffixMatcher) { - this.handler = Args.notNull(handler, "Cookie handler"); - this.publicSuffixMatcher = Args.notNull(publicSuffixMatcher, "Public suffix matcher"); - } - - public PublicSuffixDomainFilter( - final CommonCookieAttributeHandler handler, final PublicSuffixList suffixList) { - Args.notNull(handler, "Cookie handler"); - Args.notNull(suffixList, "Public suffix list"); - this.handler = handler; - this.publicSuffixMatcher = new PublicSuffixMatcher(suffixList.getRules(), suffixList.getExceptions()); - } - - /** - * Never matches if the cookie's domain is from the blacklist. - */ - @Override - public boolean match(final Cookie cookie, final CookieOrigin origin) { - final String domain = cookie.getDomain(); - if (!domain.equalsIgnoreCase("localhost") && publicSuffixMatcher.matches(domain)) { - return false; - } else { - return handler.match(cookie, origin); - } - } - - @Override - public void parse(final SetCookie cookie, final String value) throws MalformedCookieException { - handler.parse(cookie, value); - } - - @Override - public void validate(final Cookie cookie, final CookieOrigin origin) throws MalformedCookieException { - handler.validate(cookie, origin); - } - - @Override - public String getAttributeName() { - return handler.getAttributeName(); - } - - public static CommonCookieAttributeHandler decorate( - final CommonCookieAttributeHandler handler, final PublicSuffixMatcher publicSuffixMatcher) { - Args.notNull(handler, "Cookie attribute handler"); - return publicSuffixMatcher != null ? new PublicSuffixDomainFilter(handler, publicSuffixMatcher) : handler; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2109DomainHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2109DomainHandler.java deleted file mode 100644 index 6677e786..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2109DomainHandler.java +++ /dev/null @@ -1,130 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import java.util.Locale; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.cookie.ClientCookie; -import com.tracelytics.ext.apache.http.cookie.CommonCookieAttributeHandler; -import com.tracelytics.ext.apache.http.cookie.Cookie; -import com.tracelytics.ext.apache.http.cookie.CookieOrigin; -import com.tracelytics.ext.apache.http.cookie.CookieRestrictionViolationException; -import com.tracelytics.ext.apache.http.cookie.MalformedCookieException; -import com.tracelytics.ext.apache.http.cookie.SetCookie; - -/** - * - * @since 4.0 - */ -@Immutable -public class RFC2109DomainHandler implements CommonCookieAttributeHandler { - - public RFC2109DomainHandler() { - super(); - } - - @Override - public void parse(final SetCookie cookie, final String value) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - if (value == null) { - throw new MalformedCookieException("Missing value for domain attribute"); - } - if (value.trim().isEmpty()) { - throw new MalformedCookieException("Blank value for domain attribute"); - } - cookie.setDomain(value); - } - - @Override - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - String host = origin.getHost(); - final String domain = cookie.getDomain(); - if (domain == null) { - throw new CookieRestrictionViolationException("Cookie domain may not be null"); - } - if (!domain.equals(host)) { - int dotIndex = domain.indexOf('.'); - if (dotIndex == -1) { - throw new CookieRestrictionViolationException("Domain attribute \"" - + domain - + "\" does not match the host \"" - + host + "\""); - } - // domain must start with dot - if (!domain.startsWith(".")) { - throw new CookieRestrictionViolationException("Domain attribute \"" - + domain - + "\" violates RFC 2109: domain must start with a dot"); - } - // domain must have at least one embedded dot - dotIndex = domain.indexOf('.', 1); - if (dotIndex < 0 || dotIndex == domain.length() - 1) { - throw new CookieRestrictionViolationException("Domain attribute \"" - + domain - + "\" violates RFC 2109: domain must contain an embedded dot"); - } - host = host.toLowerCase(Locale.ROOT); - if (!host.endsWith(domain)) { - throw new CookieRestrictionViolationException( - "Illegal domain attribute \"" + domain - + "\". Domain of origin: \"" + host + "\""); - } - // host minus domain may not contain any dots - final String hostWithoutDomain = host.substring(0, host.length() - domain.length()); - if (hostWithoutDomain.indexOf('.') != -1) { - throw new CookieRestrictionViolationException("Domain attribute \"" - + domain - + "\" violates RFC 2109: host minus domain may not contain any dots"); - } - } - } - - @Override - public boolean match(final Cookie cookie, final CookieOrigin origin) { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - final String host = origin.getHost(); - final String domain = cookie.getDomain(); - if (domain == null) { - return false; - } - return host.equals(domain) || (domain.startsWith(".") && host.endsWith(domain)); - } - - @Override - public String getAttributeName() { - return ClientCookie.DOMAIN_ATTR; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2109Spec.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2109Spec.java deleted file mode 100644 index 811e535f..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2109Spec.java +++ /dev/null @@ -1,244 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HeaderElement; -import com.tracelytics.ext.apache.http.annotation.Obsolete; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.message.BufferedHeader; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -import com.tracelytics.ext.apache.http.client.utils.DateUtils; -import com.tracelytics.ext.apache.http.cookie.ClientCookie; -import com.tracelytics.ext.apache.http.cookie.CommonCookieAttributeHandler; -import com.tracelytics.ext.apache.http.cookie.Cookie; -import com.tracelytics.ext.apache.http.cookie.CookieOrigin; -import com.tracelytics.ext.apache.http.cookie.CookiePathComparator; -import com.tracelytics.ext.apache.http.cookie.CookieRestrictionViolationException; -import com.tracelytics.ext.apache.http.cookie.MalformedCookieException; -import com.tracelytics.ext.apache.http.cookie.SM; - -/** - * RFC 2109 compliant {@link com.tracelytics.ext.apache.http.cookie.CookieSpec} implementation. - *

- * Rendered obsolete by {@link com.tracelytics.ext.apache.http.impl.cookie.RFC6265StrictSpec}. - * - * @since 4.0 - * @see com.tracelytics.ext.apache.http.impl.cookie.RFC6265StrictSpec - */ -@Obsolete -@ThreadSafe -public class RFC2109Spec extends CookieSpecBase { - - final static String[] DATE_PATTERNS = { - DateUtils.PATTERN_RFC1123, - DateUtils.PATTERN_RFC1036, - DateUtils.PATTERN_ASCTIME - }; - - private final boolean oneHeader; - - /** Default constructor */ - public RFC2109Spec(final String[] datepatterns, final boolean oneHeader) { - super(new RFC2109VersionHandler(), - new BasicPathHandler(), - new RFC2109DomainHandler(), - new BasicMaxAgeHandler(), - new BasicSecureHandler(), - new BasicCommentHandler(), - new BasicExpiresHandler( - datepatterns != null ? datepatterns.clone() : DATE_PATTERNS)); - this.oneHeader = oneHeader; - } - - /** Default constructor */ - public RFC2109Spec() { - this(null, false); - } - - protected RFC2109Spec(final boolean oneHeader, - final CommonCookieAttributeHandler... handlers) { - super(handlers); - this.oneHeader = oneHeader; - } - - @Override - public List parse(final Header header, final CookieOrigin origin) - throws MalformedCookieException { - Args.notNull(header, "Header"); - Args.notNull(origin, "Cookie origin"); - if (!header.getName().equalsIgnoreCase(SM.SET_COOKIE)) { - throw new MalformedCookieException("Unrecognized cookie header '" - + header.toString() + "'"); - } - final HeaderElement[] elems = header.getElements(); - return parse(elems, origin); - } - - @Override - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - final String name = cookie.getName(); - if (name.indexOf(' ') != -1) { - throw new CookieRestrictionViolationException("Cookie name may not contain blanks"); - } - if (name.startsWith("$")) { - throw new CookieRestrictionViolationException("Cookie name may not start with $"); - } - super.validate(cookie, origin); - } - - @Override - public List

formatCookies(final List cookies) { - Args.notEmpty(cookies, "List of cookies"); - List cookieList; - if (cookies.size() > 1) { - // Create a mutable copy and sort the copy. - cookieList = new ArrayList(cookies); - Collections.sort(cookieList, CookiePathComparator.INSTANCE); - } else { - cookieList = cookies; - } - if (this.oneHeader) { - return doFormatOneHeader(cookieList); - } else { - return doFormatManyHeaders(cookieList); - } - } - - private List
doFormatOneHeader(final List cookies) { - int version = Integer.MAX_VALUE; - // Pick the lowest common denominator - for (final Cookie cookie : cookies) { - if (cookie.getVersion() < version) { - version = cookie.getVersion(); - } - } - final CharArrayBuffer buffer = new CharArrayBuffer(40 * cookies.size()); - buffer.append(SM.COOKIE); - buffer.append(": "); - buffer.append("$Version="); - buffer.append(Integer.toString(version)); - for (final Cookie cooky : cookies) { - buffer.append("; "); - final Cookie cookie = cooky; - formatCookieAsVer(buffer, cookie, version); - } - final List
headers = new ArrayList
(1); - headers.add(new BufferedHeader(buffer)); - return headers; - } - - private List
doFormatManyHeaders(final List cookies) { - final List
headers = new ArrayList
(cookies.size()); - for (final Cookie cookie : cookies) { - final int version = cookie.getVersion(); - final CharArrayBuffer buffer = new CharArrayBuffer(40); - buffer.append("Cookie: "); - buffer.append("$Version="); - buffer.append(Integer.toString(version)); - buffer.append("; "); - formatCookieAsVer(buffer, cookie, version); - headers.add(new BufferedHeader(buffer)); - } - return headers; - } - - /** - * Return a name/value string suitable for sending in a {@code "Cookie"} - * header as defined in RFC 2109 for backward compatibility with cookie - * version 0 - * @param buffer The char array buffer to use for output - * @param name The cookie name - * @param value The cookie value - * @param version The cookie version - */ - protected void formatParamAsVer(final CharArrayBuffer buffer, - final String name, final String value, final int version) { - buffer.append(name); - buffer.append("="); - if (value != null) { - if (version > 0) { - buffer.append('\"'); - buffer.append(value); - buffer.append('\"'); - } else { - buffer.append(value); - } - } - } - - /** - * Return a string suitable for sending in a {@code "Cookie"} header - * as defined in RFC 2109 for backward compatibility with cookie version 0 - * @param buffer The char array buffer to use for output - * @param cookie The {@link Cookie} to be formatted as string - * @param version The version to use. - */ - protected void formatCookieAsVer(final CharArrayBuffer buffer, - final Cookie cookie, final int version) { - formatParamAsVer(buffer, cookie.getName(), cookie.getValue(), version); - if (cookie.getPath() != null) { - if (cookie instanceof ClientCookie - && ((ClientCookie) cookie).containsAttribute(ClientCookie.PATH_ATTR)) { - buffer.append("; "); - formatParamAsVer(buffer, "$Path", cookie.getPath(), version); - } - } - if (cookie.getDomain() != null) { - if (cookie instanceof ClientCookie - && ((ClientCookie) cookie).containsAttribute(ClientCookie.DOMAIN_ATTR)) { - buffer.append("; "); - formatParamAsVer(buffer, "$Domain", cookie.getDomain(), version); - } - } - } - - @Override - public int getVersion() { - return 1; - } - - @Override - public Header getVersionHeader() { - return null; - } - - @Override - public String toString() { - return "rfc2109"; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2109SpecProvider.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2109SpecProvider.java deleted file mode 100644 index bcba73bf..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2109SpecProvider.java +++ /dev/null @@ -1,90 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.annotation.Obsolete; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -import com.tracelytics.ext.apache.http.conn.util.PublicSuffixMatcher; -import com.tracelytics.ext.apache.http.cookie.CookieSpec; -import com.tracelytics.ext.apache.http.cookie.CookieSpecProvider; - -/** - * {@link com.tracelytics.ext.apache.http.cookie.CookieSpecProvider} implementation that provides an instance of - * {@link RFC2109Spec}. The instance returned by this factory - * can be shared by multiple threads. - *

- * Rendered obsolete by {@link com.tracelytics.ext.apache.http.impl.cookie.RFC6265CookieSpecProvider} - * - * @since 4.4 - * @see com.tracelytics.ext.apache.http.impl.cookie.RFC6265CookieSpecProvider - */ -@Obsolete -@Immutable -public class RFC2109SpecProvider implements CookieSpecProvider { - - private final PublicSuffixMatcher publicSuffixMatcher; - private final boolean oneHeader; - - private volatile CookieSpec cookieSpec; - - public RFC2109SpecProvider(final PublicSuffixMatcher publicSuffixMatcher, final boolean oneHeader) { - super(); - this.oneHeader = oneHeader; - this.publicSuffixMatcher = publicSuffixMatcher; - } - - public RFC2109SpecProvider(final PublicSuffixMatcher publicSuffixMatcher) { - this(publicSuffixMatcher, false); - } - - public RFC2109SpecProvider() { - this(null, false); - } - - @Override - public CookieSpec create(final HttpContext context) { - if (cookieSpec == null) { - synchronized (this) { - if (cookieSpec == null) { - this.cookieSpec = new RFC2109Spec(this.oneHeader, - new RFC2109VersionHandler(), - new BasicPathHandler(), - PublicSuffixDomainFilter.decorate( - new RFC2109DomainHandler(), this.publicSuffixMatcher), - new BasicMaxAgeHandler(), - new BasicSecureHandler(), - new BasicCommentHandler()); - } - } - } - return this.cookieSpec; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2109VersionHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2109VersionHandler.java deleted file mode 100644 index 079991ab..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2109VersionHandler.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 com.tracelytics.ext.apache.http.impl.cookie; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.cookie.ClientCookie; -import com.tracelytics.ext.apache.http.cookie.CommonCookieAttributeHandler; -import com.tracelytics.ext.apache.http.cookie.Cookie; -import com.tracelytics.ext.apache.http.cookie.CookieOrigin; -import com.tracelytics.ext.apache.http.cookie.CookieRestrictionViolationException; -import com.tracelytics.ext.apache.http.cookie.MalformedCookieException; -import com.tracelytics.ext.apache.http.cookie.SetCookie; - -/** - * - * @since 4.0 - */ -@Immutable -public class RFC2109VersionHandler extends AbstractCookieAttributeHandler implements CommonCookieAttributeHandler { - - public RFC2109VersionHandler() { - super(); - } - - @Override - public void parse(final SetCookie cookie, final String value) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - if (value == null) { - throw new MalformedCookieException("Missing value for version attribute"); - } - if (value.trim().isEmpty()) { - throw new MalformedCookieException("Blank value for version attribute"); - } - try { - cookie.setVersion(Integer.parseInt(value)); - } catch (final NumberFormatException e) { - throw new MalformedCookieException("Invalid version: " - + e.getMessage()); - } - } - - @Override - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - if (cookie.getVersion() < 0) { - throw new CookieRestrictionViolationException("Cookie version may not be negative"); - } - } - - @Override - public String getAttributeName() { - return ClientCookie.VERSION_ATTR; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2965CommentUrlAttributeHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2965CommentUrlAttributeHandler.java deleted file mode 100644 index 2689ca02..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2965CommentUrlAttributeHandler.java +++ /dev/null @@ -1,76 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import com.tracelytics.ext.apache.http.annotation.Immutable; - -import com.tracelytics.ext.apache.http.cookie.ClientCookie; -import com.tracelytics.ext.apache.http.cookie.CommonCookieAttributeHandler; -import com.tracelytics.ext.apache.http.cookie.Cookie; -import com.tracelytics.ext.apache.http.cookie.CookieOrigin; -import com.tracelytics.ext.apache.http.cookie.MalformedCookieException; -import com.tracelytics.ext.apache.http.cookie.SetCookie; -import com.tracelytics.ext.apache.http.cookie.SetCookie2; - -/** - * {@code "CommentURL"} cookie attribute handler for RFC 2965 cookie spec. - * - * @since 4.0 - */ -@Immutable -public class RFC2965CommentUrlAttributeHandler implements CommonCookieAttributeHandler { - - public RFC2965CommentUrlAttributeHandler() { - super(); - } - - @Override - public void parse(final SetCookie cookie, final String commenturl) - throws MalformedCookieException { - if (cookie instanceof SetCookie2) { - final SetCookie2 cookie2 = (SetCookie2) cookie; - cookie2.setCommentURL(commenturl); - } - } - - @Override - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - } - - @Override - public boolean match(final Cookie cookie, final CookieOrigin origin) { - return true; - } - - @Override - public String getAttributeName() { - return ClientCookie.COMMENTURL_ATTR; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2965DiscardAttributeHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2965DiscardAttributeHandler.java deleted file mode 100644 index 2a35dc87..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2965DiscardAttributeHandler.java +++ /dev/null @@ -1,76 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import com.tracelytics.ext.apache.http.annotation.Immutable; - -import com.tracelytics.ext.apache.http.cookie.ClientCookie; -import com.tracelytics.ext.apache.http.cookie.CommonCookieAttributeHandler; -import com.tracelytics.ext.apache.http.cookie.Cookie; -import com.tracelytics.ext.apache.http.cookie.CookieOrigin; -import com.tracelytics.ext.apache.http.cookie.MalformedCookieException; -import com.tracelytics.ext.apache.http.cookie.SetCookie; -import com.tracelytics.ext.apache.http.cookie.SetCookie2; - -/** - * {@code "Discard"} cookie attribute handler for RFC 2965 cookie spec. - * - * @since 4.0 - */ -@Immutable -public class RFC2965DiscardAttributeHandler implements CommonCookieAttributeHandler { - - public RFC2965DiscardAttributeHandler() { - super(); - } - - @Override - public void parse(final SetCookie cookie, final String commenturl) - throws MalformedCookieException { - if (cookie instanceof SetCookie2) { - final SetCookie2 cookie2 = (SetCookie2) cookie; - cookie2.setDiscard(true); - } - } - - @Override - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - } - - @Override - public boolean match(final Cookie cookie, final CookieOrigin origin) { - return true; - } - - @Override - public String getAttributeName() { - return ClientCookie.DISCARD_ATTR; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2965DomainAttributeHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2965DomainAttributeHandler.java deleted file mode 100644 index 38808fe9..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2965DomainAttributeHandler.java +++ /dev/null @@ -1,195 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import java.util.Locale; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.cookie.ClientCookie; -import com.tracelytics.ext.apache.http.cookie.CommonCookieAttributeHandler; -import com.tracelytics.ext.apache.http.cookie.Cookie; -import com.tracelytics.ext.apache.http.cookie.CookieOrigin; -import com.tracelytics.ext.apache.http.cookie.CookieRestrictionViolationException; -import com.tracelytics.ext.apache.http.cookie.MalformedCookieException; -import com.tracelytics.ext.apache.http.cookie.SetCookie; - -/** - * {@code "Domain"} cookie attribute handler for RFC 2965 cookie spec. - * - * - * @since 3.1 - */ -@Immutable -public class RFC2965DomainAttributeHandler implements CommonCookieAttributeHandler { - - public RFC2965DomainAttributeHandler() { - super(); - } - - /** - * Parse cookie domain attribute. - */ - @Override - public void parse( - final SetCookie cookie, final String domain) throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - if (domain == null) { - throw new MalformedCookieException( - "Missing value for domain attribute"); - } - if (domain.trim().isEmpty()) { - throw new MalformedCookieException( - "Blank value for domain attribute"); - } - String s = domain; - s = s.toLowerCase(Locale.ROOT); - if (!domain.startsWith(".")) { - // Per RFC 2965 section 3.2.2 - // "... If an explicitly specified value does not start with - // a dot, the user agent supplies a leading dot ..." - // That effectively implies that the domain attribute - // MAY NOT be an IP address of a host name - s = '.' + s; - } - cookie.setDomain(s); - } - - /** - * Performs domain-match as defined by the RFC2965. - *

- * Host A's name domain-matches host B's if - *

- *
    - *
  1. their host name strings string-compare equal; or
  2. - *
  3. A is a HDN string and has the form NB, where N is a non-empty - * name string, B has the form .B', and B' is a HDN string. (So, - * x.y.com domain-matches .Y.com but not Y.com.)
  4. - *
- * - * @param host host name where cookie is received from or being sent to. - * @param domain The cookie domain attribute. - * @return true if the specified host matches the given domain. - */ - public boolean domainMatch(final String host, final String domain) { - final boolean match = host.equals(domain) - || (domain.startsWith(".") && host.endsWith(domain)); - - return match; - } - - /** - * Validate cookie domain attribute. - */ - @Override - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - final String host = origin.getHost().toLowerCase(Locale.ROOT); - if (cookie.getDomain() == null) { - throw new CookieRestrictionViolationException("Invalid cookie state: " + - "domain not specified"); - } - final String cookieDomain = cookie.getDomain().toLowerCase(Locale.ROOT); - - if (cookie instanceof ClientCookie - && ((ClientCookie) cookie).containsAttribute(ClientCookie.DOMAIN_ATTR)) { - // Domain attribute must start with a dot - if (!cookieDomain.startsWith(".")) { - throw new CookieRestrictionViolationException("Domain attribute \"" + - cookie.getDomain() + "\" violates RFC 2109: domain must start with a dot"); - } - - // Domain attribute must contain at least one embedded dot, - // or the value must be equal to .local. - final int dotIndex = cookieDomain.indexOf('.', 1); - if (((dotIndex < 0) || (dotIndex == cookieDomain.length() - 1)) - && (!cookieDomain.equals(".local"))) { - throw new CookieRestrictionViolationException( - "Domain attribute \"" + cookie.getDomain() - + "\" violates RFC 2965: the value contains no embedded dots " - + "and the value is not .local"); - } - - // The effective host name must domain-match domain attribute. - if (!domainMatch(host, cookieDomain)) { - throw new CookieRestrictionViolationException( - "Domain attribute \"" + cookie.getDomain() - + "\" violates RFC 2965: effective host name does not " - + "domain-match domain attribute."); - } - - // effective host name minus domain must not contain any dots - final String effectiveHostWithoutDomain = host.substring( - 0, host.length() - cookieDomain.length()); - if (effectiveHostWithoutDomain.indexOf('.') != -1) { - throw new CookieRestrictionViolationException("Domain attribute \"" - + cookie.getDomain() + "\" violates RFC 2965: " - + "effective host minus domain may not contain any dots"); - } - } else { - // Domain was not specified in header. In this case, domain must - // string match request host (case-insensitive). - if (!cookie.getDomain().equals(host)) { - throw new CookieRestrictionViolationException("Illegal domain attribute: \"" - + cookie.getDomain() + "\"." - + "Domain of origin: \"" - + host + "\""); - } - } - } - - /** - * Match cookie domain attribute. - */ - @Override - public boolean match(final Cookie cookie, final CookieOrigin origin) { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - final String host = origin.getHost().toLowerCase(Locale.ROOT); - final String cookieDomain = cookie.getDomain(); - - // The effective host name MUST domain-match the Domain - // attribute of the cookie. - if (!domainMatch(host, cookieDomain)) { - return false; - } - // effective host name minus domain must not contain any dots - final String effectiveHostWithoutDomain = host.substring( - 0, host.length() - cookieDomain.length()); - return effectiveHostWithoutDomain.indexOf('.') == -1; - } - - @Override - public String getAttributeName() { - return ClientCookie.DOMAIN_ATTR; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2965PortAttributeHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2965PortAttributeHandler.java deleted file mode 100644 index 645b71cf..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2965PortAttributeHandler.java +++ /dev/null @@ -1,169 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import java.util.StringTokenizer; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.cookie.ClientCookie; -import com.tracelytics.ext.apache.http.cookie.CommonCookieAttributeHandler; -import com.tracelytics.ext.apache.http.cookie.Cookie; -import com.tracelytics.ext.apache.http.cookie.CookieOrigin; -import com.tracelytics.ext.apache.http.cookie.CookieRestrictionViolationException; -import com.tracelytics.ext.apache.http.cookie.MalformedCookieException; -import com.tracelytics.ext.apache.http.cookie.SetCookie; -import com.tracelytics.ext.apache.http.cookie.SetCookie2; - -/** - * {@code "Port"} cookie attribute handler for RFC 2965 cookie spec. - * - * @since 4.0 - */ -@Immutable -public class RFC2965PortAttributeHandler implements CommonCookieAttributeHandler { - - public RFC2965PortAttributeHandler() { - super(); - } - - /** - * Parses the given Port attribute value (e.g. "8000,8001,8002") - * into an array of ports. - * - * @param portValue port attribute value - * @return parsed array of ports - * @throws MalformedCookieException if there is a problem in - * parsing due to invalid portValue. - */ - private static int[] parsePortAttribute(final String portValue) - throws MalformedCookieException { - final StringTokenizer st = new StringTokenizer(portValue, ","); - final int[] ports = new int[st.countTokens()]; - try { - int i = 0; - while(st.hasMoreTokens()) { - ports[i] = Integer.parseInt(st.nextToken().trim()); - if (ports[i] < 0) { - throw new MalformedCookieException ("Invalid Port attribute."); - } - ++i; - } - } catch (final NumberFormatException e) { - throw new MalformedCookieException ("Invalid Port " - + "attribute: " + e.getMessage()); - } - return ports; - } - - /** - * Returns {@code true} if the given port exists in the given - * ports list. - * - * @param port port of host where cookie was received from or being sent to. - * @param ports port list - * @return true returns {@code true} if the given port exists in - * the given ports list; {@code false} otherwise. - */ - private static boolean portMatch(final int port, final int[] ports) { - boolean portInList = false; - for (final int port2 : ports) { - if (port == port2) { - portInList = true; - break; - } - } - return portInList; - } - - /** - * Parse cookie port attribute. - */ - @Override - public void parse(final SetCookie cookie, final String portValue) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - if (cookie instanceof SetCookie2) { - final SetCookie2 cookie2 = (SetCookie2) cookie; - if (portValue != null && !portValue.trim().isEmpty()) { - final int[] ports = parsePortAttribute(portValue); - cookie2.setPorts(ports); - } - } - } - - /** - * Validate cookie port attribute. If the Port attribute was specified - * in header, the request port must be in cookie's port list. - */ - @Override - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - final int port = origin.getPort(); - if (cookie instanceof ClientCookie - && ((ClientCookie) cookie).containsAttribute(ClientCookie.PORT_ATTR)) { - if (!portMatch(port, cookie.getPorts())) { - throw new CookieRestrictionViolationException( - "Port attribute violates RFC 2965: " - + "Request port not found in cookie's port list."); - } - } - } - - /** - * Match cookie port attribute. If the Port attribute is not specified - * in header, the cookie can be sent to any port. Otherwise, the request port - * must be in the cookie's port list. - */ - @Override - public boolean match(final Cookie cookie, final CookieOrigin origin) { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - final int port = origin.getPort(); - if (cookie instanceof ClientCookie - && ((ClientCookie) cookie).containsAttribute(ClientCookie.PORT_ATTR)) { - if (cookie.getPorts() == null) { - // Invalid cookie state: port not specified - return false; - } - if (!portMatch(port, cookie.getPorts())) { - return false; - } - } - return true; - } - - @Override - public String getAttributeName() { - return ClientCookie.PORT_ATTR; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2965Spec.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2965Spec.java deleted file mode 100644 index f53c7e4b..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2965Spec.java +++ /dev/null @@ -1,257 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HeaderElement; -import com.tracelytics.ext.apache.http.NameValuePair; -import com.tracelytics.ext.apache.http.annotation.Obsolete; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.message.BufferedHeader; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -import com.tracelytics.ext.apache.http.cookie.ClientCookie; -import com.tracelytics.ext.apache.http.cookie.CommonCookieAttributeHandler; -import com.tracelytics.ext.apache.http.cookie.Cookie; -import com.tracelytics.ext.apache.http.cookie.CookieAttributeHandler; -import com.tracelytics.ext.apache.http.cookie.CookieOrigin; -import com.tracelytics.ext.apache.http.cookie.MalformedCookieException; -import com.tracelytics.ext.apache.http.cookie.SM; - -/** - * RFC 2965 compliant {@link com.tracelytics.ext.apache.http.cookie.CookieSpec} implementation. - *

- * Rendered obsolete by {@link com.tracelytics.ext.apache.http.impl.cookie.RFC6265StrictSpec}. - * - * @since 4.0 - * @see com.tracelytics.ext.apache.http.impl.cookie.RFC6265StrictSpec - */ -@Obsolete -@ThreadSafe -public class RFC2965Spec extends RFC2109Spec { - - /** - * Default constructor - * - */ - public RFC2965Spec() { - this(null, false); - } - - public RFC2965Spec(final String[] datepatterns, final boolean oneHeader) { - super(oneHeader, - new RFC2965VersionAttributeHandler(), - new BasicPathHandler(), - new RFC2965DomainAttributeHandler(), - new RFC2965PortAttributeHandler(), - new BasicMaxAgeHandler(), - new BasicSecureHandler(), - new BasicCommentHandler(), - new BasicExpiresHandler( - datepatterns != null ? datepatterns.clone() : DATE_PATTERNS), - new RFC2965CommentUrlAttributeHandler(), - new RFC2965DiscardAttributeHandler()); - } - - RFC2965Spec(final boolean oneHeader, - final CommonCookieAttributeHandler... handlers) { - super(oneHeader, handlers); - } - - @Override - public List parse( - final Header header, - final CookieOrigin origin) throws MalformedCookieException { - Args.notNull(header, "Header"); - Args.notNull(origin, "Cookie origin"); - if (!header.getName().equalsIgnoreCase(SM.SET_COOKIE2)) { - throw new MalformedCookieException("Unrecognized cookie header '" - + header.toString() + "'"); - } - final HeaderElement[] elems = header.getElements(); - return createCookies(elems, adjustEffectiveHost(origin)); - } - - @Override - protected List parse( - final HeaderElement[] elems, - final CookieOrigin origin) throws MalformedCookieException { - return createCookies(elems, adjustEffectiveHost(origin)); - } - - private List createCookies( - final HeaderElement[] elems, - final CookieOrigin origin) throws MalformedCookieException { - final List cookies = new ArrayList(elems.length); - for (final HeaderElement headerelement : elems) { - final String name = headerelement.getName(); - final String value = headerelement.getValue(); - if (name == null || name.isEmpty()) { - throw new MalformedCookieException("Cookie name may not be empty"); - } - - final BasicClientCookie2 cookie = new BasicClientCookie2(name, value); - cookie.setPath(getDefaultPath(origin)); - cookie.setDomain(getDefaultDomain(origin)); - cookie.setPorts(new int [] { origin.getPort() }); - // cycle through the parameters - final NameValuePair[] attribs = headerelement.getParameters(); - - // Eliminate duplicate attributes. The first occurrence takes precedence - // See RFC2965: 3.2 Origin Server Role - final Map attribmap = - new HashMap(attribs.length); - for (int j = attribs.length - 1; j >= 0; j--) { - final NameValuePair param = attribs[j]; - attribmap.put(param.getName().toLowerCase(Locale.ROOT), param); - } - for (final Map.Entry entry : attribmap.entrySet()) { - final NameValuePair attrib = entry.getValue(); - final String s = attrib.getName().toLowerCase(Locale.ROOT); - - cookie.setAttribute(s, attrib.getValue()); - - final CookieAttributeHandler handler = findAttribHandler(s); - if (handler != null) { - handler.parse(cookie, attrib.getValue()); - } - } - cookies.add(cookie); - } - return cookies; - } - - @Override - public void validate( - final Cookie cookie, final CookieOrigin origin) throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - super.validate(cookie, adjustEffectiveHost(origin)); - } - - @Override - public boolean match(final Cookie cookie, final CookieOrigin origin) { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - return super.match(cookie, adjustEffectiveHost(origin)); - } - - /** - * Adds valid Port attribute value, e.g. "8000,8001,8002" - */ - @Override - protected void formatCookieAsVer(final CharArrayBuffer buffer, - final Cookie cookie, final int version) { - super.formatCookieAsVer(buffer, cookie, version); - // format port attribute - if (cookie instanceof ClientCookie) { - // Test if the port attribute as set by the origin server is not blank - final String s = ((ClientCookie) cookie).getAttribute(ClientCookie.PORT_ATTR); - if (s != null) { - buffer.append("; $Port"); - buffer.append("=\""); - if (!s.trim().isEmpty()) { - final int[] ports = cookie.getPorts(); - if (ports != null) { - final int len = ports.length; - for (int i = 0; i < len; i++) { - if (i > 0) { - buffer.append(","); - } - buffer.append(Integer.toString(ports[i])); - } - } - } - buffer.append("\""); - } - } - } - - /** - * Set 'effective host name' as defined in RFC 2965. - *

- * If a host name contains no dots, the effective host name is - * that name with the string .local appended to it. Otherwise - * the effective host name is the same as the host name. Note - * that all effective host names contain at least one dot. - * - * @param origin origin where cookie is received from or being sent to. - */ - private static CookieOrigin adjustEffectiveHost(final CookieOrigin origin) { - String host = origin.getHost(); - - // Test if the host name appears to be a fully qualified DNS name, - // IPv4 address or IPv6 address - boolean isLocalHost = true; - for (int i = 0; i < host.length(); i++) { - final char ch = host.charAt(i); - if (ch == '.' || ch == ':') { - isLocalHost = false; - break; - } - } - if (isLocalHost) { - host += ".local"; - return new CookieOrigin( - host, - origin.getPort(), - origin.getPath(), - origin.isSecure()); - } else { - return origin; - } - } - - @Override - public int getVersion() { - return 1; - } - - @Override - public Header getVersionHeader() { - final CharArrayBuffer buffer = new CharArrayBuffer(40); - buffer.append(SM.COOKIE2); - buffer.append(": "); - buffer.append("$Version="); - buffer.append(Integer.toString(getVersion())); - return new BufferedHeader(buffer); - } - - @Override - public String toString() { - return "rfc2965"; - } - -} - diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2965SpecProvider.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2965SpecProvider.java deleted file mode 100644 index f8197b55..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2965SpecProvider.java +++ /dev/null @@ -1,93 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.annotation.Obsolete; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -import com.tracelytics.ext.apache.http.conn.util.PublicSuffixMatcher; -import com.tracelytics.ext.apache.http.cookie.CookieSpec; -import com.tracelytics.ext.apache.http.cookie.CookieSpecProvider; - -/** - * {@link com.tracelytics.ext.apache.http.cookie.CookieSpecProvider} implementation that provides an instance of - * {@link RFC2965Spec}. The instance returned by this factory can - * be shared by multiple threads. - *

- * Rendered obsolete by {@link com.tracelytics.ext.apache.http.impl.cookie.RFC6265CookieSpecProvider} - * - * @since 4.4 - * @see com.tracelytics.ext.apache.http.impl.cookie.RFC6265CookieSpecProvider - */ -@Obsolete -@Immutable -public class RFC2965SpecProvider implements CookieSpecProvider { - - private final PublicSuffixMatcher publicSuffixMatcher; - private final boolean oneHeader; - - private volatile CookieSpec cookieSpec; - - public RFC2965SpecProvider(final PublicSuffixMatcher publicSuffixMatcher, final boolean oneHeader) { - super(); - this.oneHeader = oneHeader; - this.publicSuffixMatcher = publicSuffixMatcher; - } - - public RFC2965SpecProvider(final PublicSuffixMatcher publicSuffixMatcher) { - this(publicSuffixMatcher, false); - } - - public RFC2965SpecProvider() { - this(null, false); - } - - @Override - public CookieSpec create(final HttpContext context) { - if (cookieSpec == null) { - synchronized (this) { - if (cookieSpec == null) { - this.cookieSpec = new RFC2965Spec(this.oneHeader, - new RFC2965VersionAttributeHandler(), - new BasicPathHandler(), - PublicSuffixDomainFilter.decorate( - new RFC2965DomainAttributeHandler(), this.publicSuffixMatcher), - new RFC2965PortAttributeHandler(), - new BasicMaxAgeHandler(), - new BasicSecureHandler(), - new BasicCommentHandler(), - new RFC2965CommentUrlAttributeHandler(), - new RFC2965DiscardAttributeHandler()); - } - } - } - return this.cookieSpec; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2965VersionAttributeHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2965VersionAttributeHandler.java deleted file mode 100644 index a06936a3..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC2965VersionAttributeHandler.java +++ /dev/null @@ -1,103 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.cookie.ClientCookie; -import com.tracelytics.ext.apache.http.cookie.CommonCookieAttributeHandler; -import com.tracelytics.ext.apache.http.cookie.Cookie; -import com.tracelytics.ext.apache.http.cookie.CookieOrigin; -import com.tracelytics.ext.apache.http.cookie.CookieRestrictionViolationException; -import com.tracelytics.ext.apache.http.cookie.MalformedCookieException; -import com.tracelytics.ext.apache.http.cookie.SetCookie; -import com.tracelytics.ext.apache.http.cookie.SetCookie2; - -/** - * {@code "Version"} cookie attribute handler for RFC 2965 cookie spec. - * - * @since 4.0 - */ -@Immutable -public class RFC2965VersionAttributeHandler implements CommonCookieAttributeHandler { - - public RFC2965VersionAttributeHandler() { - super(); - } - - /** - * Parse cookie version attribute. - */ - @Override - public void parse(final SetCookie cookie, final String value) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - if (value == null) { - throw new MalformedCookieException( - "Missing value for version attribute"); - } - int version = -1; - try { - version = Integer.parseInt(value); - } catch (final NumberFormatException e) { - version = -1; - } - if (version < 0) { - throw new MalformedCookieException("Invalid cookie version."); - } - cookie.setVersion(version); - } - - /** - * validate cookie version attribute. Version attribute is REQUIRED. - */ - @Override - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - if (cookie instanceof SetCookie2) { - if (cookie instanceof ClientCookie - && !((ClientCookie) cookie).containsAttribute(ClientCookie.VERSION_ATTR)) { - throw new CookieRestrictionViolationException( - "Violates RFC 2965. Version attribute is required."); - } - } - } - - @Override - public boolean match(final Cookie cookie, final CookieOrigin origin) { - return true; - } - - @Override - public String getAttributeName() { - return ClientCookie.VERSION_ATTR; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC6265CookieSpecBase.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC6265CookieSpecBase.java deleted file mode 100644 index ca778e02..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC6265CookieSpecBase.java +++ /dev/null @@ -1,277 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import java.util.ArrayList; -import java.util.BitSet; -import java.util.Collections; -import java.util.Date; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import com.tracelytics.ext.apache.http.FormattedHeader; -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.message.BufferedHeader; -import com.tracelytics.ext.apache.http.message.ParserCursor; -import com.tracelytics.ext.apache.http.message.TokenParser; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -import com.tracelytics.ext.apache.http.cookie.ClientCookie; -import com.tracelytics.ext.apache.http.cookie.CommonCookieAttributeHandler; -import com.tracelytics.ext.apache.http.cookie.Cookie; -import com.tracelytics.ext.apache.http.cookie.CookieAttributeHandler; -import com.tracelytics.ext.apache.http.cookie.CookieOrigin; -import com.tracelytics.ext.apache.http.cookie.CookiePriorityComparator; -import com.tracelytics.ext.apache.http.cookie.CookieSpec; -import com.tracelytics.ext.apache.http.cookie.MalformedCookieException; -import com.tracelytics.ext.apache.http.cookie.SM; - -/** - * Cookie management functions shared by RFC C6265 compliant specification. - * - * @since 4.4 - */ -@ThreadSafe -class RFC6265CookieSpecBase implements CookieSpec { - - private final static char PARAM_DELIMITER = ';'; - private final static char COMMA_CHAR = ','; - private final static char EQUAL_CHAR = '='; - private final static char DQUOTE_CHAR = '"'; - private final static char ESCAPE_CHAR = '\\'; - - // IMPORTANT! - // These private static variables must be treated as immutable and never exposed outside this class - private static final BitSet TOKEN_DELIMS = TokenParser.INIT_BITSET(EQUAL_CHAR, PARAM_DELIMITER); - private static final BitSet VALUE_DELIMS = TokenParser.INIT_BITSET(PARAM_DELIMITER); - private static final BitSet SPECIAL_CHARS = TokenParser.INIT_BITSET(' ', - DQUOTE_CHAR, COMMA_CHAR, PARAM_DELIMITER, ESCAPE_CHAR); - - private final CookieAttributeHandler[] attribHandlers; - private final Map attribHandlerMap; - private final TokenParser tokenParser; - - RFC6265CookieSpecBase(final CommonCookieAttributeHandler... handlers) { - super(); - this.attribHandlers = handlers.clone(); - this.attribHandlerMap = new ConcurrentHashMap(handlers.length); - for (CommonCookieAttributeHandler handler: handlers) { - this.attribHandlerMap.put(handler.getAttributeName().toLowerCase(Locale.ROOT), handler); - } - this.tokenParser = TokenParser.INSTANCE; - } - - static String getDefaultPath(final CookieOrigin origin) { - String defaultPath = origin.getPath(); - int lastSlashIndex = defaultPath.lastIndexOf('/'); - if (lastSlashIndex >= 0) { - if (lastSlashIndex == 0) { - //Do not remove the very first slash - lastSlashIndex = 1; - } - defaultPath = defaultPath.substring(0, lastSlashIndex); - } - return defaultPath; - } - - static String getDefaultDomain(final CookieOrigin origin) { - return origin.getHost(); - } - - @Override - public final List parse(final Header header, final CookieOrigin origin) throws MalformedCookieException { - Args.notNull(header, "Header"); - Args.notNull(origin, "Cookie origin"); - if (!header.getName().equalsIgnoreCase(SM.SET_COOKIE)) { - throw new MalformedCookieException("Unrecognized cookie header: '" + header.toString() + "'"); - } - final CharArrayBuffer buffer; - final ParserCursor cursor; - if (header instanceof FormattedHeader) { - buffer = ((FormattedHeader) header).getBuffer(); - cursor = new ParserCursor(((FormattedHeader) header).getValuePos(), buffer.length()); - } else { - final String s = header.getValue(); - if (s == null) { - throw new MalformedCookieException("Header value is null"); - } - buffer = new CharArrayBuffer(s.length()); - buffer.append(s); - cursor = new ParserCursor(0, buffer.length()); - } - final String name = tokenParser.parseToken(buffer, cursor, TOKEN_DELIMS); - if (name.length() == 0) { - throw new MalformedCookieException("Cookie name is invalid: '" + header.toString() + "'"); - } - if (cursor.atEnd()) { - throw new MalformedCookieException("Cookie value is invalid: '" + header.toString() + "'"); - } - final int valueDelim = buffer.charAt(cursor.getPos()); - cursor.updatePos(cursor.getPos() + 1); - if (valueDelim != '=') { - throw new MalformedCookieException("Cookie value is invalid: '" + header.toString() + "'"); - } - final String value = tokenParser.parseValue(buffer, cursor, VALUE_DELIMS); - if (!cursor.atEnd()) { - cursor.updatePos(cursor.getPos() + 1); - } - final BasicClientCookie cookie = new BasicClientCookie(name, value); - cookie.setPath(getDefaultPath(origin)); - cookie.setDomain(getDefaultDomain(origin)); - cookie.setCreationDate(new Date()); - - final Map attribMap = new LinkedHashMap(); - while (!cursor.atEnd()) { - final String paramName = tokenParser.parseToken(buffer, cursor, TOKEN_DELIMS); - String paramValue = null; - if (!cursor.atEnd()) { - final int paramDelim = buffer.charAt(cursor.getPos()); - cursor.updatePos(cursor.getPos() + 1); - if (paramDelim == EQUAL_CHAR) { - paramValue = tokenParser.parseToken(buffer, cursor, VALUE_DELIMS); - if (!cursor.atEnd()) { - cursor.updatePos(cursor.getPos() + 1); - } - } - } - cookie.setAttribute(paramName.toLowerCase(Locale.ROOT), paramValue); - attribMap.put(paramName, paramValue); - } - // Ignore 'Expires' if 'Max-Age' is present - if (attribMap.containsKey(ClientCookie.MAX_AGE_ATTR)) { - attribMap.remove(ClientCookie.EXPIRES_ATTR); - } - - for (Map.Entry entry: attribMap.entrySet()) { - final String paramName = entry.getKey(); - final String paramValue = entry.getValue(); - final CookieAttributeHandler handler = this.attribHandlerMap.get(paramName); - if (handler != null) { - handler.parse(cookie, paramValue); - } - } - - return Collections.singletonList(cookie); - } - - @Override - public final void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - for (final CookieAttributeHandler handler: this.attribHandlers) { - handler.validate(cookie, origin); - } - } - - @Override - public final boolean match(final Cookie cookie, final CookieOrigin origin) { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - for (final CookieAttributeHandler handler: this.attribHandlers) { - if (!handler.match(cookie, origin)) { - return false; - } - } - return true; - } - - @Override - public List

formatCookies(final List cookies) { - Args.notEmpty(cookies, "List of cookies"); - final List sortedCookies; - if (cookies.size() > 1) { - // Create a mutable copy and sort the copy. - sortedCookies = new ArrayList(cookies); - Collections.sort(sortedCookies, CookiePriorityComparator.INSTANCE); - } else { - sortedCookies = cookies; - } - final CharArrayBuffer buffer = new CharArrayBuffer(20 * sortedCookies.size()); - buffer.append(SM.COOKIE); - buffer.append(": "); - for (int n = 0; n < sortedCookies.size(); n++) { - final Cookie cookie = sortedCookies.get(n); - if (n > 0) { - buffer.append(PARAM_DELIMITER); - buffer.append(' '); - } - buffer.append(cookie.getName()); - final String s = cookie.getValue(); - if (s != null) { - buffer.append(EQUAL_CHAR); - if (containsSpecialChar(s)) { - buffer.append(DQUOTE_CHAR); - for (int i = 0; i < s.length(); i++) { - final char ch = s.charAt(i); - if (ch == DQUOTE_CHAR || ch == ESCAPE_CHAR) { - buffer.append(ESCAPE_CHAR); - } - buffer.append(ch); - } - buffer.append(DQUOTE_CHAR); - } else { - buffer.append(s); - } - } - } - final List
headers = new ArrayList
(1); - headers.add(new BufferedHeader(buffer)); - return headers; - } - - boolean containsSpecialChar(final CharSequence s) { - return containsChars(s, SPECIAL_CHARS); - } - - boolean containsChars(final CharSequence s, final BitSet chars) { - for (int i = 0; i < s.length(); i++) { - final char ch = s.charAt(i); - if (chars.get(ch)) { - return true; - } - } - return false; - } - - @Override - public final int getVersion() { - return 0; - } - - @Override - public final Header getVersionHeader() { - return null; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC6265CookieSpecProvider.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC6265CookieSpecProvider.java deleted file mode 100644 index 957d649a..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC6265CookieSpecProvider.java +++ /dev/null @@ -1,123 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.protocol.HttpContext; - -import com.tracelytics.ext.apache.http.conn.util.PublicSuffixMatcher; -import com.tracelytics.ext.apache.http.cookie.Cookie; -import com.tracelytics.ext.apache.http.cookie.CookieOrigin; -import com.tracelytics.ext.apache.http.cookie.CookieSpec; -import com.tracelytics.ext.apache.http.cookie.CookieSpecProvider; -import com.tracelytics.ext.apache.http.cookie.MalformedCookieException; - -/** - * {@link com.tracelytics.ext.apache.http.cookie.CookieSpecProvider} implementation that provides an instance of - * RFC 6265 conformant cookie policy. The instance returned by this factory can be shared by - * multiple threads. - * - * @since 4.4 - */ -@Immutable -public class RFC6265CookieSpecProvider implements CookieSpecProvider { - - public enum CompatibilityLevel { - STRICT, - RELAXED, - IE_MEDIUM_SECURITY - } - - private final CompatibilityLevel compatibilityLevel; - private final PublicSuffixMatcher publicSuffixMatcher; - - private volatile CookieSpec cookieSpec; - - public RFC6265CookieSpecProvider( - final CompatibilityLevel compatibilityLevel, - final PublicSuffixMatcher publicSuffixMatcher) { - super(); - this.compatibilityLevel = compatibilityLevel != null ? compatibilityLevel : CompatibilityLevel.RELAXED; - this.publicSuffixMatcher = publicSuffixMatcher; - } - - public RFC6265CookieSpecProvider(final PublicSuffixMatcher publicSuffixMatcher) { - this(CompatibilityLevel.RELAXED, publicSuffixMatcher); - } - - public RFC6265CookieSpecProvider() { - this(CompatibilityLevel.RELAXED, null); - } - - @Override - public CookieSpec create(final HttpContext context) { - if (cookieSpec == null) { - synchronized (this) { - if (cookieSpec == null) { - switch (this.compatibilityLevel) { - case STRICT: - this.cookieSpec = new RFC6265StrictSpec( - new BasicPathHandler(), - PublicSuffixDomainFilter.decorate( - new BasicDomainHandler(), this.publicSuffixMatcher), - new BasicMaxAgeHandler(), - new BasicSecureHandler(), - new BasicExpiresHandler(RFC6265StrictSpec.DATE_PATTERNS)); - break; - case IE_MEDIUM_SECURITY: - this.cookieSpec = new RFC6265LaxSpec( - new BasicPathHandler() { - @Override - public void validate( - final Cookie cookie, - final CookieOrigin origin) throws MalformedCookieException { - // No validation - } - }, - PublicSuffixDomainFilter.decorate( - new BasicDomainHandler(), this.publicSuffixMatcher), - new BasicMaxAgeHandler(), - new BasicSecureHandler(), - new BasicExpiresHandler(RFC6265StrictSpec.DATE_PATTERNS)); - break; - default: - this.cookieSpec = new RFC6265LaxSpec( - new BasicPathHandler(), - PublicSuffixDomainFilter.decorate( - new BasicDomainHandler(), this.publicSuffixMatcher), - new LaxMaxAgeHandler(), - new BasicSecureHandler(), - new LaxExpiresHandler()); - } - } - } - } - return this.cookieSpec; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC6265LaxSpec.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC6265LaxSpec.java deleted file mode 100644 index 006d2d64..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC6265LaxSpec.java +++ /dev/null @@ -1,62 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; - -import com.tracelytics.ext.apache.http.cookie.CommonCookieAttributeHandler; - -/** - * Standard {@link com.tracelytics.ext.apache.http.cookie.CookieSpec} implementation that enforces a more relaxed - * interpretation of the HTTP state management specification (RFC 6265, section 5) - * for interoperability with existing servers that do not conform to the well behaved profile - * (RFC 6265, section 4). - * - * @since 4.4 - */ -@ThreadSafe -public class RFC6265LaxSpec extends RFC6265CookieSpecBase { - - public RFC6265LaxSpec() { - super(new BasicPathHandler(), - new BasicDomainHandler(), - new LaxMaxAgeHandler(), - new BasicSecureHandler(), - new LaxExpiresHandler()); - } - - RFC6265LaxSpec(final CommonCookieAttributeHandler... handlers) { - super(handlers); - } - - @Override - public String toString() { - return "rfc6265-lax"; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC6265StrictSpec.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC6265StrictSpec.java deleted file mode 100644 index 2ae0d4ec..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/RFC6265StrictSpec.java +++ /dev/null @@ -1,68 +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 com.tracelytics.ext.apache.http.impl.cookie; - -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; - -import com.tracelytics.ext.apache.http.client.utils.DateUtils; -import com.tracelytics.ext.apache.http.cookie.CommonCookieAttributeHandler; - -/** - * Standard {@link com.tracelytics.ext.apache.http.cookie.CookieSpec} implementation that enforces syntax - * and semantics of the well-behaved profile of the HTTP state management specification - * (RFC 6265, section 4). - * - * @since 4.4 - */ -@ThreadSafe -public class RFC6265StrictSpec extends RFC6265CookieSpecBase { - - final static String[] DATE_PATTERNS = { - DateUtils.PATTERN_RFC1123, - DateUtils.PATTERN_RFC1036, - DateUtils.PATTERN_ASCTIME - }; - - public RFC6265StrictSpec() { - super(new BasicPathHandler(), - new BasicDomainHandler(), - new BasicMaxAgeHandler(), - new BasicSecureHandler(), - new BasicExpiresHandler(DATE_PATTERNS)); - } - - RFC6265StrictSpec(final CommonCookieAttributeHandler... handlers) { - super(handlers); - } - - @Override - public String toString() { - return "rfc6265-strict"; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/package-info.java deleted file mode 100644 index 057f9b13..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/cookie/package-info.java +++ /dev/null @@ -1,32 +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 - * . - * - */ - -/** - * Default implementations of standard and common HTTP state - * management policies. - */ -package com.tracelytics.ext.apache.http.impl.cookie; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/entity/DisallowIdentityContentLengthStrategy.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/entity/DisallowIdentityContentLengthStrategy.java deleted file mode 100644 index 7f51943e..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/entity/DisallowIdentityContentLengthStrategy.java +++ /dev/null @@ -1,64 +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 com.tracelytics.ext.apache.http.impl.entity; - -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpMessage; -import com.tracelytics.ext.apache.http.ProtocolException; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.entity.ContentLengthStrategy; - -/** - * Decorator for {@link ContentLengthStrategy} implementations that disallows the use of - * identity transfer encoding. - * - * @since 4.2 - */ -@Immutable -public class DisallowIdentityContentLengthStrategy implements ContentLengthStrategy { - - public static final DisallowIdentityContentLengthStrategy INSTANCE = - new DisallowIdentityContentLengthStrategy(new LaxContentLengthStrategy(0)); - - private final ContentLengthStrategy contentLengthStrategy; - - public DisallowIdentityContentLengthStrategy(final ContentLengthStrategy contentLengthStrategy) { - super(); - this.contentLengthStrategy = contentLengthStrategy; - } - - @Override - public long determineLength(final HttpMessage message) throws HttpException { - final long result = this.contentLengthStrategy.determineLength(message); - if (result == ContentLengthStrategy.IDENTITY) { - throw new ProtocolException("Identity transfer encoding cannot be used"); - } - return result; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/entity/EntityDeserializer.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/entity/EntityDeserializer.java deleted file mode 100644 index d69542eb..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/entity/EntityDeserializer.java +++ /dev/null @@ -1,143 +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 com.tracelytics.ext.apache.http.impl.entity; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpMessage; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.entity.BasicHttpEntity; -import com.tracelytics.ext.apache.http.entity.ContentLengthStrategy; -import com.tracelytics.ext.apache.http.impl.io.ChunkedInputStream; -import com.tracelytics.ext.apache.http.impl.io.ContentLengthInputStream; -import com.tracelytics.ext.apache.http.impl.io.IdentityInputStream; -import com.tracelytics.ext.apache.http.io.SessionInputBuffer; -import com.tracelytics.ext.apache.http.protocol.HTTP; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * HTTP entity deserializer. - *

- * This entity deserializer supports "chunked" and "identitiy" transfer-coding - * and content length delimited content. - *

- * This class relies on a specific implementation of - * {@link ContentLengthStrategy} to determine the content length or transfer - * encoding of the entity. - *

- * This class generates an instance of {@link HttpEntity} based on - * properties of the message. The content of the entity will be decoded - * transparently for the consumer. - * - * @since 4.0 - * - * @deprecated (4.3) use {@link com.tracelytics.ext.apache.http.impl.BHttpConnectionBase} - */ -@Immutable // assuming injected dependencies are immutable -@Deprecated -public class EntityDeserializer { - - private final ContentLengthStrategy lenStrategy; - - public EntityDeserializer(final ContentLengthStrategy lenStrategy) { - super(); - this.lenStrategy = Args.notNull(lenStrategy, "Content length strategy"); - } - - /** - * Creates a {@link BasicHttpEntity} based on properties of the given - * message. The content of the entity is created by wrapping - * {@link SessionInputBuffer} with a content decoder depending on the - * transfer mechanism used by the message. - *

- * This method is called by the public - * {@link #deserialize(SessionInputBuffer, HttpMessage)}. - * - * @param inbuffer the session input buffer. - * @param message the message. - * @return HTTP entity. - * @throws HttpException in case of HTTP protocol violation. - * @throws IOException in case of an I/O error. - */ - protected BasicHttpEntity doDeserialize( - final SessionInputBuffer inbuffer, - final HttpMessage message) throws HttpException, IOException { - final BasicHttpEntity entity = new BasicHttpEntity(); - - final long len = this.lenStrategy.determineLength(message); - if (len == ContentLengthStrategy.CHUNKED) { - entity.setChunked(true); - entity.setContentLength(-1); - entity.setContent(new ChunkedInputStream(inbuffer)); - } else if (len == ContentLengthStrategy.IDENTITY) { - entity.setChunked(false); - entity.setContentLength(-1); - entity.setContent(new IdentityInputStream(inbuffer)); - } else { - entity.setChunked(false); - entity.setContentLength(len); - entity.setContent(new ContentLengthInputStream(inbuffer, len)); - } - - final Header contentTypeHeader = message.getFirstHeader(HTTP.CONTENT_TYPE); - if (contentTypeHeader != null) { - entity.setContentType(contentTypeHeader); - } - final Header contentEncodingHeader = message.getFirstHeader(HTTP.CONTENT_ENCODING); - if (contentEncodingHeader != null) { - entity.setContentEncoding(contentEncodingHeader); - } - return entity; - } - - /** - * Creates an {@link HttpEntity} based on properties of the given message. - * The content of the entity is created by wrapping - * {@link SessionInputBuffer} with a content decoder depending on the - * transfer mechanism used by the message. - *

- * The content of the entity is NOT retrieved by this method. - * - * @param inbuffer the session input buffer. - * @param message the message. - * @return HTTP entity. - * @throws HttpException in case of HTTP protocol violation. - * @throws IOException in case of an I/O error. - */ - public HttpEntity deserialize( - final SessionInputBuffer inbuffer, - final HttpMessage message) throws HttpException, IOException { - Args.notNull(inbuffer, "Session input buffer"); - Args.notNull(message, "HTTP message"); - return doDeserialize(inbuffer, message); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/entity/EntitySerializer.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/entity/EntitySerializer.java deleted file mode 100644 index 6a681862..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/entity/EntitySerializer.java +++ /dev/null @@ -1,121 +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 com.tracelytics.ext.apache.http.impl.entity; - -import java.io.IOException; -import java.io.OutputStream; - -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpMessage; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.entity.ContentLengthStrategy; -import com.tracelytics.ext.apache.http.impl.io.ChunkedOutputStream; -import com.tracelytics.ext.apache.http.impl.io.ContentLengthOutputStream; -import com.tracelytics.ext.apache.http.impl.io.IdentityOutputStream; -import com.tracelytics.ext.apache.http.io.SessionOutputBuffer; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * HTTP entity serializer. - *

- * This entity serializer currently supports "chunked" and "identitiy" - * transfer-coding and content length delimited content. - *

- * This class relies on a specific implementation of - * {@link ContentLengthStrategy} to determine the content length or transfer - * encoding of the entity. - *

- * This class writes out the content of {@link HttpEntity} to the data stream - * using a transfer coding based on properties on the HTTP message. - * - * @since 4.0 - * - * @deprecated (4.3) use {@link com.tracelytics.ext.apache.http.impl.BHttpConnectionBase} - */ -@Immutable // assuming injected dependencies are immutable -@Deprecated -public class EntitySerializer { - - private final ContentLengthStrategy lenStrategy; - - public EntitySerializer(final ContentLengthStrategy lenStrategy) { - super(); - this.lenStrategy = Args.notNull(lenStrategy, "Content length strategy"); - } - - /** - * Creates a transfer codec based on properties of the given HTTP message - * and returns {@link OutputStream} instance that transparently encodes - * output data as it is being written out to the output stream. - *

- * This method is called by the public - * {@link #serialize(SessionOutputBuffer, HttpMessage, HttpEntity)}. - * - * @param outbuffer the session output buffer. - * @param message the HTTP message. - * @return output stream. - * @throws HttpException in case of HTTP protocol violation. - * @throws IOException in case of an I/O error. - */ - protected OutputStream doSerialize( - final SessionOutputBuffer outbuffer, - final HttpMessage message) throws HttpException, IOException { - final long len = this.lenStrategy.determineLength(message); - if (len == ContentLengthStrategy.CHUNKED) { - return new ChunkedOutputStream(outbuffer); - } else if (len == ContentLengthStrategy.IDENTITY) { - return new IdentityOutputStream(outbuffer); - } else { - return new ContentLengthOutputStream(outbuffer, len); - } - } - - /** - * Writes out the content of the given HTTP entity to the session output - * buffer based on properties of the given HTTP message. - * - * @param outbuffer the output session buffer. - * @param message the HTTP message. - * @param entity the HTTP entity to be written out. - * @throws HttpException in case of HTTP protocol violation. - * @throws IOException in case of an I/O error. - */ - public void serialize( - final SessionOutputBuffer outbuffer, - final HttpMessage message, - final HttpEntity entity) throws HttpException, IOException { - Args.notNull(outbuffer, "Session output buffer"); - Args.notNull(message, "HTTP message"); - Args.notNull(entity, "HTTP entity"); - final OutputStream outstream = doSerialize(outbuffer, message); - entity.writeTo(outstream); - outstream.close(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/entity/LaxContentLengthStrategy.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/entity/LaxContentLengthStrategy.java deleted file mode 100644 index a60faa3f..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/entity/LaxContentLengthStrategy.java +++ /dev/null @@ -1,127 +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 com.tracelytics.ext.apache.http.impl.entity; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HeaderElement; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpMessage; -import com.tracelytics.ext.apache.http.ParseException; -import com.tracelytics.ext.apache.http.ProtocolException; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.entity.ContentLengthStrategy; -import com.tracelytics.ext.apache.http.protocol.HTTP; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * The lax implementation of the content length strategy. This class will ignore - * unrecognized transfer encodings and malformed {@code Content-Length} - * header values. - *

- * This class recognizes "chunked" and "identitiy" transfer-coding only. - * - * @since 4.0 - */ -@Immutable -public class LaxContentLengthStrategy implements ContentLengthStrategy { - - public static final LaxContentLengthStrategy INSTANCE = new LaxContentLengthStrategy(); - - private final int implicitLen; - - /** - * Creates {@code LaxContentLengthStrategy} instance with the given length used per default - * when content length is not explicitly specified in the message. - * - * @param implicitLen implicit content length. - * - * @since 4.2 - */ - public LaxContentLengthStrategy(final int implicitLen) { - super(); - this.implicitLen = implicitLen; - } - - /** - * Creates {@code LaxContentLengthStrategy} instance. {@link ContentLengthStrategy#IDENTITY} - * is used per default when content length is not explicitly specified in the message. - */ - public LaxContentLengthStrategy() { - this(IDENTITY); - } - - @Override - public long determineLength(final HttpMessage message) throws HttpException { - Args.notNull(message, "HTTP message"); - - final Header transferEncodingHeader = message.getFirstHeader(HTTP.TRANSFER_ENCODING); - // We use Transfer-Encoding if present and ignore Content-Length. - // RFC2616, 4.4 item number 3 - if (transferEncodingHeader != null) { - final HeaderElement[] encodings; - try { - encodings = transferEncodingHeader.getElements(); - } catch (final ParseException px) { - throw new ProtocolException - ("Invalid Transfer-Encoding header value: " + - transferEncodingHeader, px); - } - // The chunked encoding must be the last one applied RFC2616, 14.41 - final int len = encodings.length; - if (HTTP.IDENTITY_CODING.equalsIgnoreCase(transferEncodingHeader.getValue())) { - return IDENTITY; - } else if ((len > 0) && (HTTP.CHUNK_CODING.equalsIgnoreCase( - encodings[len - 1].getName()))) { - return CHUNKED; - } else { - return IDENTITY; - } - } - final Header contentLengthHeader = message.getFirstHeader(HTTP.CONTENT_LEN); - if (contentLengthHeader != null) { - long contentlen = -1; - final Header[] headers = message.getHeaders(HTTP.CONTENT_LEN); - for (int i = headers.length - 1; i >= 0; i--) { - final Header header = headers[i]; - try { - contentlen = Long.parseLong(header.getValue()); - break; - } catch (final NumberFormatException ignore) { - } - // See if we can have better luck with another header, if present - } - if (contentlen >= 0) { - return contentlen; - } else { - return IDENTITY; - } - } - return this.implicitLen; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/entity/StrictContentLengthStrategy.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/entity/StrictContentLengthStrategy.java deleted file mode 100644 index 771f1e11..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/entity/StrictContentLengthStrategy.java +++ /dev/null @@ -1,117 +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 com.tracelytics.ext.apache.http.impl.entity; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpMessage; -import com.tracelytics.ext.apache.http.HttpVersion; -import com.tracelytics.ext.apache.http.ProtocolException; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.entity.ContentLengthStrategy; -import com.tracelytics.ext.apache.http.protocol.HTTP; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * The strict implementation of the content length strategy. This class - * will throw {@link ProtocolException} if it encounters an unsupported - * transfer encoding or a malformed {@code Content-Length} header - * value. - *

- * This class recognizes "chunked" and "identitiy" transfer-coding only. - * - * @since 4.0 - */ -@Immutable -public class StrictContentLengthStrategy implements ContentLengthStrategy { - - public static final StrictContentLengthStrategy INSTANCE = new StrictContentLengthStrategy(); - - private final int implicitLen; - - /** - * Creates {@code StrictContentLengthStrategy} instance with the given length used per default - * when content length is not explicitly specified in the message. - * - * @param implicitLen implicit content length. - * - * @since 4.2 - */ - public StrictContentLengthStrategy(final int implicitLen) { - super(); - this.implicitLen = implicitLen; - } - - /** - * Creates {@code StrictContentLengthStrategy} instance. {@link ContentLengthStrategy#IDENTITY} - * is used per default when content length is not explicitly specified in the message. - */ - public StrictContentLengthStrategy() { - this(IDENTITY); - } - - @Override - public long determineLength(final HttpMessage message) throws HttpException { - Args.notNull(message, "HTTP message"); - // Although Transfer-Encoding is specified as a list, in practice - // it is either missing or has the single value "chunked". So we - // treat it as a single-valued header here. - final Header transferEncodingHeader = message.getFirstHeader(HTTP.TRANSFER_ENCODING); - if (transferEncodingHeader != null) { - final String s = transferEncodingHeader.getValue(); - if (HTTP.CHUNK_CODING.equalsIgnoreCase(s)) { - if (message.getProtocolVersion().lessEquals(HttpVersion.HTTP_1_0)) { - throw new ProtocolException( - "Chunked transfer encoding not allowed for " + - message.getProtocolVersion()); - } - return CHUNKED; - } else if (HTTP.IDENTITY_CODING.equalsIgnoreCase(s)) { - return IDENTITY; - } else { - throw new ProtocolException( - "Unsupported transfer encoding: " + s); - } - } - final Header contentLengthHeader = message.getFirstHeader(HTTP.CONTENT_LEN); - if (contentLengthHeader != null) { - final String s = contentLengthHeader.getValue(); - try { - final long len = Long.parseLong(s); - if (len < 0) { - throw new ProtocolException("Negative content length: " + s); - } - return len; - } catch (final NumberFormatException e) { - throw new ProtocolException("Invalid content length: " + s); - } - } - return this.implicitLen; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/entity/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/entity/package-info.java deleted file mode 100644 index 8973c24b..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/entity/package-info.java +++ /dev/null @@ -1,31 +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 - * . - * - */ - -/** - * Default implementations of entity content strategies. - */ -package com.tracelytics.ext.apache.http.impl.entity; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/BackoffStrategyExec.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/BackoffStrategyExec.java deleted file mode 100644 index 4af072a6..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/BackoffStrategyExec.java +++ /dev/null @@ -1,106 +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 com.tracelytics.ext.apache.http.impl.execchain; - -import java.io.IOException; -import java.lang.reflect.UndeclaredThrowableException; - -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -import com.tracelytics.ext.apache.http.client.BackoffManager; -import com.tracelytics.ext.apache.http.client.ConnectionBackoffStrategy; -import com.tracelytics.ext.apache.http.client.methods.CloseableHttpResponse; -import com.tracelytics.ext.apache.http.client.methods.HttpExecutionAware; -import com.tracelytics.ext.apache.http.client.methods.HttpRequestWrapper; -import com.tracelytics.ext.apache.http.client.protocol.HttpClientContext; -import com.tracelytics.ext.apache.http.conn.routing.HttpRoute; - -/** - * @since 4.3 - */ -@Immutable -public class BackoffStrategyExec implements ClientExecChain { - - private final ClientExecChain requestExecutor; - private final ConnectionBackoffStrategy connectionBackoffStrategy; - private final BackoffManager backoffManager; - - public BackoffStrategyExec( - final ClientExecChain requestExecutor, - final ConnectionBackoffStrategy connectionBackoffStrategy, - final BackoffManager backoffManager) { - super(); - Args.notNull(requestExecutor, "HTTP client request executor"); - Args.notNull(connectionBackoffStrategy, "Connection backoff strategy"); - Args.notNull(backoffManager, "Backoff manager"); - this.requestExecutor = requestExecutor; - this.connectionBackoffStrategy = connectionBackoffStrategy; - this.backoffManager = backoffManager; - } - - @Override - public CloseableHttpResponse execute( - final HttpRoute route, - final HttpRequestWrapper 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; - try { - out = this.requestExecutor.execute(route, request, context, execAware); - } catch (final Exception ex) { - if (out != null) { - out.close(); - } - if (this.connectionBackoffStrategy.shouldBackoff(ex)) { - this.backoffManager.backOff(route); - } - if (ex instanceof RuntimeException) { - throw (RuntimeException) ex; - } - if (ex instanceof HttpException) { - throw (HttpException) ex; - } - if (ex instanceof IOException) { - throw (IOException) ex; - } - throw new UndeclaredThrowableException(ex); - } - if (this.connectionBackoffStrategy.shouldBackoff(out)) { - this.backoffManager.backOff(route); - } else { - this.backoffManager.probe(route); - } - return out; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/ClientExecChain.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/ClientExecChain.java deleted file mode 100644 index 910a0071..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/ClientExecChain.java +++ /dev/null @@ -1,76 +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 com.tracelytics.ext.apache.http.impl.execchain; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.HttpException; - -import com.tracelytics.ext.apache.http.client.methods.CloseableHttpResponse; -import com.tracelytics.ext.apache.http.client.methods.HttpExecutionAware; -import com.tracelytics.ext.apache.http.client.methods.HttpRequestWrapper; -import com.tracelytics.ext.apache.http.client.protocol.HttpClientContext; -import com.tracelytics.ext.apache.http.conn.routing.HttpRoute; - -/** - * This interface represents an element in the HTTP request execution chain. Each element can - * either be a decorator around another element that implements a cross cutting aspect or - * a self-contained executor capable of producing a response for the given request. - *

- * 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 - * runtime exception, or in case the response is not propagated to the caller. - *

- * - * @since 4.3 - */ -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. - * @return HTTP response either received from the opposite endpoint - * or generated locally. - * @throws IOException in case of a I/O error. - * (this type of exceptions are potentially recoverable). - * @throws HttpException in case of an HTTP protocol error - * (usually this type of exceptions are non-recoverable). - */ - CloseableHttpResponse execute( - HttpRoute route, - HttpRequestWrapper request, - HttpClientContext clientContext, - HttpExecutionAware execAware) throws IOException, HttpException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/ConnectionHolder.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/ConnectionHolder.java deleted file mode 100644 index 305c1a18..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/ConnectionHolder.java +++ /dev/null @@ -1,158 +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 com.tracelytics.ext.apache.http.impl.execchain; - -import java.io.Closeable; -import java.io.IOException; -import java.util.concurrent.TimeUnit; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.tracelytics.ext.apache.http.HttpClientConnection; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.concurrent.Cancellable; -import com.tracelytics.ext.apache.http.conn.ConnectionReleaseTrigger; -import com.tracelytics.ext.apache.http.conn.HttpClientConnectionManager; - -/** - * Internal connection holder. - * - * @since 4.3 - */ -@ThreadSafe -class ConnectionHolder implements ConnectionReleaseTrigger, Cancellable, Closeable { - - private final Logger log; - - private final HttpClientConnectionManager manager; - private final HttpClientConnection managedConn; - private volatile boolean reusable; - private volatile Object state; - private volatile long validDuration; - private volatile TimeUnit tunit; - - private volatile boolean released; - - public ConnectionHolder( - final Logger log, - final HttpClientConnectionManager manager, - final HttpClientConnection managedConn) { - super(); - this.log = log; - this.manager = manager; - this.managedConn = managedConn; - } - - public boolean isReusable() { - return this.reusable; - } - - public void markReusable() { - this.reusable = true; - } - - public void markNonReusable() { - this.reusable = false; - } - - public void setState(final Object state) { - this.state = state; - } - - public void setValidFor(final long duration, final TimeUnit tunit) { - synchronized (this.managedConn) { - this.validDuration = duration; - this.tunit = tunit; - } - } - - @Override - public void releaseConnection() { - synchronized (this.managedConn) { - if (this.released) { - return; - } - this.released = true; - if (this.reusable) { - this.manager.releaseConnection(this.managedConn, - this.state, this.validDuration, this.tunit); - } else { - try { - this.managedConn.close(); - log.log(Level.FINE, "Connection discarded"); - } catch (final IOException ex) { - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, ex.getMessage(), ex); - } - } finally { - this.manager.releaseConnection( - this.managedConn, null, 0, TimeUnit.MILLISECONDS); - } - } - } - } - - @Override - public void abortConnection() { - synchronized (this.managedConn) { - if (this.released) { - return; - } - this.released = true; - try { - this.managedConn.shutdown(); - log.log(Level.FINE, "Connection discarded"); - } catch (final IOException ex) { - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, ex.getMessage(), ex); - } - } finally { - this.manager.releaseConnection( - this.managedConn, null, 0, TimeUnit.MILLISECONDS); - } - } - } - - @Override - public boolean cancel() { - final boolean alreadyReleased = this.released; - log.log(Level.FINE, "Cancelling request execution"); - abortConnection(); - return !alreadyReleased; - } - - public boolean isReleased() { - return this.released; - } - - @Override - public void close() throws IOException { - abortConnection(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/HttpResponseProxy.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/HttpResponseProxy.java deleted file mode 100644 index a7548a99..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/HttpResponseProxy.java +++ /dev/null @@ -1,214 +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 com.tracelytics.ext.apache.http.impl.execchain; - -import java.io.IOException; -import java.util.Locale; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HeaderIterator; -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.ProtocolVersion; -import com.tracelytics.ext.apache.http.StatusLine; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.params.HttpParams; - -import com.tracelytics.ext.apache.http.client.methods.CloseableHttpResponse; - -/** - * A proxy class for {@link com.tracelytics.ext.apache.http.HttpResponse} that can be used to release client connection - * associated with the original response. - * - * @since 4.3 - */ -@NotThreadSafe -class HttpResponseProxy implements CloseableHttpResponse { - - private final HttpResponse original; - private final ConnectionHolder connHolder; - - 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.abortConnection(); - } - } - - @Override - public StatusLine getStatusLine() { - return original.getStatusLine(); - } - - @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); - } - - @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 boolean containsHeader(final String name) { - return original.containsHeader(name); - } - - @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(); - } - - @Override - public void addHeader(final Header header) { - original.addHeader(header); - } - - @Override - public void addHeader(final String name, final String value) { - original.addHeader(name, value); - } - - @Override - public void setHeader(final Header header) { - original.setHeader(header); - } - - @Override - public void setHeader(final String name, final String value) { - original.setHeader(name, value); - } - - @Override - public void setHeaders(final Header[] headers) { - original.setHeaders(headers); - } - - @Override - public void removeHeader(final Header header) { - original.removeHeader(header); - } - - @Override - public void removeHeaders(final String name) { - original.removeHeaders(name); - } - - @Override - public HeaderIterator headerIterator() { - return original.headerIterator(); - } - - @Override - public HeaderIterator headerIterator(final String name) { - return original.headerIterator(name); - } - - @Override - @Deprecated - public HttpParams getParams() { - return original.getParams(); - } - - @Override - @Deprecated - public void setParams(final HttpParams params) { - original.setParams(params); - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("HttpResponseProxy{"); - sb.append(original); - sb.append('}'); - return sb.toString(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/MainClientExec.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/MainClientExec.java deleted file mode 100644 index 3f0ef947..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/MainClientExec.java +++ /dev/null @@ -1,585 +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 com.tracelytics.ext.apache.http.impl.execchain; - -import java.io.IOException; -import java.io.InterruptedIOException; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.tracelytics.ext.apache.http.ConnectionReuseStrategy; -import com.tracelytics.ext.apache.http.HttpClientConnection; -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpEntityEnclosingRequest; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.auth.AUTH; -import com.tracelytics.ext.apache.http.auth.AuthProtocolState; -import com.tracelytics.ext.apache.http.auth.AuthState; -import com.tracelytics.ext.apache.http.client.AuthenticationStrategy; -import com.tracelytics.ext.apache.http.client.NonRepeatableRequestException; -import com.tracelytics.ext.apache.http.client.UserTokenHandler; -import com.tracelytics.ext.apache.http.client.config.RequestConfig; -import com.tracelytics.ext.apache.http.client.methods.CloseableHttpResponse; -import com.tracelytics.ext.apache.http.client.methods.HttpExecutionAware; -import com.tracelytics.ext.apache.http.client.methods.HttpRequestWrapper; -import com.tracelytics.ext.apache.http.client.protocol.HttpClientContext; -import com.tracelytics.ext.apache.http.conn.ConnectionKeepAliveStrategy; -import com.tracelytics.ext.apache.http.conn.ConnectionRequest; -import com.tracelytics.ext.apache.http.conn.HttpClientConnectionManager; -import com.tracelytics.ext.apache.http.conn.routing.BasicRouteDirector; -import com.tracelytics.ext.apache.http.conn.routing.HttpRoute; -import com.tracelytics.ext.apache.http.conn.routing.HttpRouteDirector; -import com.tracelytics.ext.apache.http.conn.routing.RouteTracker; -import com.tracelytics.ext.apache.http.entity.BufferedHttpEntity; -import com.tracelytics.ext.apache.http.impl.auth.HttpAuthenticator; -import com.tracelytics.ext.apache.http.impl.conn.ConnectionShutdownException; -import com.tracelytics.ext.apache.http.message.BasicHttpRequest; -import com.tracelytics.ext.apache.http.protocol.HttpCoreContext; -import com.tracelytics.ext.apache.http.protocol.HttpProcessor; -import com.tracelytics.ext.apache.http.protocol.HttpRequestExecutor; -import com.tracelytics.ext.apache.http.protocol.ImmutableHttpProcessor; -import com.tracelytics.ext.apache.http.protocol.RequestTargetHost; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.EntityUtils; - -/** - * The last request executor in the HTTP request execution chain - * that is responsible for execution of request / response - * exchanges with the opposite endpoint. - * This executor will automatically retry the request in case - * of an authentication challenge by an intermediate proxy or - * by the target server. - * - * @since 4.3 - */ -@SuppressWarnings("deprecation") -@Immutable -public class MainClientExec implements ClientExecChain { - - private final Logger log = Logger.getLogger(getClass().getName()); - - private final HttpRequestExecutor requestExecutor; - private final HttpClientConnectionManager connManager; - private final ConnectionReuseStrategy reuseStrategy; - private final ConnectionKeepAliveStrategy keepAliveStrategy; - private final HttpProcessor proxyHttpProcessor; - private final AuthenticationStrategy targetAuthStrategy; - private final AuthenticationStrategy proxyAuthStrategy; - private final HttpAuthenticator authenticator; - private final UserTokenHandler userTokenHandler; - private final HttpRouteDirector routeDirector; - - /** - * @since 4.4 - */ - public MainClientExec( - final HttpRequestExecutor requestExecutor, - final HttpClientConnectionManager connManager, - final ConnectionReuseStrategy reuseStrategy, - final ConnectionKeepAliveStrategy keepAliveStrategy, - final HttpProcessor proxyHttpProcessor, - final AuthenticationStrategy targetAuthStrategy, - final AuthenticationStrategy proxyAuthStrategy, - final UserTokenHandler userTokenHandler) { - Args.notNull(requestExecutor, "HTTP request executor"); - Args.notNull(connManager, "Client connection manager"); - Args.notNull(reuseStrategy, "Connection reuse strategy"); - Args.notNull(keepAliveStrategy, "Connection keep alive strategy"); - Args.notNull(proxyHttpProcessor, "Proxy HTTP processor"); - Args.notNull(targetAuthStrategy, "Target authentication strategy"); - Args.notNull(proxyAuthStrategy, "Proxy authentication strategy"); - Args.notNull(userTokenHandler, "User token handler"); - this.authenticator = new HttpAuthenticator(); - this.routeDirector = new BasicRouteDirector(); - this.requestExecutor = requestExecutor; - this.connManager = connManager; - this.reuseStrategy = reuseStrategy; - this.keepAliveStrategy = keepAliveStrategy; - this.proxyHttpProcessor = proxyHttpProcessor; - this.targetAuthStrategy = targetAuthStrategy; - this.proxyAuthStrategy = proxyAuthStrategy; - this.userTokenHandler = userTokenHandler; - } - - public MainClientExec( - final HttpRequestExecutor requestExecutor, - final HttpClientConnectionManager connManager, - final ConnectionReuseStrategy reuseStrategy, - final ConnectionKeepAliveStrategy keepAliveStrategy, - final AuthenticationStrategy targetAuthStrategy, - final AuthenticationStrategy proxyAuthStrategy, - final UserTokenHandler userTokenHandler) { - this(requestExecutor, connManager, reuseStrategy, keepAliveStrategy, - new ImmutableHttpProcessor(new RequestTargetHost()), - targetAuthStrategy, proxyAuthStrategy, userTokenHandler); - } - - @Override - public CloseableHttpResponse execute( - final HttpRoute route, - final HttpRequestWrapper 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"); - - AuthState targetAuthState = context.getTargetAuthState(); - if (targetAuthState == null) { - targetAuthState = new AuthState(); - context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, targetAuthState); - } - AuthState proxyAuthState = context.getProxyAuthState(); - if (proxyAuthState == null) { - proxyAuthState = new AuthState(); - context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, proxyAuthState); - } - - if (request instanceof HttpEntityEnclosingRequest) { - RequestEntityProxy.enhance((HttpEntityEnclosingRequest) request); - } - - Object userToken = context.getUserToken(); - - final ConnectionRequest connRequest = connManager.requestConnection(route, userToken); - if (execAware != null) { - if (execAware.isAborted()) { - connRequest.cancel(); - throw new RequestAbortedException("Request aborted"); - } else { - execAware.setCancellable(connRequest); - } - } - - final RequestConfig config = context.getRequestConfig(); - - final HttpClientConnection managedConn; - try { - final int timeout = config.getConnectionRequestTimeout(); - managedConn = connRequest.get(timeout > 0 ? timeout : 0, TimeUnit.MILLISECONDS); - } catch(final InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new RequestAbortedException("Request aborted", interrupted); - } catch(final ExecutionException ex) { - Throwable cause = ex.getCause(); - if (cause == null) { - cause = ex; - } - throw new RequestAbortedException("Request execution failed", cause); - } - - context.setAttribute(HttpCoreContext.HTTP_CONNECTION, managedConn); - - if (config.isStaleConnectionCheckEnabled()) { - // validate connection - if (managedConn.isOpen()) { - this.log.log(Level.FINE, "Stale connection check"); - if (managedConn.isStale()) { - this.log.log(Level.FINE, "Stale connection detected"); - managedConn.close(); - } - } - } - - final ConnectionHolder connHolder = new ConnectionHolder(this.log, this.connManager, managedConn); - try { - if (execAware != null) { - execAware.setCancellable(connHolder); - } - - HttpResponse response; - for (int execCount = 1;; execCount++) { - - if (execCount > 1 && !RequestEntityProxy.isRepeatable(request)) { - throw new NonRepeatableRequestException("Cannot retry request " + - "with a non-repeatable request entity."); - } - - if (execAware != null && execAware.isAborted()) { - throw new RequestAbortedException("Request aborted"); - } - - if (!managedConn.isOpen()) { - this.log.log(Level.FINE, "Opening connection " + route); - try { - establishRoute(proxyAuthState, managedConn, route, request, context); - } catch (final TunnelRefusedException ex) { - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, ex.getMessage()); - } - response = ex.getResponse(); - break; - } - } - final int timeout = config.getSocketTimeout(); - if (timeout >= 0) { - managedConn.setSocketTimeout(timeout); - } - - if (execAware != null && execAware.isAborted()) { - throw new RequestAbortedException("Request aborted"); - } - - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Executing request " + request.getRequestLine()); - } - - if (!request.containsHeader(AUTH.WWW_AUTH_RESP)) { - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Target auth state: " + targetAuthState.getState()); - } - this.authenticator.generateAuthResponse(request, targetAuthState, context); - } - if (!request.containsHeader(AUTH.PROXY_AUTH_RESP) && !route.isTunnelled()) { - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Proxy auth state: " + proxyAuthState.getState()); - } - this.authenticator.generateAuthResponse(request, proxyAuthState, context); - } - - response = requestExecutor.execute(request, managedConn, context); - - // The connection is in or can be brought to a re-usable state. - if (reuseStrategy.keepAlive(response, context)) { - // Set the idle duration of this connection - final long duration = keepAliveStrategy.getKeepAliveDuration(response, context); - if (this.log.isLoggable(Level.FINE)) { - final String s; - if (duration > 0) { - s = "for " + duration + " " + TimeUnit.MILLISECONDS; - } else { - s = "indefinitely"; - } - this.log.log(Level.FINE, "Connection can be kept alive " + s); - } - connHolder.setValidFor(duration, TimeUnit.MILLISECONDS); - connHolder.markReusable(); - } else { - connHolder.markNonReusable(); - } - - if (needAuthentication( - targetAuthState, proxyAuthState, route, response, context)) { - // Make sure the response body is fully consumed, if present - final HttpEntity entity = response.getEntity(); - if (connHolder.isReusable()) { - EntityUtils.consume(entity); - } else { - managedConn.close(); - if (proxyAuthState.getState() == AuthProtocolState.SUCCESS - && proxyAuthState.getAuthScheme() != null - && proxyAuthState.getAuthScheme().isConnectionBased()) { - this.log.log(Level.FINE, "Resetting proxy auth state"); - proxyAuthState.reset(); - } - if (targetAuthState.getState() == AuthProtocolState.SUCCESS - && targetAuthState.getAuthScheme() != null - && targetAuthState.getAuthScheme().isConnectionBased()) { - this.log.log(Level.FINE, "Resetting target auth state"); - targetAuthState.reset(); - } - } - // discard previous auth headers - final HttpRequest original = request.getOriginal(); - if (!original.containsHeader(AUTH.WWW_AUTH_RESP)) { - request.removeHeaders(AUTH.WWW_AUTH_RESP); - } - if (!original.containsHeader(AUTH.PROXY_AUTH_RESP)) { - request.removeHeaders(AUTH.PROXY_AUTH_RESP); - } - } else { - break; - } - } - - if (userToken == null) { - userToken = userTokenHandler.getUserToken(context); - context.setAttribute(HttpClientContext.USER_TOKEN, userToken); - } - if (userToken != null) { - connHolder.setState(userToken); - } - - // 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 - connHolder.releaseConnection(); - return new HttpResponseProxy(response, null); - } else { - return new HttpResponseProxy(response, connHolder); - } - } catch (final ConnectionShutdownException ex) { - final InterruptedIOException ioex = new InterruptedIOException( - "Connection has been shut down"); - ioex.initCause(ex); - throw ioex; - } catch (final HttpException ex) { - connHolder.abortConnection(); - throw ex; - } catch (final IOException ex) { - connHolder.abortConnection(); - throw ex; - } catch (final RuntimeException ex) { - connHolder.abortConnection(); - throw ex; - } - } - - /** - * Establishes the target route. - */ - void establishRoute( - final AuthState proxyAuthState, - final HttpClientConnection managedConn, - final HttpRoute route, - final HttpRequest request, - final HttpClientContext context) throws HttpException, IOException { - final RequestConfig config = context.getRequestConfig(); - final int timeout = config.getConnectTimeout(); - final RouteTracker tracker = new RouteTracker(route); - int step; - do { - final HttpRoute fact = tracker.toRoute(); - step = this.routeDirector.nextStep(route, fact); - - switch (step) { - - case HttpRouteDirector.CONNECT_TARGET: - this.connManager.connect( - managedConn, - route, - timeout > 0 ? timeout : 0, - context); - tracker.connectTarget(route.isSecure()); - break; - case HttpRouteDirector.CONNECT_PROXY: - this.connManager.connect( - managedConn, - route, - timeout > 0 ? timeout : 0, - context); - final HttpHost proxy = route.getProxyHost(); - tracker.connectProxy(proxy, false); - break; - case HttpRouteDirector.TUNNEL_TARGET: { - final boolean secure = createTunnelToTarget( - proxyAuthState, managedConn, route, request, context); - this.log.log(Level.FINE, "Tunnel to target created."); - tracker.tunnelTarget(secure); - } break; - - case HttpRouteDirector.TUNNEL_PROXY: { - // The most simple example for this case is a proxy chain - // of two proxies, where P1 must be tunnelled to P2. - // route: Source -> P1 -> P2 -> Target (3 hops) - // fact: Source -> P1 -> Target (2 hops) - final int hop = fact.getHopCount()-1; // the hop to establish - final boolean secure = createTunnelToProxy(route, hop, context); - this.log.log(Level.FINE, "Tunnel to proxy created."); - tracker.tunnelProxy(route.getHopTarget(hop), secure); - } break; - - case HttpRouteDirector.LAYER_PROTOCOL: - this.connManager.upgrade(managedConn, route, context); - tracker.layerProtocol(route.isSecure()); - break; - - case HttpRouteDirector.UNREACHABLE: - throw new HttpException("Unable to establish route: " + - "planned = " + route + "; current = " + fact); - case HttpRouteDirector.COMPLETE: - this.connManager.routeComplete(managedConn, route, context); - break; - default: - throw new IllegalStateException("Unknown step indicator " - + step + " from RouteDirector."); - } - - } while (step > HttpRouteDirector.COMPLETE); - } - - /** - * Creates a tunnel to the target server. - * The connection must be established to the (last) proxy. - * A CONNECT request for tunnelling through the proxy will - * be created and sent, the response received and checked. - * This method does not update the connection with - * information about the tunnel, that is left to the caller. - */ - private boolean createTunnelToTarget( - final AuthState proxyAuthState, - final HttpClientConnection managedConn, - final HttpRoute route, - final HttpRequest request, - final HttpClientContext context) throws HttpException, IOException { - - final RequestConfig config = context.getRequestConfig(); - final int timeout = config.getConnectTimeout(); - - final HttpHost target = route.getTargetHost(); - final HttpHost proxy = route.getProxyHost(); - HttpResponse response = null; - - final String authority = target.toHostString(); - final HttpRequest connect = new BasicHttpRequest("CONNECT", authority, request.getProtocolVersion()); - - this.requestExecutor.preProcess(connect, this.proxyHttpProcessor, context); - - while (response == null) { - if (!managedConn.isOpen()) { - this.connManager.connect( - managedConn, - route, - timeout > 0 ? timeout : 0, - context); - } - - connect.removeHeaders(AUTH.PROXY_AUTH_RESP); - this.authenticator.generateAuthResponse(connect, proxyAuthState, context); - - 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()); - } - - if (config.isAuthenticationEnabled()) { - if (this.authenticator.isAuthenticationRequested(proxy, response, - this.proxyAuthStrategy, proxyAuthState, context)) { - if (this.authenticator.handleAuthChallenge(proxy, response, - this.proxyAuthStrategy, proxyAuthState, context)) { - // Retry request - if (this.reuseStrategy.keepAlive(response, context)) { - this.log.log(Level.FINE, "Connection kept alive"); - // Consume response content - final HttpEntity entity = response.getEntity(); - EntityUtils.consume(entity); - } else { - managedConn.close(); - } - response = null; - } - } - } - } - - final int status = response.getStatusLine().getStatusCode(); - - if (status > 299) { - - // Buffer response content - final HttpEntity entity = response.getEntity(); - if (entity != null) { - response.setEntity(new BufferedHttpEntity(entity)); - } - - managedConn.close(); - throw new TunnelRefusedException("CONNECT refused by proxy: " + - response.getStatusLine(), response); - } - - // How to decide on security of the tunnelled connection? - // The socket factory knows only about the segment to the proxy. - // Even if that is secure, the hop to the target may be insecure. - // Leave it to derived classes, consider insecure by default here. - return false; - } - - /** - * Creates a tunnel to an intermediate proxy. - * This method is not implemented in this class. - * It just throws an exception here. - */ - private boolean createTunnelToProxy( - final HttpRoute route, - final int hop, - final HttpClientContext context) throws HttpException { - - // Have a look at createTunnelToTarget and replicate the parts - // you need in a custom derived class. If your proxies don't require - // authentication, it is not too hard. But for the stock version of - // HttpClient, we cannot make such simplifying assumptions and would - // have to include proxy authentication code. The HttpComponents team - // is currently not in a position to support rarely used code of this - // complexity. Feel free to submit patches that refactor the code in - // createTunnelToTarget to facilitate re-use for proxy tunnelling. - - throw new HttpException("Proxy chains are not supported."); - } - - private boolean needAuthentication( - final AuthState targetAuthState, - final AuthState proxyAuthState, - final HttpRoute route, - final HttpResponse response, - final HttpClientContext context) { - final RequestConfig config = context.getRequestConfig(); - if (config.isAuthenticationEnabled()) { - HttpHost target = context.getTargetHost(); - if (target == null) { - target = route.getTargetHost(); - } - if (target.getPort() < 0) { - target = new HttpHost( - target.getHostName(), - route.getTargetHost().getPort(), - target.getSchemeName()); - } - final boolean targetAuthRequested = this.authenticator.isAuthenticationRequested( - target, response, this.targetAuthStrategy, targetAuthState, context); - - HttpHost proxy = route.getProxyHost(); - // if proxy is not set use target host instead - if (proxy == null) { - proxy = route.getTargetHost(); - } - final boolean proxyAuthRequested = this.authenticator.isAuthenticationRequested( - proxy, response, this.proxyAuthStrategy, proxyAuthState, context); - - if (targetAuthRequested) { - return this.authenticator.handleAuthChallenge(target, response, - this.targetAuthStrategy, targetAuthState, context); - } - if (proxyAuthRequested) { - return this.authenticator.handleAuthChallenge(proxy, response, - this.proxyAuthStrategy, proxyAuthState, context); - } - } - return false; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/MinimalClientExec.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/MinimalClientExec.java deleted file mode 100644 index 88e2ca27..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/MinimalClientExec.java +++ /dev/null @@ -1,251 +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 com.tracelytics.ext.apache.http.impl.execchain; - -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; -import java.util.logging.Logger; - -import com.tracelytics.ext.apache.http.ConnectionReuseStrategy; -import com.tracelytics.ext.apache.http.HttpClientConnection; -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.ProtocolException; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.client.config.RequestConfig; -import com.tracelytics.ext.apache.http.client.methods.CloseableHttpResponse; -import com.tracelytics.ext.apache.http.client.methods.HttpExecutionAware; -import com.tracelytics.ext.apache.http.client.methods.HttpRequestWrapper; -import com.tracelytics.ext.apache.http.client.methods.HttpUriRequest; -import com.tracelytics.ext.apache.http.client.protocol.HttpClientContext; -import com.tracelytics.ext.apache.http.client.protocol.RequestClientConnControl; -import com.tracelytics.ext.apache.http.client.utils.URIUtils; -import com.tracelytics.ext.apache.http.conn.ConnectionKeepAliveStrategy; -import com.tracelytics.ext.apache.http.conn.ConnectionRequest; -import com.tracelytics.ext.apache.http.conn.HttpClientConnectionManager; -import com.tracelytics.ext.apache.http.conn.routing.HttpRoute; -import com.tracelytics.ext.apache.http.impl.conn.ConnectionShutdownException; -import com.tracelytics.ext.apache.http.protocol.HttpCoreContext; -import com.tracelytics.ext.apache.http.protocol.HttpProcessor; -import com.tracelytics.ext.apache.http.protocol.HttpRequestExecutor; -import com.tracelytics.ext.apache.http.protocol.ImmutableHttpProcessor; -import com.tracelytics.ext.apache.http.protocol.RequestContent; -import com.tracelytics.ext.apache.http.protocol.RequestTargetHost; -import com.tracelytics.ext.apache.http.protocol.RequestUserAgent; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.VersionInfo; - -/** - * Request executor that implements the most fundamental aspects of - * the HTTP specification and the most straight-forward request / response - * exchange with the target server. This executor does not support - * execution via proxy and will make no attempts to retry the request - * in case of a redirect, authentication challenge or I/O error. - * - * @since 4.3 - */ -@Immutable -public class MinimalClientExec implements ClientExecChain { - - private final Logger log = Logger.getLogger(getClass().getName()); - - private final HttpRequestExecutor requestExecutor; - private final HttpClientConnectionManager connManager; - private final ConnectionReuseStrategy reuseStrategy; - private final ConnectionKeepAliveStrategy keepAliveStrategy; - private final HttpProcessor httpProcessor; - - public MinimalClientExec( - final HttpRequestExecutor requestExecutor, - final HttpClientConnectionManager connManager, - final ConnectionReuseStrategy reuseStrategy, - final ConnectionKeepAliveStrategy keepAliveStrategy) { - Args.notNull(requestExecutor, "HTTP request executor"); - Args.notNull(connManager, "Client connection manager"); - Args.notNull(reuseStrategy, "Connection reuse strategy"); - Args.notNull(keepAliveStrategy, "Connection keep alive strategy"); - this.httpProcessor = new ImmutableHttpProcessor( - new RequestContent(), - new RequestTargetHost(), - new RequestClientConnControl(), - new RequestUserAgent(VersionInfo.getUserAgent( - "Apache-HttpClient", "com.tracelytics.ext.apache.http.client", getClass()))); - this.requestExecutor = requestExecutor; - this.connManager = connManager; - this.reuseStrategy = reuseStrategy; - 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, - 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 ConnectionRequest connRequest = connManager.requestConnection(route, null); - if (execAware != null) { - if (execAware.isAborted()) { - connRequest.cancel(); - throw new RequestAbortedException("Request aborted"); - } else { - execAware.setCancellable(connRequest); - } - } - - final RequestConfig config = context.getRequestConfig(); - - final HttpClientConnection managedConn; - try { - final int timeout = config.getConnectionRequestTimeout(); - managedConn = connRequest.get(timeout > 0 ? timeout : 0, TimeUnit.MILLISECONDS); - } catch(final InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new RequestAbortedException("Request aborted", interrupted); - } catch(final ExecutionException ex) { - Throwable cause = ex.getCause(); - if (cause == null) { - cause = ex; - } - throw new RequestAbortedException("Request execution failed", cause); - } - - final ConnectionHolder releaseTrigger = new ConnectionHolder(log, connManager, managedConn); - try { - if (execAware != null) { - if (execAware.isAborted()) { - releaseTrigger.close(); - throw new RequestAbortedException("Request aborted"); - } else { - execAware.setCancellable(releaseTrigger); - } - } - - if (!managedConn.isOpen()) { - final int timeout = config.getConnectTimeout(); - this.connManager.connect( - managedConn, - route, - timeout > 0 ? timeout : 0, - context); - this.connManager.routeComplete(managedConn, route, context); - } - final int timeout = config.getSocketTimeout(); - if (timeout >= 0) { - 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); - - // The connection is in or can be brought to a re-usable state. - if (reuseStrategy.keepAlive(response, context)) { - // Set the idle duration of this connection - final long duration = keepAliveStrategy.getKeepAliveDuration(response, context); - releaseTrigger.setValidFor(duration, TimeUnit.MILLISECONDS); - releaseTrigger.markReusable(); - } else { - releaseTrigger.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); - } else { - 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 ex) { - releaseTrigger.abortConnection(); - throw ex; - } catch (final IOException ex) { - releaseTrigger.abortConnection(); - throw ex; - } catch (final RuntimeException ex) { - releaseTrigger.abortConnection(); - throw ex; - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/ProtocolExec.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/ProtocolExec.java deleted file mode 100644 index 764d6685..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/ProtocolExec.java +++ /dev/null @@ -1,203 +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 com.tracelytics.ext.apache.http.impl.execchain; - -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.ProtocolException; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.auth.AuthScope; -import com.tracelytics.ext.apache.http.auth.UsernamePasswordCredentials; -import com.tracelytics.ext.apache.http.client.CredentialsProvider; -import com.tracelytics.ext.apache.http.client.methods.CloseableHttpResponse; -import com.tracelytics.ext.apache.http.client.methods.HttpExecutionAware; -import com.tracelytics.ext.apache.http.client.methods.HttpRequestWrapper; -import com.tracelytics.ext.apache.http.client.methods.HttpUriRequest; -import com.tracelytics.ext.apache.http.client.params.ClientPNames; -import com.tracelytics.ext.apache.http.client.protocol.HttpClientContext; -import com.tracelytics.ext.apache.http.client.utils.URIUtils; -import com.tracelytics.ext.apache.http.conn.routing.HttpRoute; -import com.tracelytics.ext.apache.http.impl.client.BasicCredentialsProvider; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.protocol.HttpCoreContext; -import com.tracelytics.ext.apache.http.protocol.HttpProcessor; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Request executor in the request execution chain that is responsible - * for implementation of HTTP specification requirements. - * Internally this executor relies on a {@link HttpProcessor} to populate - * requisite HTTP request headers, process HTTP response headers and update - * session state in {@link HttpClientContext}. - *

- * Further responsibilities such as communication with the opposite - * endpoint is delegated to the next executor in the request execution - * chain. - *

- * - * @since 4.3 - */ -@Immutable -@SuppressWarnings("deprecation") -public class ProtocolExec implements ClientExecChain { - - private final Logger log = Logger.getLogger(getClass().getName()); - - private final ClientExecChain requestExecutor; - private final HttpProcessor httpProcessor; - - public ProtocolExec(final ClientExecChain requestExecutor, final HttpProcessor httpProcessor) { - Args.notNull(requestExecutor, "HTTP client request executor"); - Args.notNull(httpProcessor, "HTTP protocol processor"); - this.requestExecutor = requestExecutor; - 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, - 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 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.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "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); - - final HttpParams params = request.getParams(); - HttpHost virtualHost = (HttpHost) params.getParameter(ClientPNames.VIRTUAL_HOST); - // HTTPCLIENT-1092 - add the port if necessary - if (virtualHost != null && virtualHost.getPort() == -1) { - final int port = route.getTargetHost().getPort(); - if (port != -1) { - virtualHost = new HttpHost(virtualHost.getHostName(), port, - virtualHost.getSchemeName()); - } - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Using virtual host" + virtualHost); - } - } - - HttpHost target = null; - if (virtualHost != null) { - target = virtualHost; - } else { - 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(); - if (userinfo != null) { - CredentialsProvider credsProvider = context.getCredentialsProvider(); - if (credsProvider == null) { - credsProvider = new BasicCredentialsProvider(); - context.setCredentialsProvider(credsProvider); - } - credsProvider.setCredentials( - new AuthScope(target), - new UsernamePasswordCredentials(userinfo)); - } - } - - // 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); - - final CloseableHttpResponse response = this.requestExecutor.execute(route, request, - context, execAware); - try { - // Run response protocol interceptors - context.setAttribute(HttpCoreContext.HTTP_RESPONSE, response); - this.httpProcessor.process(response, context); - return response; - } catch (final RuntimeException ex) { - response.close(); - throw ex; - } catch (final IOException ex) { - response.close(); - throw ex; - } catch (final HttpException ex) { - response.close(); - throw ex; - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/RedirectExec.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/RedirectExec.java deleted file mode 100644 index cad2bf71..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/RedirectExec.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package com.tracelytics.ext.apache.http.impl.execchain; - -import java.io.IOException; -import java.net.URI; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.tracelytics.ext.apache.http.HttpEntityEnclosingRequest; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.ProtocolException; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.auth.AuthScheme; -import com.tracelytics.ext.apache.http.auth.AuthState; -import com.tracelytics.ext.apache.http.client.RedirectException; -import com.tracelytics.ext.apache.http.client.RedirectStrategy; -import com.tracelytics.ext.apache.http.client.config.RequestConfig; -import com.tracelytics.ext.apache.http.client.methods.CloseableHttpResponse; -import com.tracelytics.ext.apache.http.client.methods.HttpExecutionAware; -import com.tracelytics.ext.apache.http.client.methods.HttpRequestWrapper; -import com.tracelytics.ext.apache.http.client.protocol.HttpClientContext; -import com.tracelytics.ext.apache.http.client.utils.URIUtils; -import com.tracelytics.ext.apache.http.conn.routing.HttpRoute; -import com.tracelytics.ext.apache.http.conn.routing.HttpRoutePlanner; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.EntityUtils; - -/** - * Request executor in the request execution chain that is responsible - * for handling of request redirects. - *

- * Further responsibilities such as communication with the opposite - * endpoint is delegated to the next executor in the request execution - * chain. - *

- * - * @since 4.3 - */ -@ThreadSafe -public class RedirectExec implements ClientExecChain { - - private final Logger log = Logger.getLogger(getClass().getName()); - - private final ClientExecChain requestExecutor; - private final RedirectStrategy redirectStrategy; - private final HttpRoutePlanner routePlanner; - - public RedirectExec( - final ClientExecChain requestExecutor, - final HttpRoutePlanner routePlanner, - final RedirectStrategy redirectStrategy) { - super(); - Args.notNull(requestExecutor, "HTTP client request executor"); - Args.notNull(routePlanner, "HTTP route planner"); - Args.notNull(redirectStrategy, "HTTP redirect strategy"); - this.requestExecutor = requestExecutor; - this.routePlanner = routePlanner; - this.redirectStrategy = redirectStrategy; - } - - @Override - public CloseableHttpResponse execute( - final HttpRoute route, - final HttpRequestWrapper 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 List redirectLocations = context.getRedirectLocations(); - if (redirectLocations != null) { - redirectLocations.clear(); - } - - final RequestConfig config = context.getRequestConfig(); - final int maxRedirects = config.getMaxRedirects() > 0 ? config.getMaxRedirects() : 50; - HttpRoute currentRoute = route; - HttpRequestWrapper currentRequest = request; - for (int redirectCount = 0;;) { - final CloseableHttpResponse response = requestExecutor.execute( - currentRoute, currentRequest, context, execAware); - try { - if (config.isRedirectsEnabled() && - this.redirectStrategy.isRedirected(currentRequest, response, context)) { - - if (redirectCount >= maxRedirects) { - throw new RedirectException("Maximum redirects ("+ maxRedirects + ") exceeded"); - } - redirectCount++; - - final HttpRequest redirect = this.redirectStrategy.getRedirect( - currentRequest, response, context); - if (!redirect.headerIterator().hasNext()) { - final HttpRequest original = request.getOriginal(); - redirect.setHeaders(original.getAllHeaders()); - } - currentRequest = HttpRequestWrapper.wrap(redirect); - - if (currentRequest instanceof HttpEntityEnclosingRequest) { - RequestEntityProxy.enhance((HttpEntityEnclosingRequest) currentRequest); - } - - final URI uri = currentRequest.getURI(); - final HttpHost newTarget = URIUtils.extractHost(uri); - if (newTarget == null) { - throw new ProtocolException("Redirect URI does not specify a valid host name: " + - uri); - } - - // Reset virtual host and auth states if redirecting to another host - if (!currentRoute.getTargetHost().equals(newTarget)) { - final AuthState targetAuthState = context.getTargetAuthState(); - if (targetAuthState != null) { - this.log.log(Level.FINE, "Resetting target auth state"); - targetAuthState.reset(); - } - final AuthState proxyAuthState = context.getProxyAuthState(); - if (proxyAuthState != null) { - final AuthScheme authScheme = proxyAuthState.getAuthScheme(); - if (authScheme != null && authScheme.isConnectionBased()) { - this.log.log(Level.FINE, "Resetting proxy auth state"); - proxyAuthState.reset(); - } - } - } - - currentRoute = this.routePlanner.determineRoute(newTarget, currentRequest, context); - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, "Redirecting to '" + uri + "' via " + currentRoute); - } - EntityUtils.consume(response.getEntity()); - response.close(); - } else { - return response; - } - } catch (final RuntimeException ex) { - response.close(); - throw ex; - } catch (final IOException ex) { - response.close(); - throw ex; - } catch (final HttpException ex) { - // Protocol exception related to a direct. - // The underlying connection may still be salvaged. - try { - EntityUtils.consume(response.getEntity()); - } catch (final IOException ioex) { - this.log.log(Level.FINE, "I/O error while releasing connection", ioex); - } finally { - response.close(); - } - throw ex; - } - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/RequestAbortedException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/RequestAbortedException.java deleted file mode 100644 index 7beeea2d..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/RequestAbortedException.java +++ /dev/null @@ -1,55 +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 com.tracelytics.ext.apache.http.impl.execchain; - -import java.io.InterruptedIOException; - -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * Signals that the request has been aborted. - * - * @since 4.3 - */ -@Immutable -public class RequestAbortedException extends InterruptedIOException { - - private static final long serialVersionUID = 4973849966012490112L; - - public RequestAbortedException(final String message) { - super(message); - } - - public RequestAbortedException(final String message, final Throwable cause) { - super(message); - if (cause != null) { - initCause(cause); - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/RequestEntityProxy.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/RequestEntityProxy.java deleted file mode 100644 index 123ae640..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/RequestEntityProxy.java +++ /dev/null @@ -1,146 +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 com.tracelytics.ext.apache.http.impl.execchain; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpEntityEnclosingRequest; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; - -/** - * A Proxy class for {@link com.tracelytics.ext.apache.http.HttpEntity} enclosed in a request message. - * - * @since 4.3 - */ -@NotThreadSafe -class RequestEntityProxy implements HttpEntity { - - static void enhance(final HttpEntityEnclosingRequest request) { - final HttpEntity entity = request.getEntity(); - if (entity != null && !entity.isRepeatable() && !isEnhanced(entity)) { - request.setEntity(new RequestEntityProxy(entity)); - } - } - - static boolean isEnhanced(final HttpEntity entity) { - return entity instanceof RequestEntityProxy; - } - - static boolean isRepeatable(final HttpRequest request) { - if (request instanceof HttpEntityEnclosingRequest) { - final HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); - if (entity != null) { - if (isEnhanced(entity)) { - final RequestEntityProxy proxy = (RequestEntityProxy) entity; - if (!proxy.isConsumed()) { - return true; - } - } - return entity.isRepeatable(); - } - } - return true; - } - - private final HttpEntity original; - private boolean consumed = false; - - RequestEntityProxy(final HttpEntity original) { - super(); - this.original = original; - } - - public HttpEntity getOriginal() { - return original; - } - - public boolean isConsumed() { - return consumed; - } - - @Override - public boolean isRepeatable() { - return original.isRepeatable(); - } - - @Override - public boolean isChunked() { - return original.isChunked(); - } - - @Override - public long getContentLength() { - return original.getContentLength(); - } - - @Override - public Header getContentType() { - return original.getContentType(); - } - - @Override - public Header getContentEncoding() { - return original.getContentEncoding(); - } - - @Override - public InputStream getContent() throws IOException, IllegalStateException { - return original.getContent(); - } - - @Override - public void writeTo(final OutputStream outstream) throws IOException { - consumed = true; - original.writeTo(outstream); - } - - @Override - public boolean isStreaming() { - return original.isStreaming(); - } - - @Override - @Deprecated - public void consumeContent() throws IOException { - consumed = true; - original.consumeContent(); - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("RequestEntityProxy{"); - sb.append(original); - sb.append('}'); - return sb.toString(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/ResponseEntityProxy.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/ResponseEntityProxy.java deleted file mode 100644 index 144d4a75..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/ResponseEntityProxy.java +++ /dev/null @@ -1,156 +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 com.tracelytics.ext.apache.http.impl.execchain; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.SocketException; - -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.entity.HttpEntityWrapper; - -import com.tracelytics.ext.apache.http.conn.EofSensorInputStream; -import com.tracelytics.ext.apache.http.conn.EofSensorWatcher; - -/** - * 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) { - final HttpEntity entity = response.getEntity(); - if (entity != null && entity.isStreaming() && connHolder != null) { - response.setEntity(new ResponseEntityProxy(entity, connHolder)); - } - } - - ResponseEntityProxy(final HttpEntity entity, final ConnectionHolder connHolder) { - super(entity); - this.connHolder = connHolder; - } - - private void cleanup() { - if (this.connHolder != null) { - this.connHolder.abortConnection(); - } - } - - public void releaseConnection() throws IOException { - if (this.connHolder != null) { - try { - if (this.connHolder.isReusable()) { - this.connHolder.releaseConnection(); - } - } finally { - cleanup(); - } - } - } - - @Override - public boolean isRepeatable() { - return false; - } - - @Override - public InputStream getContent() throws IOException { - return new EofSensorInputStream(this.wrappedEntity.getContent(), this); - } - - @Deprecated - @Override - public void consumeContent() throws IOException { - releaseConnection(); - } - - @Override - public void writeTo(final OutputStream outstream) throws IOException { - try { - this.wrappedEntity.writeTo(outstream); - releaseConnection(); - } finally { - cleanup(); - } - } - - @Override - public boolean eofDetected(final InputStream wrapped) throws IOException { - try { - // there may be some cleanup required, such as - // reading trailers after the response body: - wrapped.close(); - releaseConnection(); - } finally { - cleanup(); - } - return false; - } - - @Override - public boolean streamClosed(final InputStream wrapped) throws IOException { - try { - final boolean open = connHolder != null && !connHolder.isReleased(); - // this assumes that closing the stream will - // consume the remainder of the response body: - try { - wrapped.close(); - releaseConnection(); - } catch (final SocketException ex) { - if (open) { - throw ex; - } - } - } finally { - cleanup(); - } - return false; - } - - @Override - public boolean streamAbort(final InputStream wrapped) throws IOException { - cleanup(); - return false; - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("ResponseEntityProxy{"); - sb.append(wrappedEntity); - sb.append('}'); - return sb.toString(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/RetryExec.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/RetryExec.java deleted file mode 100644 index 523e6823..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/RetryExec.java +++ /dev/null @@ -1,128 +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 com.tracelytics.ext.apache.http.impl.execchain; - -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.NoHttpResponseException; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.client.HttpRequestRetryHandler; -import com.tracelytics.ext.apache.http.client.NonRepeatableRequestException; -import com.tracelytics.ext.apache.http.client.methods.CloseableHttpResponse; -import com.tracelytics.ext.apache.http.client.methods.HttpExecutionAware; -import com.tracelytics.ext.apache.http.client.methods.HttpRequestWrapper; -import com.tracelytics.ext.apache.http.client.protocol.HttpClientContext; -import com.tracelytics.ext.apache.http.conn.routing.HttpRoute; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Request executor in the request execution chain that is responsible - * for making a decision whether a request failed due to an I/O error - * should be re-executed. - *

- * Further responsibilities such as communication with the opposite - * endpoint is delegated to the next executor in the request execution - * chain. - *

- * - * @since 4.3 - */ -@Immutable -public class RetryExec implements ClientExecChain { - - private final Logger log = Logger.getLogger(getClass().getName()); - - private final ClientExecChain requestExecutor; - private final HttpRequestRetryHandler retryHandler; - - public RetryExec( - final ClientExecChain requestExecutor, - final HttpRequestRetryHandler retryHandler) { - Args.notNull(requestExecutor, "HTTP request executor"); - Args.notNull(retryHandler, "HTTP request retry handler"); - this.requestExecutor = requestExecutor; - this.retryHandler = retryHandler; - } - - @Override - public CloseableHttpResponse execute( - final HttpRoute route, - final HttpRequestWrapper 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); - } catch (final IOException ex) { - if (execAware != null && execAware.isAborted()) { - this.log.log(Level.FINE, "Request has been aborted"); - throw ex; - } - if (retryHandler.retryRequest(ex, execCount, context)) { - if (this.log.isLoggable(Level.INFO)) { - this.log.info("I/O exception ("+ ex.getClass().getName() + - ") caught when processing request to " - + route + - ": " - + ex.getMessage()); - } - if (this.log.isLoggable(Level.FINE)) { - this.log.log(Level.FINE, ex.getMessage(), ex); - } - if (!RequestEntityProxy.isRepeatable(request)) { - this.log.log(Level.FINE, "Cannot retry non-repeatable request"); - throw new NonRepeatableRequestException("Cannot retry request " + - "with a non-repeatable request entity", ex); - } - request.setHeaders(origheaders); - if (this.log.isLoggable(Level.INFO)) { - this.log.info("Retrying request to " + route); - } - } else { - if (ex instanceof NoHttpResponseException) { - final NoHttpResponseException updatedex = new NoHttpResponseException( - route.getTargetHost().toHostString() + " failed to respond"); - updatedex.setStackTrace(ex.getStackTrace()); - throw updatedex; - } else { - throw ex; - } - } - } - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/ServiceUnavailableRetryExec.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/ServiceUnavailableRetryExec.java deleted file mode 100644 index b13c786e..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/ServiceUnavailableRetryExec.java +++ /dev/null @@ -1,110 +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 com.tracelytics.ext.apache.http.impl.execchain; - -import java.io.IOException; -import java.io.InterruptedIOException; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.client.ServiceUnavailableRetryStrategy; -import com.tracelytics.ext.apache.http.client.methods.CloseableHttpResponse; -import com.tracelytics.ext.apache.http.client.methods.HttpExecutionAware; -import com.tracelytics.ext.apache.http.client.methods.HttpRequestWrapper; -import com.tracelytics.ext.apache.http.client.protocol.HttpClientContext; -import com.tracelytics.ext.apache.http.conn.routing.HttpRoute; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Request executor in the request execution chain that is responsible - * for making a decision whether a request that received a non-2xx response - * from the target server should be re-executed. - *

- * Further responsibilities such as communication with the opposite - * endpoint is delegated to the next executor in the request execution - * chain. - *

- * - * @since 4.3 - */ -@Immutable -public class ServiceUnavailableRetryExec implements ClientExecChain { - - private final Logger log = Logger.getLogger(getClass().getName()); - - private final ClientExecChain requestExecutor; - private final ServiceUnavailableRetryStrategy retryStrategy; - - public ServiceUnavailableRetryExec( - final ClientExecChain requestExecutor, - final ServiceUnavailableRetryStrategy retryStrategy) { - super(); - Args.notNull(requestExecutor, "HTTP request executor"); - Args.notNull(retryStrategy, "Retry strategy"); - this.requestExecutor = requestExecutor; - this.retryStrategy = retryStrategy; - } - - @Override - public CloseableHttpResponse execute( - final HttpRoute route, - final HttpRequestWrapper 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); - try { - if (this.retryStrategy.retryRequest(response, c, context)) { - response.close(); - final long nextInterval = this.retryStrategy.getRetryInterval(); - if (nextInterval > 0) { - try { - this.log.log(Level.FINEST, "Wait for " + nextInterval); - Thread.sleep(nextInterval); - } catch (final InterruptedException e) { - Thread.currentThread().interrupt(); - throw new InterruptedIOException(); - } - } - request.setHeaders(origheaders); - } else { - return response; - } - } catch (final RuntimeException ex) { - response.close(); - throw ex; - } - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/TunnelRefusedException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/TunnelRefusedException.java deleted file mode 100644 index f4d5c6d8..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/TunnelRefusedException.java +++ /dev/null @@ -1,55 +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 com.tracelytics.ext.apache.http.impl.execchain; - -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * 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; - - public TunnelRefusedException(final String message, final HttpResponse response) { - super(message); - this.response = response; - } - - public HttpResponse getResponse() { - return this.response; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/package-info.java deleted file mode 100644 index c1dc8be8..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/execchain/package-info.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * HTTP request execution chain APIs. - */ -package com.tracelytics.ext.apache.http.impl.execchain; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/AbstractMessageParser.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/AbstractMessageParser.java deleted file mode 100644 index f6ffafbb..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/AbstractMessageParser.java +++ /dev/null @@ -1,285 +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 com.tracelytics.ext.apache.http.impl.io; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpMessage; -import com.tracelytics.ext.apache.http.MessageConstraintException; -import com.tracelytics.ext.apache.http.ParseException; -import com.tracelytics.ext.apache.http.ProtocolException; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.config.MessageConstraints; -import com.tracelytics.ext.apache.http.io.HttpMessageParser; -import com.tracelytics.ext.apache.http.io.SessionInputBuffer; -import com.tracelytics.ext.apache.http.message.BasicLineParser; -import com.tracelytics.ext.apache.http.message.LineParser; -import com.tracelytics.ext.apache.http.params.HttpParamConfig; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -/** - * Abstract base class for HTTP message parsers that obtain input from - * an instance of {@link SessionInputBuffer}. - * - * @since 4.0 - */ -@SuppressWarnings("deprecation") -@NotThreadSafe -public abstract class AbstractMessageParser implements HttpMessageParser { - - private static final int HEAD_LINE = 0; - private static final int HEADERS = 1; - - private final SessionInputBuffer sessionBuffer; - private final MessageConstraints messageConstraints; - private final List headerLines; - protected final LineParser lineParser; - - private int state; - private T message; - - /** - * Creates an instance of AbstractMessageParser. - * - * @param buffer the session input buffer. - * @param parser the line parser. - * @param params HTTP parameters. - * - * @deprecated (4.3) use {@link AbstractMessageParser#AbstractMessageParser(SessionInputBuffer, - * LineParser, MessageConstraints)} - */ - @Deprecated - public AbstractMessageParser( - final SessionInputBuffer buffer, - final LineParser parser, - final HttpParams params) { - super(); - Args.notNull(buffer, "Session input buffer"); - Args.notNull(params, "HTTP parameters"); - this.sessionBuffer = buffer; - this.messageConstraints = HttpParamConfig.getMessageConstraints(params); - this.lineParser = (parser != null) ? parser : BasicLineParser.INSTANCE; - this.headerLines = new ArrayList(); - this.state = HEAD_LINE; - } - - /** - * Creates new instance of AbstractMessageParser. - * - * @param buffer the session input buffer. - * @param lineParser the line parser. If {@code null} {@link BasicLineParser#INSTANCE} - * will be used. - * @param constraints the message constraints. If {@code null} - * {@link MessageConstraints#DEFAULT} will be used. - * - * @since 4.3 - */ - public AbstractMessageParser( - final SessionInputBuffer buffer, - final LineParser lineParser, - final MessageConstraints constraints) { - super(); - this.sessionBuffer = Args.notNull(buffer, "Session input buffer"); - this.lineParser = lineParser != null ? lineParser : BasicLineParser.INSTANCE; - this.messageConstraints = constraints != null ? constraints : MessageConstraints.DEFAULT; - this.headerLines = new ArrayList(); - this.state = HEAD_LINE; - } - - /** - * Parses HTTP headers from the data receiver stream according to the generic - * format as given in Section 3.1 of RFC 822, RFC-2616 Section 4 and 19.3. - * - * @param inbuffer Session input buffer - * @param maxHeaderCount maximum number of headers allowed. If the number - * of headers received from the data stream exceeds maxCount value, an - * IOException will be thrown. Setting this parameter to a negative value - * or zero will disable the check. - * @param maxLineLen maximum number of characters for a header line, - * including the continuation lines. Setting this parameter to a negative - * value or zero will disable the check. - * @return array of HTTP headers - * @param parser line parser to use. Can be {@code null}, in which case - * the default implementation of this interface will be used. - * - * @throws IOException in case of an I/O error - * @throws HttpException in case of HTTP protocol violation - */ - public static Header[] parseHeaders( - final SessionInputBuffer inbuffer, - final int maxHeaderCount, - final int maxLineLen, - final LineParser parser) throws HttpException, IOException { - final List headerLines = new ArrayList(); - return parseHeaders(inbuffer, maxHeaderCount, maxLineLen, - parser != null ? parser : BasicLineParser.INSTANCE, - headerLines); - } - - /** - * Parses HTTP headers from the data receiver stream according to the generic - * format as given in Section 3.1 of RFC 822, RFC-2616 Section 4 and 19.3. - * - * @param inbuffer Session input buffer - * @param maxHeaderCount maximum number of headers allowed. If the number - * of headers received from the data stream exceeds maxCount value, an - * IOException will be thrown. Setting this parameter to a negative value - * or zero will disable the check. - * @param maxLineLen maximum number of characters for a header line, - * including the continuation lines. Setting this parameter to a negative - * value or zero will disable the check. - * @param parser line parser to use. - * @param headerLines List of header lines. This list will be used to store - * intermediate results. This makes it possible to resume parsing of - * headers in case of a {@link java.io.InterruptedIOException}. - * - * @return array of HTTP headers - * - * @throws IOException in case of an I/O error - * @throws HttpException in case of HTTP protocol violation - * - * @since 4.1 - */ - public static Header[] parseHeaders( - final SessionInputBuffer inbuffer, - final int maxHeaderCount, - final int maxLineLen, - final LineParser parser, - final List headerLines) throws HttpException, IOException { - Args.notNull(inbuffer, "Session input buffer"); - Args.notNull(parser, "Line parser"); - Args.notNull(headerLines, "Header line list"); - - CharArrayBuffer current = null; - CharArrayBuffer previous = null; - for (;;) { - if (current == null) { - current = new CharArrayBuffer(64); - } else { - current.clear(); - } - final int l = inbuffer.readLine(current); - if (l == -1 || current.length() < 1) { - break; - } - // Parse the header name and value - // Check for folded headers first - // Detect LWS-char see HTTP/1.0 or HTTP/1.1 Section 2.2 - // discussion on folded headers - if ((current.charAt(0) == ' ' || current.charAt(0) == '\t') && previous != null) { - // we have continuation folded header - // so append value - int i = 0; - while (i < current.length()) { - final char ch = current.charAt(i); - if (ch != ' ' && ch != '\t') { - break; - } - i++; - } - if (maxLineLen > 0 - && previous.length() + 1 + current.length() - i > maxLineLen) { - throw new MessageConstraintException("Maximum line length limit exceeded"); - } - previous.append(' '); - previous.append(current, i, current.length() - i); - } else { - headerLines.add(current); - previous = current; - current = null; - } - if (maxHeaderCount > 0 && headerLines.size() >= maxHeaderCount) { - throw new MessageConstraintException("Maximum header count exceeded"); - } - } - final Header[] headers = new Header[headerLines.size()]; - for (int i = 0; i < headerLines.size(); i++) { - final CharArrayBuffer buffer = headerLines.get(i); - try { - headers[i] = parser.parseHeader(buffer); - } catch (final ParseException ex) { - throw new ProtocolException(ex.getMessage()); - } - } - return headers; - } - - /** - * Subclasses must override this method to generate an instance of - * {@link HttpMessage} based on the initial input from the session buffer. - *

- * Usually this method is expected to read just the very first line or - * the very first valid from the data stream and based on the input generate - * an appropriate instance of {@link HttpMessage}. - * - * @param sessionBuffer the session input buffer. - * @return HTTP message based on the input from the session buffer. - * @throws IOException in case of an I/O error. - * @throws HttpException in case of HTTP protocol violation. - * @throws ParseException in case of a parse error. - */ - protected abstract T parseHead(SessionInputBuffer sessionBuffer) - throws IOException, HttpException, ParseException; - - @Override - public T parse() throws IOException, HttpException { - final int st = this.state; - switch (st) { - case HEAD_LINE: - try { - this.message = parseHead(this.sessionBuffer); - } catch (final ParseException px) { - throw new ProtocolException(px.getMessage(), px); - } - this.state = HEADERS; - //$FALL-THROUGH$ - case HEADERS: - final Header[] headers = AbstractMessageParser.parseHeaders( - this.sessionBuffer, - this.messageConstraints.getMaxHeaderCount(), - this.messageConstraints.getMaxLineLength(), - this.lineParser, - this.headerLines); - this.message.setHeaders(headers); - final T result = this.message; - this.message = null; - this.headerLines.clear(); - this.state = HEAD_LINE; - return result; - default: - throw new IllegalStateException("Inconsistent parser state"); - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/AbstractMessageWriter.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/AbstractMessageWriter.java deleted file mode 100644 index f82aeeab..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/AbstractMessageWriter.java +++ /dev/null @@ -1,120 +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 com.tracelytics.ext.apache.http.impl.io; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HeaderIterator; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpMessage; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.io.HttpMessageWriter; -import com.tracelytics.ext.apache.http.io.SessionOutputBuffer; -import com.tracelytics.ext.apache.http.message.BasicLineFormatter; -import com.tracelytics.ext.apache.http.message.LineFormatter; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -/** - * Abstract base class for HTTP message writers that serialize output to - * an instance of {@link SessionOutputBuffer}. - * - * @since 4.0 - */ -@SuppressWarnings("deprecation") -@NotThreadSafe -public abstract class AbstractMessageWriter implements HttpMessageWriter { - - protected final SessionOutputBuffer sessionBuffer; - protected final CharArrayBuffer lineBuf; - protected final LineFormatter lineFormatter; - - /** - * Creates an instance of AbstractMessageWriter. - * - * @param buffer the session output buffer. - * @param formatter the line formatter. - * @param params HTTP parameters. - * - * @deprecated (4.3) use - * {@link AbstractMessageWriter#AbstractMessageWriter(SessionOutputBuffer, LineFormatter)} - */ - @Deprecated - public AbstractMessageWriter(final SessionOutputBuffer buffer, - final LineFormatter formatter, - final HttpParams params) { - super(); - Args.notNull(buffer, "Session input buffer"); - this.sessionBuffer = buffer; - this.lineBuf = new CharArrayBuffer(128); - this.lineFormatter = (formatter != null) ? formatter : BasicLineFormatter.INSTANCE; - } - - /** - * Creates an instance of AbstractMessageWriter. - * - * @param buffer the session output buffer. - * @param formatter the line formatter If {@code null} {@link BasicLineFormatter#INSTANCE} - * will be used. - * - * @since 4.3 - */ - public AbstractMessageWriter( - final SessionOutputBuffer buffer, - final LineFormatter formatter) { - super(); - this.sessionBuffer = Args.notNull(buffer, "Session input buffer"); - this.lineFormatter = (formatter != null) ? formatter : BasicLineFormatter.INSTANCE; - this.lineBuf = new CharArrayBuffer(128); - } - - /** - * Subclasses must override this method to write out the first header line - * based on the {@link HttpMessage} passed as a parameter. - * - * @param message the message whose first line is to be written out. - * @throws IOException in case of an I/O error. - */ - protected abstract void writeHeadLine(T message) throws IOException; - - @Override - public void write(final T message) throws IOException, HttpException { - Args.notNull(message, "HTTP message"); - writeHeadLine(message); - for (final HeaderIterator it = message.headerIterator(); it.hasNext(); ) { - final Header header = it.nextHeader(); - this.sessionBuffer.writeLine - (lineFormatter.formatHeader(this.lineBuf, header)); - } - this.lineBuf.clear(); - this.sessionBuffer.writeLine(this.lineBuf); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/AbstractSessionInputBuffer.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/AbstractSessionInputBuffer.java deleted file mode 100644 index ca8545f3..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/AbstractSessionInputBuffer.java +++ /dev/null @@ -1,401 +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 com.tracelytics.ext.apache.http.impl.io; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CoderResult; -import java.nio.charset.CodingErrorAction; - -import com.tracelytics.ext.apache.http.Consts; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.io.BufferInfo; -import com.tracelytics.ext.apache.http.io.HttpTransportMetrics; -import com.tracelytics.ext.apache.http.io.SessionInputBuffer; -import com.tracelytics.ext.apache.http.params.CoreConnectionPNames; -import com.tracelytics.ext.apache.http.params.CoreProtocolPNames; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.protocol.HTTP; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.ByteArrayBuffer; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -/** - * Abstract base class for session input buffers that stream data from - * an arbitrary {@link InputStream}. This class buffers input data in - * an internal byte array for optimal input performance. - *

- * {@link #readLine(CharArrayBuffer)} and {@link #readLine()} methods of this - * class treat a lone LF as valid line delimiters in addition to CR-LF required - * by the HTTP specification. - * - * @since 4.0 - * - * @deprecated (4.3) use {@link SessionInputBufferImpl} - */ -@NotThreadSafe -@Deprecated -public abstract class AbstractSessionInputBuffer implements SessionInputBuffer, BufferInfo { - - private InputStream instream; - private byte[] buffer; - private ByteArrayBuffer linebuffer; - private Charset charset; - private boolean ascii; - private int maxLineLen; - private int minChunkLimit; - private HttpTransportMetricsImpl metrics; - private CodingErrorAction onMalformedCharAction; - private CodingErrorAction onUnmappableCharAction; - - private int bufferpos; - private int bufferlen; - private CharsetDecoder decoder; - private CharBuffer cbuf; - - public AbstractSessionInputBuffer() { - } - - /** - * Initializes this session input buffer. - * - * @param instream the source input stream. - * @param buffersize the size of the internal buffer. - * @param params HTTP parameters. - */ - protected void init(final InputStream instream, final int buffersize, final HttpParams params) { - Args.notNull(instream, "Input stream"); - Args.notNegative(buffersize, "Buffer size"); - Args.notNull(params, "HTTP parameters"); - this.instream = instream; - this.buffer = new byte[buffersize]; - this.bufferpos = 0; - this.bufferlen = 0; - this.linebuffer = new ByteArrayBuffer(buffersize); - final String charset = (String) params.getParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET); - this.charset = charset != null ? Charset.forName(charset) : Consts.ASCII; - this.ascii = this.charset.equals(Consts.ASCII); - this.decoder = null; - this.maxLineLen = params.getIntParameter(CoreConnectionPNames.MAX_LINE_LENGTH, -1); - this.minChunkLimit = params.getIntParameter(CoreConnectionPNames.MIN_CHUNK_LIMIT, 512); - this.metrics = createTransportMetrics(); - final CodingErrorAction a1 = (CodingErrorAction) params.getParameter( - CoreProtocolPNames.HTTP_MALFORMED_INPUT_ACTION); - this.onMalformedCharAction = a1 != null ? a1 : CodingErrorAction.REPORT; - final CodingErrorAction a2 = (CodingErrorAction) params.getParameter( - CoreProtocolPNames.HTTP_UNMAPPABLE_INPUT_ACTION); - this.onUnmappableCharAction = a2 != null? a2 : CodingErrorAction.REPORT; - } - - /** - * @since 4.1 - */ - protected HttpTransportMetricsImpl createTransportMetrics() { - return new HttpTransportMetricsImpl(); - } - - /** - * @since 4.1 - */ - public int capacity() { - return this.buffer.length; - } - - /** - * @since 4.1 - */ - public int length() { - return this.bufferlen - this.bufferpos; - } - - /** - * @since 4.1 - */ - public int available() { - return capacity() - length(); - } - - protected int fillBuffer() throws IOException { - // compact the buffer if necessary - if (this.bufferpos > 0) { - final int len = this.bufferlen - this.bufferpos; - if (len > 0) { - System.arraycopy(this.buffer, this.bufferpos, this.buffer, 0, len); - } - this.bufferpos = 0; - this.bufferlen = len; - } - final int l; - final int off = this.bufferlen; - final int len = this.buffer.length - off; - l = this.instream.read(this.buffer, off, len); - if (l == -1) { - return -1; - } else { - this.bufferlen = off + l; - this.metrics.incrementBytesTransferred(l); - return l; - } - } - - protected boolean hasBufferedData() { - return this.bufferpos < this.bufferlen; - } - - public int read() throws IOException { - int noRead; - while (!hasBufferedData()) { - noRead = fillBuffer(); - if (noRead == -1) { - return -1; - } - } - return this.buffer[this.bufferpos++] & 0xff; - } - - public int read(final byte[] b, final int off, final int len) throws IOException { - if (b == null) { - return 0; - } - if (hasBufferedData()) { - final int chunk = Math.min(len, this.bufferlen - this.bufferpos); - System.arraycopy(this.buffer, this.bufferpos, b, off, chunk); - this.bufferpos += chunk; - return chunk; - } - // If the remaining capacity is big enough, read directly from the - // underlying input stream bypassing the buffer. - if (len > this.minChunkLimit) { - final int read = this.instream.read(b, off, len); - if (read > 0) { - this.metrics.incrementBytesTransferred(read); - } - return read; - } else { - // otherwise read to the buffer first - while (!hasBufferedData()) { - final int noRead = fillBuffer(); - if (noRead == -1) { - return -1; - } - } - final int chunk = Math.min(len, this.bufferlen - this.bufferpos); - System.arraycopy(this.buffer, this.bufferpos, b, off, chunk); - this.bufferpos += chunk; - return chunk; - } - } - - public int read(final byte[] b) throws IOException { - if (b == null) { - return 0; - } - return read(b, 0, b.length); - } - - private int locateLF() { - for (int i = this.bufferpos; i < this.bufferlen; i++) { - if (this.buffer[i] == HTTP.LF) { - return i; - } - } - return -1; - } - - /** - * Reads a complete line of characters up to a line delimiter from this - * session buffer into the given line buffer. The number of chars actually - * read is returned as an integer. The line delimiter itself is discarded. - * If no char is available because the end of the stream has been reached, - * the value {@code -1} is returned. This method blocks until input - * data is available, end of file is detected, or an exception is thrown. - *

- * This method treats a lone LF as a valid line delimiters in addition - * to CR-LF required by the HTTP specification. - * - * @param charbuffer the line buffer. - * @return one line of characters - * @exception IOException if an I/O error occurs. - */ - public int readLine(final CharArrayBuffer charbuffer) throws IOException { - Args.notNull(charbuffer, "Char array buffer"); - int noRead = 0; - boolean retry = true; - while (retry) { - // attempt to find end of line (LF) - final int i = locateLF(); - if (i != -1) { - // end of line found. - if (this.linebuffer.isEmpty()) { - // the entire line is preset in the read buffer - return lineFromReadBuffer(charbuffer, i); - } - retry = false; - final int len = i + 1 - this.bufferpos; - this.linebuffer.append(this.buffer, this.bufferpos, len); - this.bufferpos = i + 1; - } else { - // end of line not found - if (hasBufferedData()) { - final int len = this.bufferlen - this.bufferpos; - this.linebuffer.append(this.buffer, this.bufferpos, len); - this.bufferpos = this.bufferlen; - } - noRead = fillBuffer(); - if (noRead == -1) { - retry = false; - } - } - if (this.maxLineLen > 0 && this.linebuffer.length() >= this.maxLineLen) { - throw new IOException("Maximum line length limit exceeded"); - } - } - if (noRead == -1 && this.linebuffer.isEmpty()) { - // indicate the end of stream - return -1; - } - return lineFromLineBuffer(charbuffer); - } - - /** - * Reads a complete line of characters up to a line delimiter from this - * session buffer. The line delimiter itself is discarded. If no char is - * available because the end of the stream has been reached, - * {@code null} is returned. This method blocks until input data is - * available, end of file is detected, or an exception is thrown. - *

- * This method treats a lone LF as a valid line delimiters in addition - * to CR-LF required by the HTTP specification. - * - * @return HTTP line as a string - * @exception IOException if an I/O error occurs. - */ - private int lineFromLineBuffer(final CharArrayBuffer charbuffer) - throws IOException { - // discard LF if found - int len = this.linebuffer.length(); - if (len > 0) { - if (this.linebuffer.byteAt(len - 1) == HTTP.LF) { - len--; - } - // discard CR if found - if (len > 0) { - if (this.linebuffer.byteAt(len - 1) == HTTP.CR) { - len--; - } - } - } - if (this.ascii) { - charbuffer.append(this.linebuffer, 0, len); - } else { - final ByteBuffer bbuf = ByteBuffer.wrap(this.linebuffer.buffer(), 0, len); - len = appendDecoded(charbuffer, bbuf); - } - this.linebuffer.clear(); - return len; - } - - private int lineFromReadBuffer(final CharArrayBuffer charbuffer, final int position) - throws IOException { - final int off = this.bufferpos; - int i = position; - this.bufferpos = i + 1; - if (i > off && this.buffer[i - 1] == HTTP.CR) { - // skip CR if found - i--; - } - int len = i - off; - if (this.ascii) { - charbuffer.append(this.buffer, off, len); - } else { - final ByteBuffer bbuf = ByteBuffer.wrap(this.buffer, off, len); - len = appendDecoded(charbuffer, bbuf); - } - return len; - } - - private int appendDecoded( - final CharArrayBuffer charbuffer, final ByteBuffer bbuf) throws IOException { - if (!bbuf.hasRemaining()) { - return 0; - } - if (this.decoder == null) { - this.decoder = this.charset.newDecoder(); - this.decoder.onMalformedInput(this.onMalformedCharAction); - this.decoder.onUnmappableCharacter(this.onUnmappableCharAction); - } - if (this.cbuf == null) { - this.cbuf = CharBuffer.allocate(1024); - } - this.decoder.reset(); - int len = 0; - while (bbuf.hasRemaining()) { - final CoderResult result = this.decoder.decode(bbuf, this.cbuf, true); - len += handleDecodingResult(result, charbuffer, bbuf); - } - final CoderResult result = this.decoder.flush(this.cbuf); - len += handleDecodingResult(result, charbuffer, bbuf); - this.cbuf.clear(); - return len; - } - - private int handleDecodingResult( - final CoderResult result, - final CharArrayBuffer charbuffer, - final ByteBuffer bbuf) throws IOException { - if (result.isError()) { - result.throwException(); - } - this.cbuf.flip(); - final int len = this.cbuf.remaining(); - while (this.cbuf.hasRemaining()) { - charbuffer.append(this.cbuf.get()); - } - this.cbuf.compact(); - return len; - } - - public String readLine() throws IOException { - final CharArrayBuffer charbuffer = new CharArrayBuffer(64); - final int l = readLine(charbuffer); - if (l != -1) { - return charbuffer.toString(); - } else { - return null; - } - } - - public HttpTransportMetrics getMetrics() { - return this.metrics; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/AbstractSessionOutputBuffer.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/AbstractSessionOutputBuffer.java deleted file mode 100644 index 59515fe8..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/AbstractSessionOutputBuffer.java +++ /dev/null @@ -1,307 +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 com.tracelytics.ext.apache.http.impl.io; - -import java.io.IOException; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.Charset; -import java.nio.charset.CharsetEncoder; -import java.nio.charset.CoderResult; -import java.nio.charset.CodingErrorAction; - -import com.tracelytics.ext.apache.http.Consts; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.io.BufferInfo; -import com.tracelytics.ext.apache.http.io.HttpTransportMetrics; -import com.tracelytics.ext.apache.http.io.SessionOutputBuffer; -import com.tracelytics.ext.apache.http.params.CoreConnectionPNames; -import com.tracelytics.ext.apache.http.params.CoreProtocolPNames; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.protocol.HTTP; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.ByteArrayBuffer; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -/** - * Abstract base class for session output buffers that stream data to - * an arbitrary {@link OutputStream}. This class buffers small chunks of - * output data in an internal byte array for optimal output performance. - *

- * {@link #writeLine(CharArrayBuffer)} and {@link #writeLine(String)} methods - * of this class use CR-LF as a line delimiter. - * - * @since 4.0 - * - * @deprecated (4.3) use {@link SessionOutputBufferImpl} - */ -@NotThreadSafe -@Deprecated -public abstract class AbstractSessionOutputBuffer implements SessionOutputBuffer, BufferInfo { - - private static final byte[] CRLF = new byte[] {HTTP.CR, HTTP.LF}; - - private OutputStream outstream; - private ByteArrayBuffer buffer; - private Charset charset; - private boolean ascii; - private int minChunkLimit; - private HttpTransportMetricsImpl metrics; - private CodingErrorAction onMalformedCharAction; - private CodingErrorAction onUnmappableCharAction; - - private CharsetEncoder encoder; - private ByteBuffer bbuf; - - protected AbstractSessionOutputBuffer( - final OutputStream outstream, - final int buffersize, - final Charset charset, - final int minChunkLimit, - final CodingErrorAction malformedCharAction, - final CodingErrorAction unmappableCharAction) { - super(); - Args.notNull(outstream, "Input stream"); - Args.notNegative(buffersize, "Buffer size"); - this.outstream = outstream; - this.buffer = new ByteArrayBuffer(buffersize); - this.charset = charset != null ? charset : Consts.ASCII; - this.ascii = this.charset.equals(Consts.ASCII); - this.encoder = null; - this.minChunkLimit = minChunkLimit >= 0 ? minChunkLimit : 512; - this.metrics = createTransportMetrics(); - this.onMalformedCharAction = malformedCharAction != null ? malformedCharAction : - CodingErrorAction.REPORT; - this.onUnmappableCharAction = unmappableCharAction != null? unmappableCharAction : - CodingErrorAction.REPORT; - } - - public AbstractSessionOutputBuffer() { - } - - protected void init(final OutputStream outstream, final int buffersize, final HttpParams params) { - Args.notNull(outstream, "Input stream"); - Args.notNegative(buffersize, "Buffer size"); - Args.notNull(params, "HTTP parameters"); - this.outstream = outstream; - this.buffer = new ByteArrayBuffer(buffersize); - final String charset = (String) params.getParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET); - this.charset = charset != null ? Charset.forName(charset) : Consts.ASCII; - this.ascii = this.charset.equals(Consts.ASCII); - this.encoder = null; - this.minChunkLimit = params.getIntParameter(CoreConnectionPNames.MIN_CHUNK_LIMIT, 512); - this.metrics = createTransportMetrics(); - final CodingErrorAction a1 = (CodingErrorAction) params.getParameter( - CoreProtocolPNames.HTTP_MALFORMED_INPUT_ACTION); - this.onMalformedCharAction = a1 != null ? a1 : CodingErrorAction.REPORT; - final CodingErrorAction a2 = (CodingErrorAction) params.getParameter( - CoreProtocolPNames.HTTP_UNMAPPABLE_INPUT_ACTION); - this.onUnmappableCharAction = a2 != null? a2 : CodingErrorAction.REPORT; - } - - /** - * @since 4.1 - */ - protected HttpTransportMetricsImpl createTransportMetrics() { - return new HttpTransportMetricsImpl(); - } - - /** - * @since 4.1 - */ - public int capacity() { - return this.buffer.capacity(); - } - - /** - * @since 4.1 - */ - public int length() { - return this.buffer.length(); - } - - /** - * @since 4.1 - */ - public int available() { - return capacity() - length(); - } - - protected void flushBuffer() throws IOException { - final int len = this.buffer.length(); - if (len > 0) { - this.outstream.write(this.buffer.buffer(), 0, len); - this.buffer.clear(); - this.metrics.incrementBytesTransferred(len); - } - } - - public void flush() throws IOException { - flushBuffer(); - this.outstream.flush(); - } - - public void write(final byte[] b, final int off, final int len) throws IOException { - if (b == null) { - return; - } - // Do not want to buffer large-ish chunks - // if the byte array is larger then MIN_CHUNK_LIMIT - // write it directly to the output stream - if (len > this.minChunkLimit || len > this.buffer.capacity()) { - // flush the buffer - flushBuffer(); - // write directly to the out stream - this.outstream.write(b, off, len); - this.metrics.incrementBytesTransferred(len); - } else { - // Do not let the buffer grow unnecessarily - final int freecapacity = this.buffer.capacity() - this.buffer.length(); - if (len > freecapacity) { - // flush the buffer - flushBuffer(); - } - // buffer - this.buffer.append(b, off, len); - } - } - - public void write(final byte[] b) throws IOException { - if (b == null) { - return; - } - write(b, 0, b.length); - } - - public void write(final int b) throws IOException { - if (this.buffer.isFull()) { - flushBuffer(); - } - this.buffer.append(b); - } - - /** - * Writes characters from the specified string followed by a line delimiter - * to this session buffer. - *

- * This method uses CR-LF as a line delimiter. - * - * @param s the line. - * @exception IOException if an I/O error occurs. - */ - public void writeLine(final String s) throws IOException { - if (s == null) { - return; - } - if (s.length() > 0) { - if (this.ascii) { - for (int i = 0; i < s.length(); i++) { - write(s.charAt(i)); - } - } else { - final CharBuffer cbuf = CharBuffer.wrap(s); - writeEncoded(cbuf); - } - } - write(CRLF); - } - - /** - * Writes characters from the specified char array followed by a line - * delimiter to this session buffer. - *

- * This method uses CR-LF as a line delimiter. - * - * @param charbuffer the buffer containing chars of the line. - * @exception IOException if an I/O error occurs. - */ - public void writeLine(final CharArrayBuffer charbuffer) throws IOException { - if (charbuffer == null) { - return; - } - if (this.ascii) { - int off = 0; - int remaining = charbuffer.length(); - while (remaining > 0) { - int chunk = this.buffer.capacity() - this.buffer.length(); - chunk = Math.min(chunk, remaining); - if (chunk > 0) { - this.buffer.append(charbuffer, off, chunk); - } - if (this.buffer.isFull()) { - flushBuffer(); - } - off += chunk; - remaining -= chunk; - } - } else { - final CharBuffer cbuf = CharBuffer.wrap(charbuffer.buffer(), 0, charbuffer.length()); - writeEncoded(cbuf); - } - write(CRLF); - } - - private void writeEncoded(final CharBuffer cbuf) throws IOException { - if (!cbuf.hasRemaining()) { - return; - } - if (this.encoder == null) { - this.encoder = this.charset.newEncoder(); - this.encoder.onMalformedInput(this.onMalformedCharAction); - this.encoder.onUnmappableCharacter(this.onUnmappableCharAction); - } - if (this.bbuf == null) { - this.bbuf = ByteBuffer.allocate(1024); - } - this.encoder.reset(); - while (cbuf.hasRemaining()) { - final CoderResult result = this.encoder.encode(cbuf, this.bbuf, true); - handleEncodingResult(result); - } - final CoderResult result = this.encoder.flush(this.bbuf); - handleEncodingResult(result); - this.bbuf.clear(); - } - - private void handleEncodingResult(final CoderResult result) throws IOException { - if (result.isError()) { - result.throwException(); - } - this.bbuf.flip(); - while (this.bbuf.hasRemaining()) { - write(this.bbuf.get()); - } - this.bbuf.compact(); - } - - public HttpTransportMetrics getMetrics() { - return this.metrics; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/ChunkedInputStream.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/ChunkedInputStream.java deleted file mode 100644 index 888564ea..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/ChunkedInputStream.java +++ /dev/null @@ -1,330 +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 com.tracelytics.ext.apache.http.impl.io; - -import java.io.IOException; -import java.io.InputStream; - -import com.tracelytics.ext.apache.http.ConnectionClosedException; -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.MalformedChunkCodingException; -import com.tracelytics.ext.apache.http.TruncatedChunkException; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.config.MessageConstraints; -import com.tracelytics.ext.apache.http.io.BufferInfo; -import com.tracelytics.ext.apache.http.io.SessionInputBuffer; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -/** - * Implements chunked transfer coding. The content is received in small chunks. - * Entities transferred using this input stream can be of unlimited length. - * After the stream is read to the end, it provides access to the trailers, - * if any. - *

- * Note that this class NEVER closes the underlying stream, even when close - * gets called. Instead, it will read until the "end" of its chunking on - * close, which allows for the seamless execution of subsequent HTTP 1.1 - * requests, while not requiring the client to remember to read the entire - * contents of the response. - * - * - * @since 4.0 - * - */ -@NotThreadSafe -public class ChunkedInputStream extends InputStream { - - private static final int CHUNK_LEN = 1; - private static final int CHUNK_DATA = 2; - private static final int CHUNK_CRLF = 3; - private static final int CHUNK_INVALID = Integer.MAX_VALUE; - - private static final int BUFFER_SIZE = 2048; - - /** The session input buffer */ - private final SessionInputBuffer in; - private final CharArrayBuffer buffer; - private final MessageConstraints constraints; - - private int state; - - /** The chunk size */ - private int chunkSize; - - /** The current position within the current chunk */ - private int pos; - - /** True if we've reached the end of stream */ - private boolean eof = false; - - /** True if this stream is closed */ - private boolean closed = false; - - private Header[] footers = new Header[] {}; - - /** - * Wraps session input stream and reads chunk coded input. - * - * @param in The session input buffer - * @param constraints Message constraints. If {@code null} - * {@link MessageConstraints#DEFAULT} will be used. - * - * @since 4.4 - */ - public ChunkedInputStream(final SessionInputBuffer in, final MessageConstraints constraints) { - super(); - this.in = Args.notNull(in, "Session input buffer"); - this.pos = 0; - this.buffer = new CharArrayBuffer(16); - this.constraints = constraints != null ? constraints : MessageConstraints.DEFAULT; - this.state = CHUNK_LEN; - } - - /** - * Wraps session input stream and reads chunk coded input. - * - * @param in The session input buffer - */ - public ChunkedInputStream(final SessionInputBuffer in) { - this(in, null); - } - - @Override - public int available() throws IOException { - if (this.in instanceof BufferInfo) { - final int len = ((BufferInfo) this.in).length(); - return Math.min(len, this.chunkSize - this.pos); - } else { - return 0; - } - } - - /** - *

Returns all the data in a chunked stream in coalesced form. A chunk - * is followed by a CRLF. The method returns -1 as soon as a chunksize of 0 - * is detected.

- * - *

Trailer headers are read automatically at the end of the stream and - * can be obtained with the getResponseFooters() method.

- * - * @return -1 of the end of the stream has been reached or the next data - * byte - * @throws IOException in case of an I/O error - */ - @Override - public int read() throws IOException { - if (this.closed) { - throw new IOException("Attempted read from closed stream."); - } - if (this.eof) { - return -1; - } - if (state != CHUNK_DATA) { - nextChunk(); - if (this.eof) { - return -1; - } - } - final int b = in.read(); - if (b != -1) { - pos++; - if (pos >= chunkSize) { - state = CHUNK_CRLF; - } - } - return b; - } - - /** - * Read some bytes from the stream. - * @param b The byte array that will hold the contents from the stream. - * @param off The offset into the byte array at which bytes will start to be - * placed. - * @param len the maximum number of bytes that can be returned. - * @return The number of bytes returned or -1 if the end of stream has been - * reached. - * @throws IOException in case of an I/O error - */ - @Override - public int read (final byte[] b, final int off, final int len) throws IOException { - - if (closed) { - throw new IOException("Attempted read from closed stream."); - } - - if (eof) { - return -1; - } - if (state != CHUNK_DATA) { - nextChunk(); - if (eof) { - return -1; - } - } - final int bytesRead = in.read(b, off, Math.min(len, chunkSize - pos)); - if (bytesRead != -1) { - pos += bytesRead; - if (pos >= chunkSize) { - state = CHUNK_CRLF; - } - return bytesRead; - } else { - eof = true; - throw new TruncatedChunkException("Truncated chunk " - + "( expected size: " + chunkSize - + "; actual size: " + pos + ")"); - } - } - - /** - * Read some bytes from the stream. - * @param b The byte array that will hold the contents from the stream. - * @return The number of bytes returned or -1 if the end of stream has been - * reached. - * @throws IOException in case of an I/O error - */ - @Override - public int read (final byte[] b) throws IOException { - return read(b, 0, b.length); - } - - /** - * Read the next chunk. - * @throws IOException in case of an I/O error - */ - private void nextChunk() throws IOException { - if (state == CHUNK_INVALID) { - throw new MalformedChunkCodingException("Corrupt data stream"); - } - try { - chunkSize = getChunkSize(); - if (chunkSize < 0) { - throw new MalformedChunkCodingException("Negative chunk size"); - } - state = CHUNK_DATA; - pos = 0; - if (chunkSize == 0) { - eof = true; - parseTrailerHeaders(); - } - } catch (MalformedChunkCodingException ex) { - state = CHUNK_INVALID; - throw ex; - } - } - - /** - * Expects the stream to start with a chunksize in hex with optional - * comments after a semicolon. The line must end with a CRLF: "a3; some - * comment\r\n" Positions the stream at the start of the next line. - */ - private int getChunkSize() throws IOException { - final int st = this.state; - switch (st) { - case CHUNK_CRLF: - this.buffer.clear(); - final int bytesRead1 = this.in.readLine(this.buffer); - if (bytesRead1 == -1) { - throw new MalformedChunkCodingException( - "CRLF expected at end of chunk"); - } - if (!this.buffer.isEmpty()) { - throw new MalformedChunkCodingException( - "Unexpected content at the end of chunk"); - } - state = CHUNK_LEN; - //$FALL-THROUGH$ - case CHUNK_LEN: - this.buffer.clear(); - final int bytesRead2 = this.in.readLine(this.buffer); - if (bytesRead2 == -1) { - throw new ConnectionClosedException("Premature end of chunk coded message body: " + - "closing chunk expected"); - } - int separator = this.buffer.indexOf(';'); - if (separator < 0) { - separator = this.buffer.length(); - } - try { - return Integer.parseInt(this.buffer.substringTrimmed(0, separator), 16); - } catch (final NumberFormatException e) { - throw new MalformedChunkCodingException("Bad chunk header"); - } - default: - throw new IllegalStateException("Inconsistent codec state"); - } - } - - /** - * Reads and stores the Trailer headers. - * @throws IOException in case of an I/O error - */ - private void parseTrailerHeaders() throws IOException { - try { - this.footers = AbstractMessageParser.parseHeaders(in, - constraints.getMaxHeaderCount(), - constraints.getMaxLineLength(), - null); - } catch (final HttpException ex) { - final IOException ioe = new MalformedChunkCodingException("Invalid footer: " - + ex.getMessage()); - ioe.initCause(ex); - throw ioe; - } - } - - /** - * Upon close, this reads the remainder of the chunked message, - * leaving the underlying socket at a position to start reading the - * next response without scanning. - * @throws IOException in case of an I/O error - */ - @Override - public void close() throws IOException { - if (!closed) { - try { - if (!eof && state != CHUNK_INVALID) { - // read and discard the remainder of the message - final byte buff[] = new byte[BUFFER_SIZE]; - while (read(buff) >= 0) { - } - } - } finally { - eof = true; - closed = true; - } - } - } - - public Header[] getFooters() { - return this.footers.clone(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/ChunkedOutputStream.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/ChunkedOutputStream.java deleted file mode 100644 index 40b9f97d..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/ChunkedOutputStream.java +++ /dev/null @@ -1,208 +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 com.tracelytics.ext.apache.http.impl.io; - -import java.io.IOException; -import java.io.OutputStream; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.io.SessionOutputBuffer; - -/** - * Implements chunked transfer coding. The content is sent in small chunks. - * Entities transferred using this output stream can be of unlimited length. - * Writes are buffered to an internal buffer (2048 default size). - *

- * Note that this class NEVER closes the underlying stream, even when close - * gets called. Instead, the stream will be marked as closed and no further - * output will be permitted. - * - * - * @since 4.0 - */ -@NotThreadSafe -public class ChunkedOutputStream extends OutputStream { - - // ----------------------------------------------------- Instance Variables - private final SessionOutputBuffer out; - - private final byte[] cache; - - private int cachePosition = 0; - - private boolean wroteLastChunk = false; - - /** True if the stream is closed. */ - private boolean closed = false; - - /** - * Wraps a session output buffer and chunk-encodes the output. - * - * @param out The session output buffer - * @param bufferSize The minimum chunk size (excluding last chunk) - * @throws IOException not thrown - * - * @deprecated (4.3) use {@link ChunkedOutputStream#ChunkedOutputStream(int, SessionOutputBuffer)} - */ - @Deprecated - public ChunkedOutputStream(final SessionOutputBuffer out, final int bufferSize) - throws IOException { - this(bufferSize, out); - } - - /** - * Wraps a session output buffer and chunks the output. The default buffer - * size of 2048 was chosen because the chunk overhead is less than 0.5% - * - * @param out the output buffer to wrap - * @throws IOException not thrown - * - * @deprecated (4.3) use {@link ChunkedOutputStream#ChunkedOutputStream(int, SessionOutputBuffer)} - */ - @Deprecated - public ChunkedOutputStream(final SessionOutputBuffer out) - throws IOException { - this(2048, out); - } - - /** - * Wraps a session output buffer and chunk-encodes the output. - * - * @param bufferSize The minimum chunk size (excluding last chunk) - * @param out The session output buffer - */ - public ChunkedOutputStream(final int bufferSize, final SessionOutputBuffer out) { - super(); - this.cache = new byte[bufferSize]; - this.out = out; - } - - /** - * Writes the cache out onto the underlying stream - */ - protected void flushCache() throws IOException { - if (this.cachePosition > 0) { - this.out.writeLine(Integer.toHexString(this.cachePosition)); - this.out.write(this.cache, 0, this.cachePosition); - this.out.writeLine(""); - this.cachePosition = 0; - } - } - - /** - * Writes the cache and bufferToAppend to the underlying stream - * as one large chunk - */ - protected void flushCacheWithAppend(final byte bufferToAppend[], final int off, final int len) throws IOException { - this.out.writeLine(Integer.toHexString(this.cachePosition + len)); - this.out.write(this.cache, 0, this.cachePosition); - this.out.write(bufferToAppend, off, len); - this.out.writeLine(""); - this.cachePosition = 0; - } - - protected void writeClosingChunk() throws IOException { - // Write the final chunk. - this.out.writeLine("0"); - this.out.writeLine(""); - } - - // ----------------------------------------------------------- Public Methods - /** - * Must be called to ensure the internal cache is flushed and the closing - * chunk is written. - * @throws IOException in case of an I/O error - */ - public void finish() throws IOException { - if (!this.wroteLastChunk) { - flushCache(); - writeClosingChunk(); - this.wroteLastChunk = true; - } - } - - // -------------------------------------------- OutputStream Methods - @Override - public void write(final int b) throws IOException { - if (this.closed) { - throw new IOException("Attempted write to closed stream."); - } - this.cache[this.cachePosition] = (byte) b; - this.cachePosition++; - if (this.cachePosition == this.cache.length) { - flushCache(); - } - } - - /** - * Writes the array. If the array does not fit within the buffer, it is - * not split, but rather written out as one large chunk. - */ - @Override - public void write(final byte b[]) throws IOException { - write(b, 0, b.length); - } - - /** - * Writes the array. If the array does not fit within the buffer, it is - * not split, but rather written out as one large chunk. - */ - @Override - public void write(final byte src[], final int off, final int len) throws IOException { - if (this.closed) { - throw new IOException("Attempted write to closed stream."); - } - if (len >= this.cache.length - this.cachePosition) { - flushCacheWithAppend(src, off, len); - } else { - System.arraycopy(src, off, cache, this.cachePosition, len); - this.cachePosition += len; - } - } - - /** - * Flushes the content buffer and the underlying stream. - */ - @Override - public void flush() throws IOException { - flushCache(); - this.out.flush(); - } - - /** - * Finishes writing to the underlying stream, but does NOT close the underlying stream. - */ - @Override - public void close() throws IOException { - if (!this.closed) { - this.closed = true; - finish(); - this.out.flush(); - } - } -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/ContentLengthInputStream.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/ContentLengthInputStream.java deleted file mode 100644 index 33ec27f0..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/ContentLengthInputStream.java +++ /dev/null @@ -1,232 +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 com.tracelytics.ext.apache.http.impl.io; - -import java.io.IOException; -import java.io.InputStream; - -import com.tracelytics.ext.apache.http.ConnectionClosedException; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.io.BufferInfo; -import com.tracelytics.ext.apache.http.io.SessionInputBuffer; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Input stream that cuts off after a defined number of bytes. This class - * is used to receive content of HTTP messages where the end of the content - * entity is determined by the value of the {@code Content-Length header}. - * Entities transferred using this stream can be maximum {@link Long#MAX_VALUE} - * long. - *

- * Note that this class NEVER closes the underlying stream, even when close - * gets called. Instead, it will read until the "end" of its limit on - * close, which allows for the seamless execution of subsequent HTTP 1.1 - * requests, while not requiring the client to remember to read the entire - * contents of the response. - * - * - * @since 4.0 - */ -@NotThreadSafe -public class ContentLengthInputStream extends InputStream { - - private static final int BUFFER_SIZE = 2048; - /** - * The maximum number of bytes that can be read from the stream. Subsequent - * read operations will return -1. - */ - private final long contentLength; - - /** The current position */ - private long pos = 0; - - /** True if the stream is closed. */ - private boolean closed = false; - - /** - * Wrapped input stream that all calls are delegated to. - */ - private SessionInputBuffer in = null; - - /** - * Wraps a session input buffer and cuts off output after a defined number - * of bytes. - * - * @param in The session input buffer - * @param contentLength The maximum number of bytes that can be read from - * the stream. Subsequent read operations will return -1. - */ - public ContentLengthInputStream(final SessionInputBuffer in, final long contentLength) { - super(); - this.in = Args.notNull(in, "Session input buffer"); - this.contentLength = Args.notNegative(contentLength, "Content length"); - } - - /** - *

Reads until the end of the known length of content.

- * - *

Does not close the underlying socket input, but instead leaves it - * primed to parse the next response.

- * @throws IOException If an IO problem occurs. - */ - @Override - public void close() throws IOException { - if (!closed) { - try { - if (pos < contentLength) { - final byte buffer[] = new byte[BUFFER_SIZE]; - while (read(buffer) >= 0) { - } - } - } finally { - // close after above so that we don't throw an exception trying - // to read after closed! - closed = true; - } - } - } - - @Override - public int available() throws IOException { - if (this.in instanceof BufferInfo) { - final int len = ((BufferInfo) this.in).length(); - return Math.min(len, (int) (this.contentLength - this.pos)); - } else { - return 0; - } - } - - /** - * Read the next byte from the stream - * @return The next byte or -1 if the end of stream has been reached. - * @throws IOException If an IO problem occurs - * @see java.io.InputStream#read() - */ - @Override - public int read() throws IOException { - if (closed) { - throw new IOException("Attempted read from closed stream."); - } - - if (pos >= contentLength) { - return -1; - } - final int b = this.in.read(); - if (b == -1) { - if (pos < contentLength) { - throw new ConnectionClosedException( - "Premature end of Content-Length delimited message body (expected: " - + contentLength + "; received: " + pos); - } - } else { - pos++; - } - return b; - } - - /** - * Does standard {@link InputStream#read(byte[], int, int)} behavior, but - * also notifies the watcher when the contents have been consumed. - * - * @param b The byte array to fill. - * @param off Start filling at this position. - * @param len The number of bytes to attempt to read. - * @return The number of bytes read, or -1 if the end of content has been - * reached. - * - * @throws java.io.IOException Should an error occur on the wrapped stream. - */ - @Override - public int read (final byte[] b, final int off, final int len) throws java.io.IOException { - if (closed) { - throw new IOException("Attempted read from closed stream."); - } - - if (pos >= contentLength) { - return -1; - } - - int chunk = len; - if (pos + len > contentLength) { - chunk = (int) (contentLength - pos); - } - final int count = this.in.read(b, off, chunk); - if (count == -1 && pos < contentLength) { - throw new ConnectionClosedException( - "Premature end of Content-Length delimited message body (expected: " - + contentLength + "; received: " + pos); - } - if (count > 0) { - pos += count; - } - return count; - } - - - /** - * Read more bytes from the stream. - * @param b The byte array to put the new data in. - * @return The number of bytes read into the buffer. - * @throws IOException If an IO problem occurs - * @see java.io.InputStream#read(byte[]) - */ - @Override - public int read(final byte[] b) throws IOException { - return read(b, 0, b.length); - } - - /** - * Skips and discards a number of bytes from the input stream. - * @param n The number of bytes to skip. - * @return The actual number of bytes skipped. ≤ 0 if no bytes - * are skipped. - * @throws IOException If an error occurs while skipping bytes. - * @see InputStream#skip(long) - */ - @Override - public long skip(final long n) throws IOException { - if (n <= 0) { - return 0; - } - final byte[] buffer = new byte[BUFFER_SIZE]; - // make sure we don't skip more bytes than are - // still available - long remaining = Math.min(n, this.contentLength - this.pos); - // skip and keep track of the bytes actually skipped - long count = 0; - while (remaining > 0) { - final int l = read(buffer, 0, (int)Math.min(BUFFER_SIZE, remaining)); - if (l == -1) { - break; - } - count += l; - remaining -= l; - } - return count; - } -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/ContentLengthOutputStream.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/ContentLengthOutputStream.java deleted file mode 100644 index 92448256..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/ContentLengthOutputStream.java +++ /dev/null @@ -1,136 +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 com.tracelytics.ext.apache.http.impl.io; - -import java.io.IOException; -import java.io.OutputStream; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.io.SessionOutputBuffer; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Output stream that cuts off after a defined number of bytes. This class - * is used to send content of HTTP messages where the end of the content entity - * is determined by the value of the {@code Content-Length header}. - * Entities transferred using this stream can be maximum {@link Long#MAX_VALUE} - * long. - *

- * Note that this class NEVER closes the underlying stream, even when close - * gets called. Instead, the stream will be marked as closed and no further - * output will be permitted. - * - * @since 4.0 - */ -@NotThreadSafe -public class ContentLengthOutputStream extends OutputStream { - - /** - * Wrapped session output buffer. - */ - private final SessionOutputBuffer out; - - /** - * The maximum number of bytes that can be written the stream. Subsequent - * write operations will be ignored. - */ - private final long contentLength; - - /** Total bytes written */ - private long total = 0; - - /** True if the stream is closed. */ - private boolean closed = false; - - /** - * Wraps a session output buffer and cuts off output after a defined number - * of bytes. - * - * @param out The session output buffer - * @param contentLength The maximum number of bytes that can be written to - * the stream. Subsequent write operations will be ignored. - * - * @since 4.0 - */ - public ContentLengthOutputStream(final SessionOutputBuffer out, final long contentLength) { - super(); - this.out = Args.notNull(out, "Session output buffer"); - this.contentLength = Args.notNegative(contentLength, "Content length"); - } - - /** - *

Does not close the underlying socket output.

- * - * @throws IOException If an I/O problem occurs. - */ - @Override - public void close() throws IOException { - if (!this.closed) { - this.closed = true; - this.out.flush(); - } - } - - @Override - public void flush() throws IOException { - this.out.flush(); - } - - @Override - public void write(final byte[] b, final int off, final int len) throws IOException { - if (this.closed) { - throw new IOException("Attempted write to closed stream."); - } - if (this.total < this.contentLength) { - final long max = this.contentLength - this.total; - int chunk = len; - if (chunk > max) { - chunk = (int) max; - } - this.out.write(b, off, chunk); - this.total += chunk; - } - } - - @Override - public void write(final byte[] b) throws IOException { - write(b, 0, b.length); - } - - @Override - public void write(final int b) throws IOException { - if (this.closed) { - throw new IOException("Attempted write to closed stream."); - } - if (this.total < this.contentLength) { - this.out.write(b); - this.total++; - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpRequestParser.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpRequestParser.java deleted file mode 100644 index f92e150f..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpRequestParser.java +++ /dev/null @@ -1,140 +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 com.tracelytics.ext.apache.http.impl.io; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.ConnectionClosedException; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpRequestFactory; -import com.tracelytics.ext.apache.http.ParseException; -import com.tracelytics.ext.apache.http.RequestLine; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.config.MessageConstraints; -import com.tracelytics.ext.apache.http.impl.DefaultHttpRequestFactory; -import com.tracelytics.ext.apache.http.io.SessionInputBuffer; -import com.tracelytics.ext.apache.http.message.LineParser; -import com.tracelytics.ext.apache.http.message.ParserCursor; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -/** - * HTTP request parser that obtain its input from an instance - * of {@link SessionInputBuffer}. - * - * @since 4.2 - */ -@SuppressWarnings("deprecation") -@NotThreadSafe -public class DefaultHttpRequestParser extends AbstractMessageParser { - - private final HttpRequestFactory requestFactory; - private final CharArrayBuffer lineBuf; - - /** - * Creates an instance of this class. - * - * @param buffer the session input buffer. - * @param lineParser the line parser. - * @param requestFactory the factory to use to create - * {@link HttpRequest}s. - * @param params HTTP parameters. - * - * @deprecated (4.3) use - * {@link DefaultHttpRequestParser#DefaultHttpRequestParser(SessionInputBuffer, LineParser, - * HttpRequestFactory, MessageConstraints)} - */ - @Deprecated - public DefaultHttpRequestParser( - final SessionInputBuffer buffer, - final LineParser lineParser, - final HttpRequestFactory requestFactory, - final HttpParams params) { - super(buffer, lineParser, params); - this.requestFactory = Args.notNull(requestFactory, "Request factory"); - this.lineBuf = new CharArrayBuffer(128); - } - - /** - * Creates new instance of DefaultHttpRequestParser. - * - * @param buffer the session input buffer. - * @param lineParser the line parser. If {@code null} - * {@link com.tracelytics.ext.apache.http.message.BasicLineParser#INSTANCE} will be used. - * @param requestFactory the response factory. If {@code null} - * {@link DefaultHttpRequestFactory#INSTANCE} will be used. - * @param constraints the message constraints. If {@code null} - * {@link MessageConstraints#DEFAULT} will be used. - * - * @since 4.3 - */ - public DefaultHttpRequestParser( - final SessionInputBuffer buffer, - final LineParser lineParser, - final HttpRequestFactory requestFactory, - final MessageConstraints constraints) { - super(buffer, lineParser, constraints); - this.requestFactory = requestFactory != null ? requestFactory : - DefaultHttpRequestFactory.INSTANCE; - this.lineBuf = new CharArrayBuffer(128); - } - - /** - * @since 4.3 - */ - public DefaultHttpRequestParser( - final SessionInputBuffer buffer, - final MessageConstraints constraints) { - this(buffer, null, null, constraints); - } - - /** - * @since 4.3 - */ - public DefaultHttpRequestParser(final SessionInputBuffer buffer) { - this(buffer, null, null, MessageConstraints.DEFAULT); - } - - @Override - protected HttpRequest parseHead( - final SessionInputBuffer sessionBuffer) - throws IOException, HttpException, ParseException { - - this.lineBuf.clear(); - final int i = sessionBuffer.readLine(this.lineBuf); - if (i == -1) { - throw new ConnectionClosedException("Client closed connection"); - } - final ParserCursor cursor = new ParserCursor(0, this.lineBuf.length()); - final RequestLine requestline = this.lineParser.parseRequestLine(this.lineBuf, cursor); - return this.requestFactory.newHttpRequest(requestline); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpRequestParserFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpRequestParserFactory.java deleted file mode 100644 index 321874c6..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpRequestParserFactory.java +++ /dev/null @@ -1,72 +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 com.tracelytics.ext.apache.http.impl.io; - -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpRequestFactory; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.config.MessageConstraints; -import com.tracelytics.ext.apache.http.impl.DefaultHttpRequestFactory; -import com.tracelytics.ext.apache.http.io.HttpMessageParser; -import com.tracelytics.ext.apache.http.io.HttpMessageParserFactory; -import com.tracelytics.ext.apache.http.io.SessionInputBuffer; -import com.tracelytics.ext.apache.http.message.BasicLineParser; -import com.tracelytics.ext.apache.http.message.LineParser; - -/** - * Default factory for request message parsers. - * - * @since 4.3 - */ -@Immutable -public class DefaultHttpRequestParserFactory implements HttpMessageParserFactory { - - public static final DefaultHttpRequestParserFactory INSTANCE = new DefaultHttpRequestParserFactory(); - - private final LineParser lineParser; - private final HttpRequestFactory requestFactory; - - public DefaultHttpRequestParserFactory(final LineParser lineParser, - final HttpRequestFactory requestFactory) { - super(); - this.lineParser = lineParser != null ? lineParser : BasicLineParser.INSTANCE; - this.requestFactory = requestFactory != null ? requestFactory - : DefaultHttpRequestFactory.INSTANCE; - } - - public DefaultHttpRequestParserFactory() { - this(null, null); - } - - @Override - public HttpMessageParser create(final SessionInputBuffer buffer, - final MessageConstraints constraints) { - return new DefaultHttpRequestParser(buffer, lineParser, requestFactory, constraints); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpRequestWriter.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpRequestWriter.java deleted file mode 100644 index a7f6cbae..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpRequestWriter.java +++ /dev/null @@ -1,69 +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 com.tracelytics.ext.apache.http.impl.io; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.io.SessionOutputBuffer; -import com.tracelytics.ext.apache.http.message.LineFormatter; - -/** - * HTTP request writer that serializes its output to an instance of {@link SessionOutputBuffer}. - * - * @since 4.3 - */ -@NotThreadSafe -public class DefaultHttpRequestWriter extends AbstractMessageWriter { - - /** - * Creates an instance of DefaultHttpRequestWriter. - * - * @param buffer the session output buffer. - * @param formatter the line formatter If {@code null} - * {@link com.tracelytics.ext.apache.http.message.BasicLineFormatter#INSTANCE} - * will be used. - */ - public DefaultHttpRequestWriter( - final SessionOutputBuffer buffer, - final LineFormatter formatter) { - super(buffer, formatter); - } - - public DefaultHttpRequestWriter(final SessionOutputBuffer buffer) { - this(buffer, null); - } - - @Override - protected void writeHeadLine(final HttpRequest message) throws IOException { - lineFormatter.formatRequestLine(this.lineBuf, message.getRequestLine()); - this.sessionBuffer.writeLine(this.lineBuf); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpRequestWriterFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpRequestWriterFactory.java deleted file mode 100644 index 91e9d294..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpRequestWriterFactory.java +++ /dev/null @@ -1,64 +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 com.tracelytics.ext.apache.http.impl.io; - -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.io.HttpMessageWriter; -import com.tracelytics.ext.apache.http.io.HttpMessageWriterFactory; -import com.tracelytics.ext.apache.http.io.SessionOutputBuffer; -import com.tracelytics.ext.apache.http.message.BasicLineFormatter; -import com.tracelytics.ext.apache.http.message.LineFormatter; - -/** - * Default factory for request message writers. - * - * @since 4.3 - */ -@Immutable -public class DefaultHttpRequestWriterFactory implements HttpMessageWriterFactory { - - public static final DefaultHttpRequestWriterFactory INSTANCE = new DefaultHttpRequestWriterFactory(); - - private final LineFormatter lineFormatter; - - public DefaultHttpRequestWriterFactory(final LineFormatter lineFormatter) { - super(); - this.lineFormatter = lineFormatter != null ? lineFormatter : BasicLineFormatter.INSTANCE; - } - - public DefaultHttpRequestWriterFactory() { - this(null); - } - - @Override - public HttpMessageWriter create(final SessionOutputBuffer buffer) { - return new DefaultHttpRequestWriter(buffer, lineFormatter); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpResponseParser.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpResponseParser.java deleted file mode 100644 index d72eb8b9..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpResponseParser.java +++ /dev/null @@ -1,141 +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 com.tracelytics.ext.apache.http.impl.io; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.HttpResponseFactory; -import com.tracelytics.ext.apache.http.NoHttpResponseException; -import com.tracelytics.ext.apache.http.ParseException; -import com.tracelytics.ext.apache.http.StatusLine; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.config.MessageConstraints; -import com.tracelytics.ext.apache.http.impl.DefaultHttpResponseFactory; -import com.tracelytics.ext.apache.http.io.SessionInputBuffer; -import com.tracelytics.ext.apache.http.message.LineParser; -import com.tracelytics.ext.apache.http.message.ParserCursor; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -/** - * HTTP response parser that obtain its input from an instance - * of {@link SessionInputBuffer}. - * - * @since 4.2 - */ -@SuppressWarnings("deprecation") -@NotThreadSafe -public class DefaultHttpResponseParser extends AbstractMessageParser { - - private final HttpResponseFactory responseFactory; - private final CharArrayBuffer lineBuf; - - /** - * Creates an instance of this class. - * - * @param buffer the session input buffer. - * @param lineParser the line parser. - * @param responseFactory the factory to use to create - * {@link HttpResponse}s. - * @param params HTTP parameters. - * - * @deprecated (4.3) use - * {@link DefaultHttpResponseParser#DefaultHttpResponseParser(SessionInputBuffer, LineParser, - * HttpResponseFactory, MessageConstraints)} - */ - @Deprecated - public DefaultHttpResponseParser( - final SessionInputBuffer buffer, - final LineParser lineParser, - final HttpResponseFactory responseFactory, - final HttpParams params) { - super(buffer, lineParser, params); - this.responseFactory = Args.notNull(responseFactory, "Response factory"); - this.lineBuf = new CharArrayBuffer(128); - } - - /** - * Creates new instance of DefaultHttpResponseParser. - * - * @param buffer the session input buffer. - * @param lineParser the line parser. If {@code null} - * {@link com.tracelytics.ext.apache.http.message.BasicLineParser#INSTANCE} will be used - * @param responseFactory the response factory. If {@code null} - * {@link DefaultHttpResponseFactory#INSTANCE} will be used. - * @param constraints the message constraints. If {@code null} - * {@link MessageConstraints#DEFAULT} will be used. - * - * @since 4.3 - */ - public DefaultHttpResponseParser( - final SessionInputBuffer buffer, - final LineParser lineParser, - final HttpResponseFactory responseFactory, - final MessageConstraints constraints) { - super(buffer, lineParser, constraints); - this.responseFactory = responseFactory != null ? responseFactory : - DefaultHttpResponseFactory.INSTANCE; - this.lineBuf = new CharArrayBuffer(128); - } - - /** - * @since 4.3 - */ - public DefaultHttpResponseParser( - final SessionInputBuffer buffer, - final MessageConstraints constraints) { - this(buffer, null, null, constraints); - } - - /** - * @since 4.3 - */ - public DefaultHttpResponseParser(final SessionInputBuffer buffer) { - this(buffer, null, null, MessageConstraints.DEFAULT); - } - - @Override - protected HttpResponse parseHead( - final SessionInputBuffer sessionBuffer) - throws IOException, HttpException, ParseException { - - this.lineBuf.clear(); - final int i = sessionBuffer.readLine(this.lineBuf); - if (i == -1) { - throw new NoHttpResponseException("The target server failed to respond"); - } - //create the status line from the status string - final ParserCursor cursor = new ParserCursor(0, this.lineBuf.length()); - final StatusLine statusline = lineParser.parseStatusLine(this.lineBuf, cursor); - return this.responseFactory.newHttpResponse(statusline, null); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpResponseParserFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpResponseParserFactory.java deleted file mode 100644 index 63d3bdea..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpResponseParserFactory.java +++ /dev/null @@ -1,72 +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 com.tracelytics.ext.apache.http.impl.io; - -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.HttpResponseFactory; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.config.MessageConstraints; -import com.tracelytics.ext.apache.http.impl.DefaultHttpResponseFactory; -import com.tracelytics.ext.apache.http.io.HttpMessageParser; -import com.tracelytics.ext.apache.http.io.HttpMessageParserFactory; -import com.tracelytics.ext.apache.http.io.SessionInputBuffer; -import com.tracelytics.ext.apache.http.message.BasicLineParser; -import com.tracelytics.ext.apache.http.message.LineParser; - -/** - * Default factory for response message parsers. - * - * @since 4.3 - */ -@Immutable -public class DefaultHttpResponseParserFactory implements HttpMessageParserFactory { - - public static final DefaultHttpResponseParserFactory INSTANCE = new DefaultHttpResponseParserFactory(); - - private final LineParser lineParser; - private final HttpResponseFactory responseFactory; - - public DefaultHttpResponseParserFactory(final LineParser lineParser, - final HttpResponseFactory responseFactory) { - super(); - this.lineParser = lineParser != null ? lineParser : BasicLineParser.INSTANCE; - this.responseFactory = responseFactory != null ? responseFactory - : DefaultHttpResponseFactory.INSTANCE; - } - - public DefaultHttpResponseParserFactory() { - this(null, null); - } - - @Override - public HttpMessageParser create(final SessionInputBuffer buffer, - final MessageConstraints constraints) { - return new DefaultHttpResponseParser(buffer, lineParser, responseFactory, constraints); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpResponseWriter.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpResponseWriter.java deleted file mode 100644 index 624ee065..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpResponseWriter.java +++ /dev/null @@ -1,69 +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 com.tracelytics.ext.apache.http.impl.io; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.io.SessionOutputBuffer; -import com.tracelytics.ext.apache.http.message.LineFormatter; - -/** - * HTTP response writer that serializes its output to an instance of {@link SessionOutputBuffer}. - * - * @since 4.3 - */ -@NotThreadSafe -public class DefaultHttpResponseWriter extends AbstractMessageWriter { - - /** - * Creates an instance of DefaultHttpResponseWriter. - * - * @param buffer the session output buffer. - * @param formatter the line formatter If {@code null} - * {@link com.tracelytics.ext.apache.http.message.BasicLineFormatter#INSTANCE} - * will be used. - */ - public DefaultHttpResponseWriter( - final SessionOutputBuffer buffer, - final LineFormatter formatter) { - super(buffer, formatter); - } - - public DefaultHttpResponseWriter(final SessionOutputBuffer buffer) { - super(buffer, null); - } - - @Override - protected void writeHeadLine(final HttpResponse message) throws IOException { - lineFormatter.formatStatusLine(this.lineBuf, message.getStatusLine()); - this.sessionBuffer.writeLine(this.lineBuf); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpResponseWriterFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpResponseWriterFactory.java deleted file mode 100644 index 4bf531d4..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/DefaultHttpResponseWriterFactory.java +++ /dev/null @@ -1,64 +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 com.tracelytics.ext.apache.http.impl.io; - -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.io.HttpMessageWriter; -import com.tracelytics.ext.apache.http.io.HttpMessageWriterFactory; -import com.tracelytics.ext.apache.http.io.SessionOutputBuffer; -import com.tracelytics.ext.apache.http.message.BasicLineFormatter; -import com.tracelytics.ext.apache.http.message.LineFormatter; - -/** - * Default factory for response message writers. - * - * @since 4.3 - */ -@Immutable -public class DefaultHttpResponseWriterFactory implements HttpMessageWriterFactory { - - public static final DefaultHttpResponseWriterFactory INSTANCE = new DefaultHttpResponseWriterFactory(); - - private final LineFormatter lineFormatter; - - public DefaultHttpResponseWriterFactory(final LineFormatter lineFormatter) { - super(); - this.lineFormatter = lineFormatter != null ? lineFormatter : BasicLineFormatter.INSTANCE; - } - - public DefaultHttpResponseWriterFactory() { - this(null); - } - - @Override - public HttpMessageWriter create(final SessionOutputBuffer buffer) { - return new DefaultHttpResponseWriter(buffer, lineFormatter); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/EmptyInputStream.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/EmptyInputStream.java deleted file mode 100644 index 44d7c1c2..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/EmptyInputStream.java +++ /dev/null @@ -1,84 +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 com.tracelytics.ext.apache.http.impl.io; - -import java.io.InputStream; - -/** - * @since 4.4 - */ -public final class EmptyInputStream extends InputStream { - - public static final EmptyInputStream INSTANCE = new EmptyInputStream(); - - private EmptyInputStream() { - } - - @Override - public int available() { - return 0; - } - - @Override - public void close() { - } - - @Override - public void mark(final int readLimit) { - } - - @Override - public boolean markSupported() { - return true; - } - - @Override - public int read() { - return -1; - } - - @Override - public int read(final byte[] buf) { - return -1; - } - - @Override - public int read(final byte[] buf, final int off, final int len) { - return -1; - } - - @Override - public void reset() { - } - - @Override - public long skip(final long n) { - return 0L; - } -} - diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/HttpRequestParser.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/HttpRequestParser.java deleted file mode 100644 index 1b25d50b..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/HttpRequestParser.java +++ /dev/null @@ -1,102 +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 com.tracelytics.ext.apache.http.impl.io; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.ConnectionClosedException; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpMessage; -import com.tracelytics.ext.apache.http.HttpRequestFactory; -import com.tracelytics.ext.apache.http.ParseException; -import com.tracelytics.ext.apache.http.RequestLine; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.io.SessionInputBuffer; -import com.tracelytics.ext.apache.http.message.LineParser; -import com.tracelytics.ext.apache.http.message.ParserCursor; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -/** - * HTTP request parser that obtain its input from an instance - * of {@link SessionInputBuffer}. - *

- * The following parameters can be used to customize the behavior of this - * class: - *

    - *
  • {@link com.tracelytics.ext.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}
  • - *
  • {@link com.tracelytics.ext.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}
  • - *
- * - * @since 4.0 - * - * @deprecated (4.2) use {@link DefaultHttpRequestParser} - */ -@Deprecated -@NotThreadSafe -public class HttpRequestParser extends AbstractMessageParser { - - private final HttpRequestFactory requestFactory; - private final CharArrayBuffer lineBuf; - - /** - * Creates an instance of this class. - * - * @param buffer the session input buffer. - * @param parser the line parser. - * @param requestFactory the factory to use to create - * {@link com.tracelytics.ext.apache.http.HttpRequest}s. - * @param params HTTP parameters. - */ - public HttpRequestParser( - final SessionInputBuffer buffer, - final LineParser parser, - final HttpRequestFactory requestFactory, - final HttpParams params) { - super(buffer, parser, params); - this.requestFactory = Args.notNull(requestFactory, "Request factory"); - this.lineBuf = new CharArrayBuffer(128); - } - - @Override - protected HttpMessage parseHead( - final SessionInputBuffer sessionBuffer) - throws IOException, HttpException, ParseException { - - this.lineBuf.clear(); - final int i = sessionBuffer.readLine(this.lineBuf); - if (i == -1) { - throw new ConnectionClosedException("Client closed connection"); - } - final ParserCursor cursor = new ParserCursor(0, this.lineBuf.length()); - final RequestLine requestline = this.lineParser.parseRequestLine(this.lineBuf, cursor); - return this.requestFactory.newHttpRequest(requestline); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/HttpRequestWriter.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/HttpRequestWriter.java deleted file mode 100644 index 9aacbdb8..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/HttpRequestWriter.java +++ /dev/null @@ -1,62 +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 com.tracelytics.ext.apache.http.impl.io; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.io.SessionOutputBuffer; -import com.tracelytics.ext.apache.http.message.LineFormatter; -import com.tracelytics.ext.apache.http.params.HttpParams; - -/** - * HTTP request writer that serializes its output to an instance - * of {@link SessionOutputBuffer}. - * - * @since 4.0 - * - * @deprecated (4.3) use {@link DefaultHttpRequestWriter} - */ -@NotThreadSafe -@Deprecated -public class HttpRequestWriter extends AbstractMessageWriter { - - public HttpRequestWriter(final SessionOutputBuffer buffer, - final LineFormatter formatter, - final HttpParams params) { - super(buffer, formatter, params); - } - - @Override - protected void writeHeadLine(final HttpRequest message) throws IOException { - lineFormatter.formatRequestLine(this.lineBuf, message.getRequestLine()); - this.sessionBuffer.writeLine(this.lineBuf); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/HttpResponseParser.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/HttpResponseParser.java deleted file mode 100644 index 6c78bf20..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/HttpResponseParser.java +++ /dev/null @@ -1,103 +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 com.tracelytics.ext.apache.http.impl.io; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpMessage; -import com.tracelytics.ext.apache.http.HttpResponseFactory; -import com.tracelytics.ext.apache.http.NoHttpResponseException; -import com.tracelytics.ext.apache.http.ParseException; -import com.tracelytics.ext.apache.http.StatusLine; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.io.SessionInputBuffer; -import com.tracelytics.ext.apache.http.message.LineParser; -import com.tracelytics.ext.apache.http.message.ParserCursor; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -/** - * HTTP response parser that obtain its input from an instance - * of {@link SessionInputBuffer}. - *

- * The following parameters can be used to customize the behavior of this - * class: - *

    - *
  • {@link com.tracelytics.ext.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}
  • - *
  • {@link com.tracelytics.ext.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}
  • - *
- * - * @since 4.0 - * - * @deprecated (4.2) use {@link DefaultHttpResponseParser} - */ -@Deprecated -@NotThreadSafe -public class HttpResponseParser extends AbstractMessageParser { - - private final HttpResponseFactory responseFactory; - private final CharArrayBuffer lineBuf; - - /** - * Creates an instance of this class. - * - * @param buffer the session input buffer. - * @param parser the line parser. - * @param responseFactory the factory to use to create - * {@link com.tracelytics.ext.apache.http.HttpResponse}s. - * @param params HTTP parameters. - */ - public HttpResponseParser( - final SessionInputBuffer buffer, - final LineParser parser, - final HttpResponseFactory responseFactory, - final HttpParams params) { - super(buffer, parser, params); - this.responseFactory = Args.notNull(responseFactory, "Response factory"); - this.lineBuf = new CharArrayBuffer(128); - } - - @Override - protected HttpMessage parseHead( - final SessionInputBuffer sessionBuffer) - throws IOException, HttpException, ParseException { - - this.lineBuf.clear(); - final int i = sessionBuffer.readLine(this.lineBuf); - if (i == -1) { - throw new NoHttpResponseException("The target server failed to respond"); - } - //create the status line from the status string - final ParserCursor cursor = new ParserCursor(0, this.lineBuf.length()); - final StatusLine statusline = lineParser.parseStatusLine(this.lineBuf, cursor); - return this.responseFactory.newHttpResponse(statusline, null); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/HttpResponseWriter.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/HttpResponseWriter.java deleted file mode 100644 index e9ecb00a..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/HttpResponseWriter.java +++ /dev/null @@ -1,62 +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 com.tracelytics.ext.apache.http.impl.io; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.io.SessionOutputBuffer; -import com.tracelytics.ext.apache.http.message.LineFormatter; -import com.tracelytics.ext.apache.http.params.HttpParams; - -/** - * HTTP response writer that serializes its output to an instance - * of {@link SessionOutputBuffer}. - * - * @since 4.0 - * - * @deprecated (4.3) use {@link DefaultHttpResponseWriter} - */ -@NotThreadSafe -@Deprecated -public class HttpResponseWriter extends AbstractMessageWriter { - - public HttpResponseWriter(final SessionOutputBuffer buffer, - final LineFormatter formatter, - final HttpParams params) { - super(buffer, formatter, params); - } - - @Override - protected void writeHeadLine(final HttpResponse message) throws IOException { - lineFormatter.formatStatusLine(this.lineBuf, message.getStatusLine()); - this.sessionBuffer.writeLine(this.lineBuf); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/HttpTransportMetricsImpl.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/HttpTransportMetricsImpl.java deleted file mode 100644 index b4cdc00d..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/HttpTransportMetricsImpl.java +++ /dev/null @@ -1,65 +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 com.tracelytics.ext.apache.http.impl.io; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.io.HttpTransportMetrics; - -/** - * Default implementation of {@link HttpTransportMetrics}. - * - * @since 4.0 - */ -@NotThreadSafe -public class HttpTransportMetricsImpl implements HttpTransportMetrics { - - private long bytesTransferred = 0; - - public HttpTransportMetricsImpl() { - super(); - } - - @Override - public long getBytesTransferred() { - return this.bytesTransferred; - } - - public void setBytesTransferred(final long count) { - this.bytesTransferred = count; - } - - public void incrementBytesTransferred(final long count) { - this.bytesTransferred += count; - } - - @Override - public void reset() { - this.bytesTransferred = 0; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/IdentityInputStream.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/IdentityInputStream.java deleted file mode 100644 index f62f4d45..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/IdentityInputStream.java +++ /dev/null @@ -1,99 +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 com.tracelytics.ext.apache.http.impl.io; - -import java.io.IOException; -import java.io.InputStream; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.io.BufferInfo; -import com.tracelytics.ext.apache.http.io.SessionInputBuffer; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Input stream that reads data without any transformation. The end of the - * content entity is demarcated by closing the underlying connection - * (EOF condition). Entities transferred using this input stream can be of - * unlimited length. - *

- * Note that this class NEVER closes the underlying stream, even when close - * gets called. Instead, it will read until the end of the stream (until - * {@code -1} is returned). - * - * @since 4.0 - */ -@NotThreadSafe -public class IdentityInputStream extends InputStream { - - private final SessionInputBuffer in; - - private boolean closed = false; - - /** - * Wraps session input stream and reads input until the the end of stream. - * - * @param in The session input buffer - */ - public IdentityInputStream(final SessionInputBuffer in) { - super(); - this.in = Args.notNull(in, "Session input buffer"); - } - - @Override - public int available() throws IOException { - if (this.in instanceof BufferInfo) { - return ((BufferInfo) this.in).length(); - } else { - return 0; - } - } - - @Override - public void close() throws IOException { - this.closed = true; - } - - @Override - public int read() throws IOException { - if (this.closed) { - return -1; - } else { - return this.in.read(); - } - } - - @Override - public int read(final byte[] b, final int off, final int len) throws IOException { - if (this.closed) { - return -1; - } else { - return this.in.read(b, off, len); - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/IdentityOutputStream.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/IdentityOutputStream.java deleted file mode 100644 index 107eb050..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/IdentityOutputStream.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 com.tracelytics.ext.apache.http.impl.io; - -import java.io.IOException; -import java.io.OutputStream; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.io.SessionOutputBuffer; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Output stream that writes data without any transformation. The end of - * the content entity is demarcated by closing the underlying connection - * (EOF condition). Entities transferred using this input stream can be of - * unlimited length. - *

- * Note that this class NEVER closes the underlying stream, even when close - * gets called. Instead, the stream will be marked as closed and no further - * output will be permitted. - * - * @since 4.0 - */ -@NotThreadSafe -public class IdentityOutputStream extends OutputStream { - - /** - * Wrapped session output buffer. - */ - private final SessionOutputBuffer out; - - /** True if the stream is closed. */ - private boolean closed = false; - - public IdentityOutputStream(final SessionOutputBuffer out) { - super(); - this.out = Args.notNull(out, "Session output buffer"); - } - - /** - *

Does not close the underlying socket output.

- * - * @throws IOException If an I/O problem occurs. - */ - @Override - public void close() throws IOException { - if (!this.closed) { - this.closed = true; - this.out.flush(); - } - } - - @Override - public void flush() throws IOException { - this.out.flush(); - } - - @Override - public void write(final byte[] b, final int off, final int len) throws IOException { - if (this.closed) { - throw new IOException("Attempted write to closed stream."); - } - this.out.write(b, off, len); - } - - @Override - public void write(final byte[] b) throws IOException { - write(b, 0, b.length); - } - - @Override - public void write(final int b) throws IOException { - if (this.closed) { - throw new IOException("Attempted write to closed stream."); - } - this.out.write(b); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/SessionInputBufferImpl.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/SessionInputBufferImpl.java deleted file mode 100644 index a7f46fc6..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/SessionInputBufferImpl.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 com.tracelytics.ext.apache.http.impl.io; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CoderResult; - -import com.tracelytics.ext.apache.http.MessageConstraintException; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.config.MessageConstraints; -import com.tracelytics.ext.apache.http.io.BufferInfo; -import com.tracelytics.ext.apache.http.io.HttpTransportMetrics; -import com.tracelytics.ext.apache.http.io.SessionInputBuffer; -import com.tracelytics.ext.apache.http.protocol.HTTP; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.Asserts; -import com.tracelytics.ext.apache.http.util.ByteArrayBuffer; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -/** - * Abstract base class for session input buffers that stream data from - * an arbitrary {@link InputStream}. This class buffers input data in - * an internal byte array for optimal input performance. - *

- * {@link #readLine(CharArrayBuffer)} and {@link #readLine()} methods of this - * class treat a lone LF as valid line delimiters in addition to CR-LF required - * by the HTTP specification. - * - * @since 4.3 - */ -@NotThreadSafe -public class SessionInputBufferImpl implements SessionInputBuffer, BufferInfo { - - private final HttpTransportMetricsImpl metrics; - private final byte[] buffer; - private final ByteArrayBuffer linebuffer; - private final int minChunkLimit; - private final MessageConstraints constraints; - private final CharsetDecoder decoder; - - private InputStream instream; - private int bufferpos; - private int bufferlen; - private CharBuffer cbuf; - - /** - * Creates new instance of SessionInputBufferImpl. - * - * @param metrics HTTP transport metrics. - * @param buffersize buffer size. Must be a positive number. - * @param minChunkLimit size limit below which data chunks should be buffered in memory - * in order to minimize native method invocations on the underlying network socket. - * The optimal value of this parameter can be platform specific and defines a trade-off - * between performance of memory copy operations and that of native method invocation. - * If negative default chunk limited will be used. - * @param constraints Message constraints. If {@code null} - * {@link MessageConstraints#DEFAULT} will be used. - * @param chardecoder chardecoder to be used for decoding HTTP protocol elements. - * If {@code null} simple type cast will be used for byte to char conversion. - */ - public SessionInputBufferImpl( - final HttpTransportMetricsImpl metrics, - final int buffersize, - final int minChunkLimit, - final MessageConstraints constraints, - final CharsetDecoder chardecoder) { - Args.notNull(metrics, "HTTP transport metrcis"); - Args.positive(buffersize, "Buffer size"); - this.metrics = metrics; - this.buffer = new byte[buffersize]; - this.bufferpos = 0; - this.bufferlen = 0; - this.minChunkLimit = minChunkLimit >= 0 ? minChunkLimit : 512; - this.constraints = constraints != null ? constraints : MessageConstraints.DEFAULT; - this.linebuffer = new ByteArrayBuffer(buffersize); - this.decoder = chardecoder; - } - - public SessionInputBufferImpl( - final HttpTransportMetricsImpl metrics, - final int buffersize) { - this(metrics, buffersize, buffersize, null, null); - } - - public void bind(final InputStream instream) { - this.instream = instream; - } - - public boolean isBound() { - return this.instream != null; - } - - @Override - public int capacity() { - return this.buffer.length; - } - - @Override - public int length() { - return this.bufferlen - this.bufferpos; - } - - @Override - public int available() { - return capacity() - length(); - } - - private int streamRead(final byte[] b, final int off, final int len) throws IOException { - Asserts.notNull(this.instream, "Input stream"); - return this.instream.read(b, off, len); - } - - public int fillBuffer() throws IOException { - // compact the buffer if necessary - if (this.bufferpos > 0) { - final int len = this.bufferlen - this.bufferpos; - if (len > 0) { - System.arraycopy(this.buffer, this.bufferpos, this.buffer, 0, len); - } - this.bufferpos = 0; - this.bufferlen = len; - } - final int l; - final int off = this.bufferlen; - final int len = this.buffer.length - off; - l = streamRead(this.buffer, off, len); - if (l == -1) { - return -1; - } else { - this.bufferlen = off + l; - this.metrics.incrementBytesTransferred(l); - return l; - } - } - - public boolean hasBufferedData() { - return this.bufferpos < this.bufferlen; - } - - public void clear() { - this.bufferpos = 0; - this.bufferlen = 0; - } - - @Override - public int read() throws IOException { - int noRead; - while (!hasBufferedData()) { - noRead = fillBuffer(); - if (noRead == -1) { - return -1; - } - } - return this.buffer[this.bufferpos++] & 0xff; - } - - @Override - public int read(final byte[] b, final int off, final int len) throws IOException { - if (b == null) { - return 0; - } - if (hasBufferedData()) { - final int chunk = Math.min(len, this.bufferlen - this.bufferpos); - System.arraycopy(this.buffer, this.bufferpos, b, off, chunk); - this.bufferpos += chunk; - return chunk; - } - // If the remaining capacity is big enough, read directly from the - // underlying input stream bypassing the buffer. - if (len > this.minChunkLimit) { - final int read = streamRead(b, off, len); - if (read > 0) { - this.metrics.incrementBytesTransferred(read); - } - return read; - } else { - // otherwise read to the buffer first - while (!hasBufferedData()) { - final int noRead = fillBuffer(); - if (noRead == -1) { - return -1; - } - } - final int chunk = Math.min(len, this.bufferlen - this.bufferpos); - System.arraycopy(this.buffer, this.bufferpos, b, off, chunk); - this.bufferpos += chunk; - return chunk; - } - } - - @Override - public int read(final byte[] b) throws IOException { - if (b == null) { - return 0; - } - return read(b, 0, b.length); - } - - /** - * Reads a complete line of characters up to a line delimiter from this - * session buffer into the given line buffer. The number of chars actually - * read is returned as an integer. The line delimiter itself is discarded. - * If no char is available because the end of the stream has been reached, - * the value {@code -1} is returned. This method blocks until input - * data is available, end of file is detected, or an exception is thrown. - *

- * This method treats a lone LF as a valid line delimiters in addition - * to CR-LF required by the HTTP specification. - * - * @param charbuffer the line buffer. - * @return one line of characters - * @exception IOException if an I/O error occurs. - */ - @Override - public int readLine(final CharArrayBuffer charbuffer) throws IOException { - Args.notNull(charbuffer, "Char array buffer"); - final int maxLineLen = this.constraints.getMaxLineLength(); - int noRead = 0; - boolean retry = true; - while (retry) { - // attempt to find end of line (LF) - int pos = -1; - for (int i = this.bufferpos; i < this.bufferlen; i++) { - if (this.buffer[i] == HTTP.LF) { - pos = i; - break; - } - } - - if (maxLineLen > 0) { - final int currentLen = this.linebuffer.length() - + (pos > 0 ? pos : this.bufferlen) - this.bufferpos; - if (currentLen >= maxLineLen) { - throw new MessageConstraintException("Maximum line length limit exceeded"); - } - } - - if (pos != -1) { - // end of line found. - if (this.linebuffer.isEmpty()) { - // the entire line is preset in the read buffer - return lineFromReadBuffer(charbuffer, pos); - } - retry = false; - final int len = pos + 1 - this.bufferpos; - this.linebuffer.append(this.buffer, this.bufferpos, len); - this.bufferpos = pos + 1; - } else { - // end of line not found - if (hasBufferedData()) { - final int len = this.bufferlen - this.bufferpos; - this.linebuffer.append(this.buffer, this.bufferpos, len); - this.bufferpos = this.bufferlen; - } - noRead = fillBuffer(); - if (noRead == -1) { - retry = false; - } - } - } - if (noRead == -1 && this.linebuffer.isEmpty()) { - // indicate the end of stream - return -1; - } - return lineFromLineBuffer(charbuffer); - } - - /** - * Reads a complete line of characters up to a line delimiter from this - * session buffer. The line delimiter itself is discarded. If no char is - * available because the end of the stream has been reached, - * {@code null} is returned. This method blocks until input data is - * available, end of file is detected, or an exception is thrown. - *

- * This method treats a lone LF as a valid line delimiters in addition - * to CR-LF required by the HTTP specification. - * - * @return HTTP line as a string - * @exception IOException if an I/O error occurs. - */ - private int lineFromLineBuffer(final CharArrayBuffer charbuffer) - throws IOException { - // discard LF if found - int len = this.linebuffer.length(); - if (len > 0) { - if (this.linebuffer.byteAt(len - 1) == HTTP.LF) { - len--; - } - // discard CR if found - if (len > 0) { - if (this.linebuffer.byteAt(len - 1) == HTTP.CR) { - len--; - } - } - } - if (this.decoder == null) { - charbuffer.append(this.linebuffer, 0, len); - } else { - final ByteBuffer bbuf = ByteBuffer.wrap(this.linebuffer.buffer(), 0, len); - len = appendDecoded(charbuffer, bbuf); - } - this.linebuffer.clear(); - return len; - } - - private int lineFromReadBuffer(final CharArrayBuffer charbuffer, final int position) - throws IOException { - int pos = position; - final int off = this.bufferpos; - int len; - this.bufferpos = pos + 1; - if (pos > off && this.buffer[pos - 1] == HTTP.CR) { - // skip CR if found - pos--; - } - len = pos - off; - if (this.decoder == null) { - charbuffer.append(this.buffer, off, len); - } else { - final ByteBuffer bbuf = ByteBuffer.wrap(this.buffer, off, len); - len = appendDecoded(charbuffer, bbuf); - } - return len; - } - - private int appendDecoded( - final CharArrayBuffer charbuffer, final ByteBuffer bbuf) throws IOException { - if (!bbuf.hasRemaining()) { - return 0; - } - if (this.cbuf == null) { - this.cbuf = CharBuffer.allocate(1024); - } - this.decoder.reset(); - int len = 0; - while (bbuf.hasRemaining()) { - final CoderResult result = this.decoder.decode(bbuf, this.cbuf, true); - len += handleDecodingResult(result, charbuffer, bbuf); - } - final CoderResult result = this.decoder.flush(this.cbuf); - len += handleDecodingResult(result, charbuffer, bbuf); - this.cbuf.clear(); - return len; - } - - private int handleDecodingResult( - final CoderResult result, - final CharArrayBuffer charbuffer, - final ByteBuffer bbuf) throws IOException { - if (result.isError()) { - result.throwException(); - } - this.cbuf.flip(); - final int len = this.cbuf.remaining(); - while (this.cbuf.hasRemaining()) { - charbuffer.append(this.cbuf.get()); - } - this.cbuf.compact(); - return len; - } - - @Override - public String readLine() throws IOException { - final CharArrayBuffer charbuffer = new CharArrayBuffer(64); - final int l = readLine(charbuffer); - if (l != -1) { - return charbuffer.toString(); - } else { - return null; - } - } - - @Override - public boolean isDataAvailable(final int timeout) throws IOException { - return hasBufferedData(); - } - - @Override - public HttpTransportMetrics getMetrics() { - return this.metrics; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/SessionOutputBufferImpl.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/SessionOutputBufferImpl.java deleted file mode 100644 index ca338070..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/SessionOutputBufferImpl.java +++ /dev/null @@ -1,293 +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 com.tracelytics.ext.apache.http.impl.io; - -import java.io.IOException; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.CharsetEncoder; -import java.nio.charset.CoderResult; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.io.BufferInfo; -import com.tracelytics.ext.apache.http.io.HttpTransportMetrics; -import com.tracelytics.ext.apache.http.io.SessionOutputBuffer; -import com.tracelytics.ext.apache.http.protocol.HTTP; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.Asserts; -import com.tracelytics.ext.apache.http.util.ByteArrayBuffer; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -/** - * Abstract base class for session output buffers that stream data to - * an arbitrary {@link OutputStream}. This class buffers small chunks of - * output data in an internal byte array for optimal output performance. - *

- * {@link #writeLine(CharArrayBuffer)} and {@link #writeLine(String)} methods - * of this class use CR-LF as a line delimiter. - * - * @since 4.3 - */ -@NotThreadSafe -public class SessionOutputBufferImpl implements SessionOutputBuffer, BufferInfo { - - private static final byte[] CRLF = new byte[] {HTTP.CR, HTTP.LF}; - - private final HttpTransportMetricsImpl metrics; - private final ByteArrayBuffer buffer; - private final int fragementSizeHint; - private final CharsetEncoder encoder; - - private OutputStream outstream; - private ByteBuffer bbuf; - - /** - * Creates new instance of SessionOutputBufferImpl. - * - * @param metrics HTTP transport metrics. - * @param buffersize buffer size. Must be a positive number. - * @param fragementSizeHint fragment size hint defining a minimal size of a fragment - * that should be written out directly to the socket bypassing the session buffer. - * Value {@code 0} disables fragment buffering. - * @param charencoder charencoder to be used for encoding HTTP protocol elements. - * If {@code null} simple type cast will be used for char to byte conversion. - */ - public SessionOutputBufferImpl( - final HttpTransportMetricsImpl metrics, - final int buffersize, - final int fragementSizeHint, - final CharsetEncoder charencoder) { - super(); - Args.positive(buffersize, "Buffer size"); - Args.notNull(metrics, "HTTP transport metrcis"); - this.metrics = metrics; - this.buffer = new ByteArrayBuffer(buffersize); - this.fragementSizeHint = fragementSizeHint >= 0 ? fragementSizeHint : 0; - this.encoder = charencoder; - } - - public SessionOutputBufferImpl( - final HttpTransportMetricsImpl metrics, - final int buffersize) { - this(metrics, buffersize, buffersize, null); - } - - public void bind(final OutputStream outstream) { - this.outstream = outstream; - } - - public boolean isBound() { - return this.outstream != null; - } - - @Override - public int capacity() { - return this.buffer.capacity(); - } - - @Override - public int length() { - return this.buffer.length(); - } - - @Override - public int available() { - return capacity() - length(); - } - - private void streamWrite(final byte[] b, final int off, final int len) throws IOException { - Asserts.notNull(outstream, "Output stream"); - this.outstream.write(b, off, len); - } - - private void flushStream() throws IOException { - if (this.outstream != null) { - this.outstream.flush(); - } - } - - private void flushBuffer() throws IOException { - final int len = this.buffer.length(); - if (len > 0) { - streamWrite(this.buffer.buffer(), 0, len); - this.buffer.clear(); - this.metrics.incrementBytesTransferred(len); - } - } - - @Override - public void flush() throws IOException { - flushBuffer(); - flushStream(); - } - - @Override - public void write(final byte[] b, final int off, final int len) throws IOException { - if (b == null) { - return; - } - // Do not want to buffer large-ish chunks - // if the byte array is larger then MIN_CHUNK_LIMIT - // write it directly to the output stream - if (len > this.fragementSizeHint || len > this.buffer.capacity()) { - // flush the buffer - flushBuffer(); - // write directly to the out stream - streamWrite(b, off, len); - this.metrics.incrementBytesTransferred(len); - } else { - // Do not let the buffer grow unnecessarily - final int freecapacity = this.buffer.capacity() - this.buffer.length(); - if (len > freecapacity) { - // flush the buffer - flushBuffer(); - } - // buffer - this.buffer.append(b, off, len); - } - } - - @Override - public void write(final byte[] b) throws IOException { - if (b == null) { - return; - } - write(b, 0, b.length); - } - - @Override - public void write(final int b) throws IOException { - if (this.fragementSizeHint > 0) { - if (this.buffer.isFull()) { - flushBuffer(); - } - this.buffer.append(b); - } else { - flushBuffer(); - this.outstream.write(b); - } - } - - /** - * Writes characters from the specified string followed by a line delimiter - * to this session buffer. - *

- * This method uses CR-LF as a line delimiter. - * - * @param s the line. - * @exception IOException if an I/O error occurs. - */ - @Override - public void writeLine(final String s) throws IOException { - if (s == null) { - return; - } - if (s.length() > 0) { - if (this.encoder == null) { - for (int i = 0; i < s.length(); i++) { - write(s.charAt(i)); - } - } else { - final CharBuffer cbuf = CharBuffer.wrap(s); - writeEncoded(cbuf); - } - } - write(CRLF); - } - - /** - * Writes characters from the specified char array followed by a line - * delimiter to this session buffer. - *

- * This method uses CR-LF as a line delimiter. - * - * @param charbuffer the buffer containing chars of the line. - * @exception IOException if an I/O error occurs. - */ - @Override - public void writeLine(final CharArrayBuffer charbuffer) throws IOException { - if (charbuffer == null) { - return; - } - if (this.encoder == null) { - int off = 0; - int remaining = charbuffer.length(); - while (remaining > 0) { - int chunk = this.buffer.capacity() - this.buffer.length(); - chunk = Math.min(chunk, remaining); - if (chunk > 0) { - this.buffer.append(charbuffer, off, chunk); - } - if (this.buffer.isFull()) { - flushBuffer(); - } - off += chunk; - remaining -= chunk; - } - } else { - final CharBuffer cbuf = CharBuffer.wrap(charbuffer.buffer(), 0, charbuffer.length()); - writeEncoded(cbuf); - } - write(CRLF); - } - - private void writeEncoded(final CharBuffer cbuf) throws IOException { - if (!cbuf.hasRemaining()) { - return; - } - if (this.bbuf == null) { - this.bbuf = ByteBuffer.allocate(1024); - } - this.encoder.reset(); - while (cbuf.hasRemaining()) { - final CoderResult result = this.encoder.encode(cbuf, this.bbuf, true); - handleEncodingResult(result); - } - final CoderResult result = this.encoder.flush(this.bbuf); - handleEncodingResult(result); - this.bbuf.clear(); - } - - private void handleEncodingResult(final CoderResult result) throws IOException { - if (result.isError()) { - result.throwException(); - } - this.bbuf.flip(); - while (this.bbuf.hasRemaining()) { - write(this.bbuf.get()); - } - this.bbuf.compact(); - } - - @Override - public HttpTransportMetrics getMetrics() { - return this.metrics; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/SocketInputBuffer.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/SocketInputBuffer.java deleted file mode 100644 index 6b4d2b3f..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/SocketInputBuffer.java +++ /dev/null @@ -1,108 +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 com.tracelytics.ext.apache.http.impl.io; - -import java.io.IOException; -import java.net.Socket; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.io.EofSensor; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * {@link com.tracelytics.ext.apache.http.io.SessionInputBuffer} implementation - * bound to a {@link Socket}. - * - * @since 4.0 - * - * @deprecated (4.3) use {@link SessionInputBufferImpl} - */ -@NotThreadSafe -@Deprecated -public class SocketInputBuffer extends AbstractSessionInputBuffer implements EofSensor { - - private final Socket socket; - - private boolean eof; - - /** - * Creates an instance of this class. - * - * @param socket the socket to read data from. - * @param buffersize the size of the internal buffer. If this number is less - * than {@code 0} it is set to the value of - * {@link Socket#getReceiveBufferSize()}. If resultant number is less - * than {@code 1024} it is set to {@code 1024}. - * @param params HTTP parameters. - */ - public SocketInputBuffer( - final Socket socket, - final int buffersize, - final HttpParams params) throws IOException { - super(); - Args.notNull(socket, "Socket"); - this.socket = socket; - this.eof = false; - int n = buffersize; - if (n < 0) { - n = socket.getReceiveBufferSize(); - } - if (n < 1024) { - n = 1024; - } - init(socket.getInputStream(), n, params); - } - - @Override - protected int fillBuffer() throws IOException { - final int i = super.fillBuffer(); - this.eof = i == -1; - return i; - } - - public boolean isDataAvailable(final int timeout) throws IOException { - boolean result = hasBufferedData(); - if (!result) { - final int oldtimeout = this.socket.getSoTimeout(); - try { - this.socket.setSoTimeout(timeout); - fillBuffer(); - result = hasBufferedData(); - } finally { - socket.setSoTimeout(oldtimeout); - } - } - return result; - } - - public boolean isEof() { - return this.eof; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/SocketOutputBuffer.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/SocketOutputBuffer.java deleted file mode 100644 index 90e44538..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/SocketOutputBuffer.java +++ /dev/null @@ -1,75 +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 com.tracelytics.ext.apache.http.impl.io; - -import java.io.IOException; -import java.net.Socket; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * {@link com.tracelytics.ext.apache.http.io.SessionOutputBuffer} implementation - * bound to a {@link Socket}. - * - * @since 4.0 - * - * @deprecated (4.3) use {@link SessionOutputBufferImpl} - */ -@NotThreadSafe -@Deprecated -public class SocketOutputBuffer extends AbstractSessionOutputBuffer { - - /** - * Creates an instance of this class. - * - * @param socket the socket to write data to. - * @param buffersize the size of the internal buffer. If this number is less - * than {@code 0} it is set to the value of - * {@link Socket#getSendBufferSize()}. If resultant number is less - * than {@code 1024} it is set to {@code 1024}. - * @param params HTTP parameters. - */ - public SocketOutputBuffer( - final Socket socket, - final int buffersize, - final HttpParams params) throws IOException { - super(); - Args.notNull(socket, "Socket"); - int n = buffersize; - if (n < 0) { - n = socket.getSendBufferSize(); - } - if (n < 1024) { - n = 1024; - } - init(socket.getOutputStream(), n, params); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/package-info.java deleted file mode 100644 index c0556ec2..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/io/package-info.java +++ /dev/null @@ -1,32 +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 - * . - * - */ - -/** - * Default implementations of message parses and writers - * for synchronous, blocking communication. - */ -package com.tracelytics.ext.apache.http.impl.io; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/package-info.java deleted file mode 100644 index ee74d29f..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/package-info.java +++ /dev/null @@ -1,32 +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 - * . - * - */ - -/** - * Default implementations of HTTP connections for synchronous, - * blocking communication. - */ -package com.tracelytics.ext.apache.http.impl; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/pool/BasicConnFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/pool/BasicConnFactory.java deleted file mode 100644 index a08b9b2c..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/pool/BasicConnFactory.java +++ /dev/null @@ -1,184 +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 com.tracelytics.ext.apache.http.impl.pool; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.Socket; - -import javax.net.SocketFactory; -import javax.net.ssl.SSLSocketFactory; - -import com.tracelytics.ext.apache.http.HttpClientConnection; -import com.tracelytics.ext.apache.http.HttpConnectionFactory; -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.config.ConnectionConfig; -import com.tracelytics.ext.apache.http.config.SocketConfig; -import com.tracelytics.ext.apache.http.impl.DefaultBHttpClientConnection; -import com.tracelytics.ext.apache.http.impl.DefaultBHttpClientConnectionFactory; -import com.tracelytics.ext.apache.http.params.CoreConnectionPNames; -import com.tracelytics.ext.apache.http.params.HttpParamConfig; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.pool.ConnFactory; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * A very basic {@link ConnFactory} implementation that creates - * {@link HttpClientConnection} instances given a {@link HttpHost} instance. - * - * @see HttpHost - * @since 4.2 - */ -@SuppressWarnings("deprecation") -@Immutable -public class BasicConnFactory implements ConnFactory { - - private final SocketFactory plainfactory; - private final SSLSocketFactory sslfactory; - private final int connectTimeout; - private final SocketConfig sconfig; - private final HttpConnectionFactory connFactory; - - /** - * @deprecated (4.3) use - * {@link BasicConnFactory#BasicConnFactory(SocketFactory, SSLSocketFactory, int, - * SocketConfig, ConnectionConfig)}. - */ - @Deprecated - public BasicConnFactory(final SSLSocketFactory sslfactory, final HttpParams params) { - super(); - Args.notNull(params, "HTTP params"); - this.plainfactory = null; - this.sslfactory = sslfactory; - this.connectTimeout = params.getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 0); - this.sconfig = HttpParamConfig.getSocketConfig(params); - this.connFactory = new DefaultBHttpClientConnectionFactory( - HttpParamConfig.getConnectionConfig(params)); - } - - /** - * @deprecated (4.3) use - * {@link BasicConnFactory#BasicConnFactory(int, SocketConfig, ConnectionConfig)}. - */ - @Deprecated - public BasicConnFactory(final HttpParams params) { - this(null, params); - } - - /** - * @since 4.3 - */ - public BasicConnFactory( - final SocketFactory plainfactory, - final SSLSocketFactory sslfactory, - final int connectTimeout, - final SocketConfig sconfig, - final ConnectionConfig cconfig) { - super(); - this.plainfactory = plainfactory; - this.sslfactory = sslfactory; - this.connectTimeout = connectTimeout; - this.sconfig = sconfig != null ? sconfig : SocketConfig.DEFAULT; - this.connFactory = new DefaultBHttpClientConnectionFactory( - cconfig != null ? cconfig : ConnectionConfig.DEFAULT); - } - - /** - * @since 4.3 - */ - public BasicConnFactory( - final int connectTimeout, final SocketConfig sconfig, final ConnectionConfig cconfig) { - this(null, null, connectTimeout, sconfig, cconfig); - } - - /** - * @since 4.3 - */ - public BasicConnFactory(final SocketConfig sconfig, final ConnectionConfig cconfig) { - this(null, null, 0, sconfig, cconfig); - } - - /** - * @since 4.3 - */ - public BasicConnFactory() { - this(null, null, 0, SocketConfig.DEFAULT, ConnectionConfig.DEFAULT); - } - - /** - * @deprecated (4.3) no longer used. - */ - @Deprecated - protected HttpClientConnection create(final Socket socket, final HttpParams params) throws IOException { - final int bufsize = params.getIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024); - final DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(bufsize); - conn.bind(socket); - return conn; - } - - @Override - public HttpClientConnection create(final HttpHost host) throws IOException { - final String scheme = host.getSchemeName(); - Socket socket = null; - if ("http".equalsIgnoreCase(scheme)) { - socket = this.plainfactory != null ? this.plainfactory.createSocket() : - new Socket(); - } if ("https".equalsIgnoreCase(scheme)) { - socket = (this.sslfactory != null ? this.sslfactory : - SSLSocketFactory.getDefault()).createSocket(); - } - if (socket == null) { - throw new IOException(scheme + " scheme is not supported"); - } - final String hostname = host.getHostName(); - int port = host.getPort(); - if (port == -1) { - if (host.getSchemeName().equalsIgnoreCase("http")) { - port = 80; - } else if (host.getSchemeName().equalsIgnoreCase("https")) { - port = 443; - } - } - socket.setSoTimeout(this.sconfig.getSoTimeout()); - if (this.sconfig.getSndBufSize() > 0) { - socket.setSendBufferSize(this.sconfig.getSndBufSize()); - } - if (this.sconfig.getRcvBufSize() > 0) { - socket.setReceiveBufferSize(this.sconfig.getRcvBufSize()); - } - socket.setTcpNoDelay(this.sconfig.isTcpNoDelay()); - final int linger = this.sconfig.getSoLinger(); - if (linger >= 0) { - socket.setSoLinger(true, linger); - } - socket.setKeepAlive(this.sconfig.isSoKeepAlive()); - socket.connect(new InetSocketAddress(hostname, port), this.connectTimeout); - return this.connFactory.createConnection(socket); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/pool/BasicConnPool.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/pool/BasicConnPool.java deleted file mode 100644 index ebfd3fef..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/pool/BasicConnPool.java +++ /dev/null @@ -1,94 +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 com.tracelytics.ext.apache.http.impl.pool; - -import java.util.concurrent.atomic.AtomicLong; - -import com.tracelytics.ext.apache.http.HttpClientConnection; -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.config.ConnectionConfig; -import com.tracelytics.ext.apache.http.config.SocketConfig; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.pool.AbstractConnPool; -import com.tracelytics.ext.apache.http.pool.ConnFactory; - -/** - * A very basic {@link com.tracelytics.ext.apache.http.pool.ConnPool} implementation that - * represents a pool of blocking {@link HttpClientConnection} connections - * identified by an {@link HttpHost} instance. Please note this pool - * implementation does not support complex routes via a proxy cannot - * differentiate between direct and proxied connections. - * - * @see HttpHost - * @since 4.2 - */ -@SuppressWarnings("deprecation") -@ThreadSafe -public class BasicConnPool extends AbstractConnPool { - - private static final AtomicLong COUNTER = new AtomicLong(); - - public BasicConnPool(final ConnFactory connFactory) { - super(connFactory, 2, 20); - } - - /** - * @deprecated (4.3) use {@link BasicConnPool#BasicConnPool(SocketConfig, ConnectionConfig)} - */ - @Deprecated - public BasicConnPool(final HttpParams params) { - super(new BasicConnFactory(params), 2, 20); - } - - /** - * @since 4.3 - */ - public BasicConnPool(final SocketConfig sconfig, final ConnectionConfig cconfig) { - super(new BasicConnFactory(sconfig, cconfig), 2, 20); - } - - /** - * @since 4.3 - */ - public BasicConnPool() { - super(new BasicConnFactory(SocketConfig.DEFAULT, ConnectionConfig.DEFAULT), 2, 20); - } - - @Override - protected BasicPoolEntry createEntry( - final HttpHost host, - final HttpClientConnection conn) { - return new BasicPoolEntry(Long.toString(COUNTER.getAndIncrement()), host, conn); - } - - @Override - protected boolean validate(final BasicPoolEntry entry) { - return !entry.getConnection().isStale(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/pool/BasicPoolEntry.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/pool/BasicPoolEntry.java deleted file mode 100644 index 77604ae9..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/pool/BasicPoolEntry.java +++ /dev/null @@ -1,64 +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 com.tracelytics.ext.apache.http.impl.pool; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.HttpClientConnection; -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.pool.PoolEntry; - -/** - * A very basic {@link PoolEntry} implementation that represents an entry - * in a pool of blocking {@link HttpClientConnection}s identified by - * an {@link HttpHost} instance. - * - * @see HttpHost - * @since 4.2 - */ -@ThreadSafe -public class BasicPoolEntry extends PoolEntry { - - public BasicPoolEntry(final String id, final HttpHost route, final HttpClientConnection conn) { - super(id, route, conn); - } - - @Override - public void close() { - try { - this.getConnection().close(); - } catch (final IOException ignore) { - } - } - - @Override - public boolean isClosed() { - return !this.getConnection().isOpen(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/pool/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/pool/package-info.java deleted file mode 100644 index ea73292f..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/impl/pool/package-info.java +++ /dev/null @@ -1,32 +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 - * . - * - */ - -/** - * Default implementations of client side connection pools - * for synchronous, blocking communication. - */ -package com.tracelytics.ext.apache.http.impl.pool; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/BufferInfo.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/BufferInfo.java deleted file mode 100644 index 1536a0a1..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/BufferInfo.java +++ /dev/null @@ -1,58 +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 com.tracelytics.ext.apache.http.io; - -/** - * Basic buffer properties. - * - * @since 4.1 - */ -public interface BufferInfo { - - /** - * Return length data stored in the buffer - * - * @return data length - */ - int length(); - - /** - * Returns total capacity of the buffer - * - * @return total capacity - */ - int capacity(); - - /** - * Returns available space in the buffer. - * - * @return available space. - */ - int available(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/EofSensor.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/EofSensor.java deleted file mode 100644 index a10eaf48..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/EofSensor.java +++ /dev/null @@ -1,42 +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 com.tracelytics.ext.apache.http.io; - -/** - * EOF sensor. - * - * @since 4.0 - * - * @deprecated (4.3) no longer used. - */ -@Deprecated -public interface EofSensor { - - boolean isEof(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/HttpMessageParser.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/HttpMessageParser.java deleted file mode 100644 index 11453e70..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/HttpMessageParser.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 com.tracelytics.ext.apache.http.io; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpMessage; - -/** - * Abstract message parser intended to build HTTP messages from an arbitrary data source. - * - * @param - * {@link HttpMessage} or a subclass - * - * @since 4.0 - */ -public interface HttpMessageParser { - - /** - * Generates an instance of {@link HttpMessage} from the underlying data - * source. - * - * @return HTTP message - * @throws IOException in case of an I/O error - * @throws HttpException in case of HTTP protocol violation - */ - T parse() - throws IOException, HttpException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/HttpMessageParserFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/HttpMessageParserFactory.java deleted file mode 100644 index 19fdd206..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/HttpMessageParserFactory.java +++ /dev/null @@ -1,42 +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 com.tracelytics.ext.apache.http.io; - -import com.tracelytics.ext.apache.http.HttpMessage; -import com.tracelytics.ext.apache.http.config.MessageConstraints; - -/** - * Factory for {@link HttpMessageParser} instances. - * - * @since 4.3 - */ -public interface HttpMessageParserFactory { - - HttpMessageParser create(SessionInputBuffer buffer, MessageConstraints constraints); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/HttpMessageWriter.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/HttpMessageWriter.java deleted file mode 100644 index 463cb00d..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/HttpMessageWriter.java +++ /dev/null @@ -1,54 +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 com.tracelytics.ext.apache.http.io; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpMessage; - -/** - * Abstract message writer intended to serialize HTTP messages to an arbitrary - * data sink. - * - * @since 4.0 - */ -public interface HttpMessageWriter { - - /** - * Serializes an instance of {@link HttpMessage} to the underlying data - * sink. - * - * @param message HTTP message - * @throws IOException in case of an I/O error - * @throws HttpException in case of HTTP protocol violation - */ - void write(T message) - throws IOException, HttpException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/HttpMessageWriterFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/HttpMessageWriterFactory.java deleted file mode 100644 index e85d2fef..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/HttpMessageWriterFactory.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 com.tracelytics.ext.apache.http.io; - -import com.tracelytics.ext.apache.http.HttpMessage; - -/** - * Factory for {@link HttpMessageWriter} instances. - * - * @since 4.3 - */ -public interface HttpMessageWriterFactory { - - HttpMessageWriter create(SessionOutputBuffer buffer); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/HttpTransportMetrics.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/HttpTransportMetrics.java deleted file mode 100644 index 98640dc3..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/HttpTransportMetrics.java +++ /dev/null @@ -1,48 +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 com.tracelytics.ext.apache.http.io; - -/** - * The point of access to the statistics of {@link SessionInputBuffer} or - * {@link SessionOutputBuffer}. - * - * @since 4.0 - */ -public interface HttpTransportMetrics { - - /** - * Returns the number of bytes transferred. - */ - long getBytesTransferred(); - - /** - * Resets the counts - */ - void reset(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/SessionInputBuffer.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/SessionInputBuffer.java deleted file mode 100644 index 1fe7c1df..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/SessionInputBuffer.java +++ /dev/null @@ -1,152 +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 com.tracelytics.ext.apache.http.io; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -/** - * Session input buffer for blocking connections. This interface is similar to - * InputStream class, but it also provides methods for reading lines of text. - *

- * Implementing classes are also expected to manage intermediate data buffering - * for optimal input performance. - * - * @since 4.0 - */ -public interface SessionInputBuffer { - - /** - * Reads up to {@code len} bytes of data from the session buffer into - * an array of bytes. An attempt is made to read as many as - * {@code len} bytes, but a smaller number may be read, possibly - * zero. The number of bytes actually read is returned as an integer. - * - *

This method blocks until input data is available, end of file is - * detected, or an exception is thrown. - * - *

If {@code off} is negative, or {@code len} is negative, or - * {@code off+len} is greater than the length of the array - * {@code b}, then an {@code IndexOutOfBoundsException} is - * thrown. - * - * @param b the buffer into which the data is read. - * @param off the start offset in array {@code b} - * at which the data is written. - * @param len the maximum number of bytes to read. - * @return the total number of bytes read into the buffer, or - * {@code -1} if there is no more data because the end of - * the stream has been reached. - * @exception IOException if an I/O error occurs. - */ - int read(byte[] b, int off, int len) throws IOException; - - /** - * Reads some number of bytes from the session buffer and stores them into - * the buffer array {@code b}. The number of bytes actually read is - * returned as an integer. This method blocks until input data is - * available, end of file is detected, or an exception is thrown. - * - * @param b the buffer into which the data is read. - * @return the total number of bytes read into the buffer, or - * {@code -1} is there is no more data because the end of - * the stream has been reached. - * @exception IOException if an I/O error occurs. - */ - int read(byte[] b) throws IOException; - - /** - * Reads the next byte of data from this session buffer. The value byte is - * returned as an {@code int} in the range {@code 0} to - * {@code 255}. If no byte is available because the end of the stream - * has been reached, the value {@code -1} is returned. This method - * blocks until input data is available, the end of the stream is detected, - * or an exception is thrown. - * - * @return the next byte of data, or {@code -1} if the end of the - * stream is reached. - * @exception IOException if an I/O error occurs. - */ - int read() throws IOException; - - /** - * Reads a complete line of characters up to a line delimiter from this - * session buffer into the given line buffer. The number of chars actually - * read is returned as an integer. The line delimiter itself is discarded. - * If no char is available because the end of the stream has been reached, - * the value {@code -1} is returned. This method blocks until input - * data is available, end of file is detected, or an exception is thrown. - *

- * The choice of a char encoding and line delimiter sequence is up to the - * specific implementations of this interface. - * - * @param buffer the line buffer. - * @return one line of characters - * @exception IOException if an I/O error occurs. - */ - int readLine(CharArrayBuffer buffer) throws IOException; - - /** - * Reads a complete line of characters up to a line delimiter from this - * session buffer. The line delimiter itself is discarded. If no char is - * available because the end of the stream has been reached, - * {@code null} is returned. This method blocks until input data is - * available, end of file is detected, or an exception is thrown. - *

- * The choice of a char encoding and line delimiter sequence is up to the - * specific implementations of this interface. - * - * @return HTTP line as a string - * @exception IOException if an I/O error occurs. - */ - String readLine() throws IOException; - - /** Blocks until some data becomes available in the session buffer or the - * given timeout period in milliseconds elapses. If the timeout value is - * {@code 0} this method blocks indefinitely. - * - * @param timeout in milliseconds. - * @return {@code true} if some data is available in the session - * buffer or {@code false} otherwise. - * @exception IOException if an I/O error occurs. - * - * @deprecated (4.3) do not use. This function should be provided at the - * connection level - */ - @Deprecated - boolean isDataAvailable(int timeout) throws IOException; - - /** - * Returns {@link HttpTransportMetrics} for this session buffer. - * - * @return transport metrics. - */ - HttpTransportMetrics getMetrics(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/SessionOutputBuffer.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/SessionOutputBuffer.java deleted file mode 100644 index 9d8d45eb..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/SessionOutputBuffer.java +++ /dev/null @@ -1,120 +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 com.tracelytics.ext.apache.http.io; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -/** - * Session output buffer for blocking connections. This interface is similar to - * OutputStream class, but it also provides methods for writing lines of text. - *

- * Implementing classes are also expected to manage intermediate data buffering - * for optimal output performance. - * - * @since 4.0 - */ -public interface SessionOutputBuffer { - - /** - * Writes {@code len} bytes from the specified byte array - * starting at offset {@code off} to this session buffer. - *

- * If {@code off} is negative, or {@code len} is negative, or - * {@code off+len} is greater than the length of the array - * {@code b}, then an {@code IndexOutOfBoundsException} is thrown. - * - * @param b the data. - * @param off the start offset in the data. - * @param len the number of bytes to write. - * @exception IOException if an I/O error occurs. - */ - void write(byte[] b, int off, int len) throws IOException; - - /** - * Writes {@code b.length} bytes from the specified byte array - * to this session buffer. - * - * @param b the data. - * @exception IOException if an I/O error occurs. - */ - void write(byte[] b) throws IOException; - - /** - * Writes the specified byte to this session buffer. - * - * @param b the {@code byte}. - * @exception IOException if an I/O error occurs. - */ - void write(int b) throws IOException; - - /** - * Writes characters from the specified string followed by a line delimiter - * to this session buffer. - *

- * The choice of a char encoding and line delimiter sequence is up to the - * specific implementations of this interface. - * - * @param s the line. - * @exception IOException if an I/O error occurs. - */ - void writeLine(String s) throws IOException; - - /** - * Writes characters from the specified char array followed by a line - * delimiter to this session buffer. - *

- * The choice of a char encoding and line delimiter sequence is up to the - * specific implementations of this interface. - * - * @param buffer the buffer containing chars of the line. - * @exception IOException if an I/O error occurs. - */ - void writeLine(CharArrayBuffer buffer) throws IOException; - - /** - * Flushes this session buffer and forces any buffered output bytes - * to be written out. The general contract of {@code flush} is - * that calling it is an indication that, if any bytes previously - * written have been buffered by the implementation of the output - * stream, such bytes should immediately be written to their - * intended destination. - * - * @exception IOException if an I/O error occurs. - */ - void flush() throws IOException; - - /** - * Returns {@link HttpTransportMetrics} for this session buffer. - * - * @return transport metrics. - */ - HttpTransportMetrics getMetrics(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/package-info.java deleted file mode 100644 index 4f3367c6..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/io/package-info.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * HTTP message parser and writer APIs for synchronous, blocking - * communication. - */ -package com.tracelytics.ext.apache.http.io; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/AbstractHttpMessage.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/AbstractHttpMessage.java deleted file mode 100644 index 374aafda..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/AbstractHttpMessage.java +++ /dev/null @@ -1,180 +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 com.tracelytics.ext.apache.http.message; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HeaderIterator; -import com.tracelytics.ext.apache.http.HttpMessage; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.params.BasicHttpParams; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Basic implementation of {@link HttpMessage}. - * - * @since 4.0 - */ -@SuppressWarnings("deprecation") -@NotThreadSafe -public abstract class AbstractHttpMessage implements HttpMessage { - - protected HeaderGroup headergroup; - - @Deprecated - protected HttpParams params; - - /** - * @deprecated (4.3) use {@link AbstractHttpMessage#AbstractHttpMessage()} - */ - @Deprecated - protected AbstractHttpMessage(final HttpParams params) { - super(); - this.headergroup = new HeaderGroup(); - this.params = params; - } - - protected AbstractHttpMessage() { - this(null); - } - - // non-javadoc, see interface HttpMessage - @Override - public boolean containsHeader(final String name) { - return this.headergroup.containsHeader(name); - } - - // non-javadoc, see interface HttpMessage - @Override - public Header[] getHeaders(final String name) { - return this.headergroup.getHeaders(name); - } - - // non-javadoc, see interface HttpMessage - @Override - public Header getFirstHeader(final String name) { - return this.headergroup.getFirstHeader(name); - } - - // non-javadoc, see interface HttpMessage - @Override - public Header getLastHeader(final String name) { - return this.headergroup.getLastHeader(name); - } - - // non-javadoc, see interface HttpMessage - @Override - public Header[] getAllHeaders() { - return this.headergroup.getAllHeaders(); - } - - // non-javadoc, see interface HttpMessage - @Override - public void addHeader(final Header header) { - this.headergroup.addHeader(header); - } - - // non-javadoc, see interface HttpMessage - @Override - public void addHeader(final String name, final String value) { - Args.notNull(name, "Header name"); - this.headergroup.addHeader(new BasicHeader(name, value)); - } - - // non-javadoc, see interface HttpMessage - @Override - public void setHeader(final Header header) { - this.headergroup.updateHeader(header); - } - - // non-javadoc, see interface HttpMessage - @Override - public void setHeader(final String name, final String value) { - Args.notNull(name, "Header name"); - this.headergroup.updateHeader(new BasicHeader(name, value)); - } - - // non-javadoc, see interface HttpMessage - @Override - public void setHeaders(final Header[] headers) { - this.headergroup.setHeaders(headers); - } - - // non-javadoc, see interface HttpMessage - @Override - public void removeHeader(final Header header) { - this.headergroup.removeHeader(header); - } - - // non-javadoc, see interface HttpMessage - @Override - public void removeHeaders(final String name) { - if (name == null) { - return; - } - for (final HeaderIterator i = this.headergroup.iterator(); i.hasNext(); ) { - final Header header = i.nextHeader(); - if (name.equalsIgnoreCase(header.getName())) { - i.remove(); - } - } - } - - // non-javadoc, see interface HttpMessage - @Override - public HeaderIterator headerIterator() { - return this.headergroup.iterator(); - } - - // non-javadoc, see interface HttpMessage - @Override - public HeaderIterator headerIterator(final String name) { - return this.headergroup.iterator(name); - } - - /** - * @deprecated (4.3) use constructor parameters of configuration API provided by HttpClient - */ - @Override - @Deprecated - public HttpParams getParams() { - if (this.params == null) { - this.params = new BasicHttpParams(); - } - return this.params; - } - - /** - * @deprecated (4.3) use constructor parameters of configuration API provided by HttpClient - */ - @Override - @Deprecated - public void setParams(final HttpParams params) { - this.params = Args.notNull(params, "HTTP parameters"); - } -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHeader.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHeader.java deleted file mode 100644 index c725c067..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHeader.java +++ /dev/null @@ -1,94 +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 com.tracelytics.ext.apache.http.message; - -import java.io.Serializable; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HeaderElement; -import com.tracelytics.ext.apache.http.ParseException; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Basic implementation of {@link Header}. - * - * @since 4.0 - */ -@Immutable -public class BasicHeader implements Header, Cloneable, Serializable { - - private static final long serialVersionUID = -5427236326487562174L; - - private final String name; - private final String value; - - /** - * Constructor with name and value - * - * @param name the header name - * @param value the header value - */ - public BasicHeader(final String name, final String value) { - super(); - this.name = Args.notNull(name, "Name"); - this.value = value; - } - - @Override - public String getName() { - return this.name; - } - - @Override - public String getValue() { - return this.value; - } - - @Override - public String toString() { - // no need for non-default formatting in toString() - return BasicLineFormatter.INSTANCE.formatHeader(null, this).toString(); - } - - @Override - public HeaderElement[] getElements() throws ParseException { - if (this.value != null) { - // result intentionally not cached, it's probably not used again - return BasicHeaderValueParser.parseElements(this.value, null); - } else { - return new HeaderElement[] {}; - } - } - - @Override - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHeaderElement.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHeaderElement.java deleted file mode 100644 index 117974a0..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHeaderElement.java +++ /dev/null @@ -1,168 +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 com.tracelytics.ext.apache.http.message; - -import com.tracelytics.ext.apache.http.HeaderElement; -import com.tracelytics.ext.apache.http.NameValuePair; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.LangUtils; - -/** - * Basic implementation of {@link HeaderElement} - * - * @since 4.0 - */ -@NotThreadSafe -public class BasicHeaderElement implements HeaderElement, Cloneable { - - private final String name; - private final String value; - private final NameValuePair[] parameters; - - /** - * Constructor with name, value and parameters. - * - * @param name header element name - * @param value header element value. May be {@code null} - * @param parameters header element parameters. May be {@code null}. - * Parameters are copied by reference, not by value - */ - public BasicHeaderElement( - final String name, - final String value, - final NameValuePair[] parameters) { - super(); - this.name = Args.notNull(name, "Name"); - this.value = value; - if (parameters != null) { - this.parameters = parameters; - } else { - this.parameters = new NameValuePair[] {}; - } - } - - /** - * Constructor with name and value. - * - * @param name header element name - * @param value header element value. May be {@code null} - */ - public BasicHeaderElement(final String name, final String value) { - this(name, value, null); - } - - @Override - public String getName() { - return this.name; - } - - @Override - public String getValue() { - return this.value; - } - - @Override - public NameValuePair[] getParameters() { - return this.parameters.clone(); - } - - @Override - public int getParameterCount() { - return this.parameters.length; - } - - @Override - public NameValuePair getParameter(final int index) { - // ArrayIndexOutOfBoundsException is appropriate - return this.parameters[index]; - } - - @Override - public NameValuePair getParameterByName(final String name) { - Args.notNull(name, "Name"); - NameValuePair found = null; - for (final NameValuePair current : this.parameters) { - if (current.getName().equalsIgnoreCase(name)) { - found = current; - break; - } - } - return found; - } - - @Override - public boolean equals(final Object object) { - if (this == object) { - return true; - } - if (object instanceof HeaderElement) { - final BasicHeaderElement that = (BasicHeaderElement) object; - return this.name.equals(that.name) - && LangUtils.equals(this.value, that.value) - && LangUtils.equals(this.parameters, that.parameters); - } else { - return false; - } - } - - @Override - public int hashCode() { - int hash = LangUtils.HASH_SEED; - hash = LangUtils.hashCode(hash, this.name); - hash = LangUtils.hashCode(hash, this.value); - for (final NameValuePair parameter : this.parameters) { - hash = LangUtils.hashCode(hash, parameter); - } - return hash; - } - - @Override - public String toString() { - final StringBuilder buffer = new StringBuilder(); - buffer.append(this.name); - if (this.value != null) { - buffer.append("="); - buffer.append(this.value); - } - for (final NameValuePair parameter : this.parameters) { - buffer.append("; "); - buffer.append(parameter); - } - return buffer.toString(); - } - - @Override - public Object clone() throws CloneNotSupportedException { - // parameters array is considered immutable - // no need to make a copy of it - return super.clone(); - } - -} - diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHeaderElementIterator.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHeaderElementIterator.java deleted file mode 100644 index 982e5968..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHeaderElementIterator.java +++ /dev/null @@ -1,155 +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 com.tracelytics.ext.apache.http.message; - -import java.util.NoSuchElementException; - -import com.tracelytics.ext.apache.http.FormattedHeader; -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HeaderElement; -import com.tracelytics.ext.apache.http.HeaderElementIterator; -import com.tracelytics.ext.apache.http.HeaderIterator; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -/** - * Basic implementation of a {@link HeaderElementIterator}. - * - * @since 4.0 - */ -@NotThreadSafe -public class BasicHeaderElementIterator implements HeaderElementIterator { - - private final HeaderIterator headerIt; - private final HeaderValueParser parser; - - private HeaderElement currentElement = null; - private CharArrayBuffer buffer = null; - private ParserCursor cursor = null; - - /** - * Creates a new instance of BasicHeaderElementIterator - */ - public BasicHeaderElementIterator( - final HeaderIterator headerIterator, - final HeaderValueParser parser) { - this.headerIt = Args.notNull(headerIterator, "Header iterator"); - this.parser = Args.notNull(parser, "Parser"); - } - - - public BasicHeaderElementIterator(final HeaderIterator headerIterator) { - this(headerIterator, BasicHeaderValueParser.INSTANCE); - } - - - private void bufferHeaderValue() { - this.cursor = null; - this.buffer = null; - while (this.headerIt.hasNext()) { - final Header h = this.headerIt.nextHeader(); - if (h instanceof FormattedHeader) { - this.buffer = ((FormattedHeader) h).getBuffer(); - this.cursor = new ParserCursor(0, this.buffer.length()); - this.cursor.updatePos(((FormattedHeader) h).getValuePos()); - break; - } else { - final String value = h.getValue(); - if (value != null) { - this.buffer = new CharArrayBuffer(value.length()); - this.buffer.append(value); - this.cursor = new ParserCursor(0, this.buffer.length()); - break; - } - } - } - } - - private void parseNextElement() { - // loop while there are headers left to parse - while (this.headerIt.hasNext() || this.cursor != null) { - if (this.cursor == null || this.cursor.atEnd()) { - // get next header value - bufferHeaderValue(); - } - // Anything buffered? - if (this.cursor != null) { - // loop while there is data in the buffer - while (!this.cursor.atEnd()) { - final HeaderElement e = this.parser.parseHeaderElement(this.buffer, this.cursor); - if (!(e.getName().length() == 0 && e.getValue() == null)) { - // Found something - this.currentElement = e; - return; - } - } - // if at the end of the buffer - if (this.cursor.atEnd()) { - // discard it - this.cursor = null; - this.buffer = null; - } - } - } - } - - @Override - public boolean hasNext() { - if (this.currentElement == null) { - parseNextElement(); - } - return this.currentElement != null; - } - - @Override - public HeaderElement nextElement() throws NoSuchElementException { - if (this.currentElement == null) { - parseNextElement(); - } - - if (this.currentElement == null) { - throw new NoSuchElementException("No more header elements available"); - } - - final HeaderElement element = this.currentElement; - this.currentElement = null; - return element; - } - - @Override - public final Object next() throws NoSuchElementException { - return nextElement(); - } - - @Override - public void remove() throws UnsupportedOperationException { - throw new UnsupportedOperationException("Remove not supported"); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHeaderIterator.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHeaderIterator.java deleted file mode 100644 index 8163e961..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHeaderIterator.java +++ /dev/null @@ -1,179 +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 com.tracelytics.ext.apache.http.message; - -import java.util.NoSuchElementException; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HeaderIterator; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Basic implementation of a {@link HeaderIterator}. - * - * @since 4.0 - */ -@NotThreadSafe -public class BasicHeaderIterator implements HeaderIterator { - - /** - * An array of headers to iterate over. - * Not all elements of this array are necessarily part of the iteration. - * This array will never be modified by the iterator. - * Derived implementations are expected to adhere to this restriction. - */ - protected final Header[] allHeaders; - - - /** - * The position of the next header in {@link #allHeaders allHeaders}. - * Negative if the iteration is over. - */ - protected int currentIndex; - - - /** - * The header name to filter by. - * {@code null} to iterate over all headers in the array. - */ - protected String headerName; - - - - /** - * Creates a new header iterator. - * - * @param headers an array of headers over which to iterate - * @param name the name of the headers over which to iterate, or - * {@code null} for any - */ - public BasicHeaderIterator(final Header[] headers, final String name) { - super(); - this.allHeaders = Args.notNull(headers, "Header array"); - this.headerName = name; - this.currentIndex = findNext(-1); - } - - - /** - * Determines the index of the next header. - * - * @param pos one less than the index to consider first, - * -1 to search for the first header - * - * @return the index of the next header that matches the filter name, - * or negative if there are no more headers - */ - protected int findNext(final int pos) { - int from = pos; - if (from < -1) { - return -1; - } - - final int to = this.allHeaders.length-1; - boolean found = false; - while (!found && (from < to)) { - from++; - found = filterHeader(from); - } - return found ? from : -1; - } - - - /** - * Checks whether a header is part of the iteration. - * - * @param index the index of the header to check - * - * @return {@code true} if the header should be part of the - * iteration, {@code false} to skip - */ - protected boolean filterHeader(final int index) { - return (this.headerName == null) || - this.headerName.equalsIgnoreCase(this.allHeaders[index].getName()); - } - - - // non-javadoc, see interface HeaderIterator - @Override - public boolean hasNext() { - return (this.currentIndex >= 0); - } - - - /** - * Obtains the next header from this iteration. - * - * @return the next header in this iteration - * - * @throws NoSuchElementException if there are no more headers - */ - @Override - public Header nextHeader() - throws NoSuchElementException { - - final int current = this.currentIndex; - if (current < 0) { - throw new NoSuchElementException("Iteration already finished."); - } - - this.currentIndex = findNext(current); - - return this.allHeaders[current]; - } - - - /** - * Returns the next header. - * Same as {@link #nextHeader nextHeader}, but not type-safe. - * - * @return the next header in this iteration - * - * @throws NoSuchElementException if there are no more headers - */ - @Override - public final Object next() - throws NoSuchElementException { - return nextHeader(); - } - - - /** - * Removing headers is not supported. - * - * @throws UnsupportedOperationException always - */ - @Override - public void remove() - throws UnsupportedOperationException { - - throw new UnsupportedOperationException - ("Removing headers is not supported."); - } -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHeaderValueFormatter.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHeaderValueFormatter.java deleted file mode 100644 index aa3079a7..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHeaderValueFormatter.java +++ /dev/null @@ -1,426 +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 com.tracelytics.ext.apache.http.message; - -import com.tracelytics.ext.apache.http.HeaderElement; -import com.tracelytics.ext.apache.http.NameValuePair; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -/** - * Basic implementation for formatting header value elements. - * Instances of this class are stateless and thread-safe. - * Derived classes are expected to maintain these properties. - * - * @since 4.0 - */ -@Immutable -public class BasicHeaderValueFormatter implements HeaderValueFormatter { - - /** - * A default instance of this class, for use as default or fallback. - * Note that {@link BasicHeaderValueFormatter} is not a singleton, there - * can be many instances of the class itself and of derived classes. - * The instance here provides non-customized, default behavior. - * - * @deprecated (4.3) use {@link #INSTANCE} - */ - @Deprecated - public final static - BasicHeaderValueFormatter DEFAULT = new BasicHeaderValueFormatter(); - - public final static BasicHeaderValueFormatter INSTANCE = new BasicHeaderValueFormatter(); - - /** - * Special characters that can be used as separators in HTTP parameters. - * These special characters MUST be in a quoted string to be used within - * a parameter value . - */ - public final static String SEPARATORS = " ;,:@()<>\\\"/[]?={}\t"; - - /** - * Unsafe special characters that must be escaped using the backslash - * character - */ - public final static String UNSAFE_CHARS = "\"\\"; - - public BasicHeaderValueFormatter() { - super(); - } - - /** - * Formats an array of header elements. - * - * @param elems the header elements to format - * @param quote {@code true} to always format with quoted values, - * {@code false} to use quotes only when necessary - * @param formatter the formatter to use, or {@code null} - * for the {@link #INSTANCE default} - * - * @return the formatted header elements - */ - public static - String formatElements(final HeaderElement[] elems, - final boolean quote, - final HeaderValueFormatter formatter) { - return (formatter != null ? formatter : BasicHeaderValueFormatter.INSTANCE) - .formatElements(null, elems, quote).toString(); - } - - - // non-javadoc, see interface HeaderValueFormatter - @Override - public CharArrayBuffer formatElements(final CharArrayBuffer charBuffer, - final HeaderElement[] elems, - final boolean quote) { - Args.notNull(elems, "Header element array"); - final int len = estimateElementsLen(elems); - CharArrayBuffer buffer = charBuffer; - if (buffer == null) { - buffer = new CharArrayBuffer(len); - } else { - buffer.ensureCapacity(len); - } - - for (int i=0; i 0) { - buffer.append(", "); - } - formatHeaderElement(buffer, elems[i], quote); - } - - return buffer; - } - - - /** - * Estimates the length of formatted header elements. - * - * @param elems the header elements to format, or {@code null} - * - * @return a length estimate, in number of characters - */ - protected int estimateElementsLen(final HeaderElement[] elems) { - if ((elems == null) || (elems.length < 1)) { - return 0; - } - - int result = (elems.length-1) * 2; // elements separated by ", " - for (final HeaderElement elem : elems) { - result += estimateHeaderElementLen(elem); - } - - return result; - } - - - - /** - * Formats a header element. - * - * @param elem the header element to format - * @param quote {@code true} to always format with quoted values, - * {@code false} to use quotes only when necessary - * @param formatter the formatter to use, or {@code null} - * for the {@link #INSTANCE default} - * - * @return the formatted header element - */ - public static - String formatHeaderElement(final HeaderElement elem, - final boolean quote, - final HeaderValueFormatter formatter) { - return (formatter != null ? formatter : BasicHeaderValueFormatter.INSTANCE) - .formatHeaderElement(null, elem, quote).toString(); - } - - - // non-javadoc, see interface HeaderValueFormatter - @Override - public CharArrayBuffer formatHeaderElement(final CharArrayBuffer charBuffer, - final HeaderElement elem, - final boolean quote) { - Args.notNull(elem, "Header element"); - final int len = estimateHeaderElementLen(elem); - CharArrayBuffer buffer = charBuffer; - if (buffer == null) { - buffer = new CharArrayBuffer(len); - } else { - buffer.ensureCapacity(len); - } - - buffer.append(elem.getName()); - final String value = elem.getValue(); - if (value != null) { - buffer.append('='); - doFormatValue(buffer, value, quote); - } - - final int parcnt = elem.getParameterCount(); - if (parcnt > 0) { - for (int i=0; i 0) { - for (int i=0; i - estimateNameValuePairLen(elem.getParameter(i)); - } - } - - return result; - } - - - - - /** - * Formats a set of parameters. - * - * @param nvps the parameters to format - * @param quote {@code true} to always format with quoted values, - * {@code false} to use quotes only when necessary - * @param formatter the formatter to use, or {@code null} - * for the {@link #INSTANCE default} - * - * @return the formatted parameters - */ - public static - String formatParameters(final NameValuePair[] nvps, - final boolean quote, - final HeaderValueFormatter formatter) { - return (formatter != null ? formatter : BasicHeaderValueFormatter.INSTANCE) - .formatParameters(null, nvps, quote).toString(); - } - - - // non-javadoc, see interface HeaderValueFormatter - @Override - public CharArrayBuffer formatParameters(final CharArrayBuffer charBuffer, - final NameValuePair[] nvps, - final boolean quote) { - Args.notNull(nvps, "Header parameter array"); - final int len = estimateParametersLen(nvps); - CharArrayBuffer buffer = charBuffer; - if (buffer == null) { - buffer = new CharArrayBuffer(len); - } else { - buffer.ensureCapacity(len); - } - - for (int i = 0; i < nvps.length; i++) { - if (i > 0) { - buffer.append("; "); - } - formatNameValuePair(buffer, nvps[i], quote); - } - - return buffer; - } - - - /** - * Estimates the length of formatted parameters. - * - * @param nvps the parameters to format, or {@code null} - * - * @return a length estimate, in number of characters - */ - protected int estimateParametersLen(final NameValuePair[] nvps) { - if ((nvps == null) || (nvps.length < 1)) { - return 0; - } - - int result = (nvps.length-1) * 2; // "; " between the parameters - for (final NameValuePair nvp : nvps) { - result += estimateNameValuePairLen(nvp); - } - - return result; - } - - - /** - * Formats a name-value pair. - * - * @param nvp the name-value pair to format - * @param quote {@code true} to always format with a quoted value, - * {@code false} to use quotes only when necessary - * @param formatter the formatter to use, or {@code null} - * for the {@link #INSTANCE default} - * - * @return the formatted name-value pair - */ - public static - String formatNameValuePair(final NameValuePair nvp, - final boolean quote, - final HeaderValueFormatter formatter) { - return (formatter != null ? formatter : BasicHeaderValueFormatter.INSTANCE) - .formatNameValuePair(null, nvp, quote).toString(); - } - - - // non-javadoc, see interface HeaderValueFormatter - @Override - public CharArrayBuffer formatNameValuePair(final CharArrayBuffer charBuffer, - final NameValuePair nvp, - final boolean quote) { - Args.notNull(nvp, "Name / value pair"); - final int len = estimateNameValuePairLen(nvp); - CharArrayBuffer buffer = charBuffer; - if (buffer == null) { - buffer = new CharArrayBuffer(len); - } else { - buffer.ensureCapacity(len); - } - - buffer.append(nvp.getName()); - final String value = nvp.getValue(); - if (value != null) { - buffer.append('='); - doFormatValue(buffer, value, quote); - } - - return buffer; - } - - - /** - * Estimates the length of a formatted name-value pair. - * - * @param nvp the name-value pair to format, or {@code null} - * - * @return a length estimate, in number of characters - */ - protected int estimateNameValuePairLen(final NameValuePair nvp) { - if (nvp == null) { - return 0; - } - - int result = nvp.getName().length(); // name - final String value = nvp.getValue(); - if (value != null) { - // assume quotes, but no escaped characters - result += 3 + value.length(); // ="value" - } - return result; - } - - - /** - * Actually formats the value of a name-value pair. - * This does not include a leading = character. - * Called from {@link #formatNameValuePair formatNameValuePair}. - * - * @param buffer the buffer to append to, never {@code null} - * @param value the value to append, never {@code null} - * @param quote {@code true} to always format with quotes, - * {@code false} to use quotes only when necessary - */ - protected void doFormatValue(final CharArrayBuffer buffer, - final String value, - final boolean quote) { - - boolean quoteFlag = quote; - if (!quoteFlag) { - for (int i = 0; (i < value.length()) && !quoteFlag; i++) { - quoteFlag = isSeparator(value.charAt(i)); - } - } - - if (quoteFlag) { - buffer.append('"'); - } - for (int i = 0; i < value.length(); i++) { - final char ch = value.charAt(i); - if (isUnsafe(ch)) { - buffer.append('\\'); - } - buffer.append(ch); - } - if (quoteFlag) { - buffer.append('"'); - } - } - - - /** - * Checks whether a character is a {@link #SEPARATORS separator}. - * - * @param ch the character to check - * - * @return {@code true} if the character is a separator, - * {@code false} otherwise - */ - protected boolean isSeparator(final char ch) { - return SEPARATORS.indexOf(ch) >= 0; - } - - - /** - * Checks whether a character is {@link #UNSAFE_CHARS unsafe}. - * - * @param ch the character to check - * - * @return {@code true} if the character is unsafe, - * {@code false} otherwise - */ - protected boolean isUnsafe(final char ch) { - return UNSAFE_CHARS.indexOf(ch) >= 0; - } - - -} // class BasicHeaderValueFormatter diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHeaderValueParser.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHeaderValueParser.java deleted file mode 100644 index 31d920ec..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHeaderValueParser.java +++ /dev/null @@ -1,304 +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 com.tracelytics.ext.apache.http.message; - -import java.util.ArrayList; -import java.util.BitSet; -import java.util.List; - -import com.tracelytics.ext.apache.http.HeaderElement; -import com.tracelytics.ext.apache.http.NameValuePair; -import com.tracelytics.ext.apache.http.ParseException; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -/** - * Basic implementation for parsing header values into elements. - * Instances of this class are stateless and thread-safe. - * Derived classes are expected to maintain these properties. - * - * @since 4.0 - */ -@Immutable -public class BasicHeaderValueParser implements HeaderValueParser { - - /** - * A default instance of this class, for use as default or fallback. - * Note that {@link BasicHeaderValueParser} is not a singleton, there - * can be many instances of the class itself and of derived classes. - * The instance here provides non-customized, default behavior. - * - * @deprecated (4.3) use {@link #INSTANCE} - */ - @Deprecated - public final static - BasicHeaderValueParser DEFAULT = new BasicHeaderValueParser(); - - public final static BasicHeaderValueParser INSTANCE = new BasicHeaderValueParser(); - - private final static char PARAM_DELIMITER = ';'; - private final static char ELEM_DELIMITER = ','; - - // IMPORTANT! - // These private static variables must be treated as immutable and never exposed outside this class - private static final BitSet TOKEN_DELIMS = TokenParser.INIT_BITSET('=', PARAM_DELIMITER, ELEM_DELIMITER); - private static final BitSet VALUE_DELIMS = TokenParser.INIT_BITSET(PARAM_DELIMITER, ELEM_DELIMITER); - - private final TokenParser tokenParser; - - public BasicHeaderValueParser() { - this.tokenParser = TokenParser.INSTANCE; - } - - /** - * Parses elements with the given parser. - * - * @param value the header value to parse - * @param parser the parser to use, or {@code null} for default - * - * @return array holding the header elements, never {@code null} - * @throws ParseException in case of a parsing error - */ - public static - HeaderElement[] parseElements(final String value, - final HeaderValueParser parser) throws ParseException { - Args.notNull(value, "Value"); - - final CharArrayBuffer buffer = new CharArrayBuffer(value.length()); - buffer.append(value); - final ParserCursor cursor = new ParserCursor(0, value.length()); - return (parser != null ? parser : BasicHeaderValueParser.INSTANCE) - .parseElements(buffer, cursor); - } - - - // non-javadoc, see interface HeaderValueParser - @Override - public HeaderElement[] parseElements(final CharArrayBuffer buffer, - final ParserCursor cursor) { - Args.notNull(buffer, "Char array buffer"); - Args.notNull(cursor, "Parser cursor"); - final List elements = new ArrayList(); - while (!cursor.atEnd()) { - final HeaderElement element = parseHeaderElement(buffer, cursor); - if (!(element.getName().length() == 0 && element.getValue() == null)) { - elements.add(element); - } - } - return elements.toArray(new HeaderElement[elements.size()]); - } - - - /** - * Parses an element with the given parser. - * - * @param value the header element to parse - * @param parser the parser to use, or {@code null} for default - * - * @return the parsed header element - */ - public static - HeaderElement parseHeaderElement(final String value, - final HeaderValueParser parser) throws ParseException { - Args.notNull(value, "Value"); - - final CharArrayBuffer buffer = new CharArrayBuffer(value.length()); - buffer.append(value); - final ParserCursor cursor = new ParserCursor(0, value.length()); - return (parser != null ? parser : BasicHeaderValueParser.INSTANCE) - .parseHeaderElement(buffer, cursor); - } - - - // non-javadoc, see interface HeaderValueParser - @Override - public HeaderElement parseHeaderElement(final CharArrayBuffer buffer, - final ParserCursor cursor) { - Args.notNull(buffer, "Char array buffer"); - Args.notNull(cursor, "Parser cursor"); - final NameValuePair nvp = parseNameValuePair(buffer, cursor); - NameValuePair[] params = null; - if (!cursor.atEnd()) { - final char ch = buffer.charAt(cursor.getPos() - 1); - if (ch != ELEM_DELIMITER) { - params = parseParameters(buffer, cursor); - } - } - return createHeaderElement(nvp.getName(), nvp.getValue(), params); - } - - - /** - * Creates a header element. - * Called from {@link #parseHeaderElement}. - * - * @return a header element representing the argument - */ - protected HeaderElement createHeaderElement( - final String name, - final String value, - final NameValuePair[] params) { - return new BasicHeaderElement(name, value, params); - } - - - /** - * Parses parameters with the given parser. - * - * @param value the parameter list to parse - * @param parser the parser to use, or {@code null} for default - * - * @return array holding the parameters, never {@code null} - */ - public static - NameValuePair[] parseParameters(final String value, - final HeaderValueParser parser) throws ParseException { - Args.notNull(value, "Value"); - - final CharArrayBuffer buffer = new CharArrayBuffer(value.length()); - buffer.append(value); - final ParserCursor cursor = new ParserCursor(0, value.length()); - return (parser != null ? parser : BasicHeaderValueParser.INSTANCE) - .parseParameters(buffer, cursor); - } - - - - // non-javadoc, see interface HeaderValueParser - @Override - public NameValuePair[] parseParameters(final CharArrayBuffer buffer, - final ParserCursor cursor) { - Args.notNull(buffer, "Char array buffer"); - Args.notNull(cursor, "Parser cursor"); - tokenParser.skipWhiteSpace(buffer, cursor); - final List params = new ArrayList(); - while (!cursor.atEnd()) { - final NameValuePair param = parseNameValuePair(buffer, cursor); - params.add(param); - final char ch = buffer.charAt(cursor.getPos() - 1); - if (ch == ELEM_DELIMITER) { - break; - } - } - return params.toArray(new NameValuePair[params.size()]); - } - - /** - * Parses a name-value-pair with the given parser. - * - * @param value the NVP to parse - * @param parser the parser to use, or {@code null} for default - * - * @return the parsed name-value pair - */ - public static - NameValuePair parseNameValuePair(final String value, - final HeaderValueParser parser) throws ParseException { - Args.notNull(value, "Value"); - - final CharArrayBuffer buffer = new CharArrayBuffer(value.length()); - buffer.append(value); - final ParserCursor cursor = new ParserCursor(0, value.length()); - return (parser != null ? parser : BasicHeaderValueParser.INSTANCE) - .parseNameValuePair(buffer, cursor); - } - - - // non-javadoc, see interface HeaderValueParser - @Override - public NameValuePair parseNameValuePair(final CharArrayBuffer buffer, - final ParserCursor cursor) { - Args.notNull(buffer, "Char array buffer"); - Args.notNull(cursor, "Parser cursor"); - - final String name = tokenParser.parseToken(buffer, cursor, TOKEN_DELIMS); - if (cursor.atEnd()) { - return new BasicNameValuePair(name, null); - } - final int delim = buffer.charAt(cursor.getPos()); - cursor.updatePos(cursor.getPos() + 1); - if (delim != '=') { - return createNameValuePair(name, null); - } - final String value = tokenParser.parseValue(buffer, cursor, VALUE_DELIMS); - if (!cursor.atEnd()) { - cursor.updatePos(cursor.getPos() + 1); - } - return createNameValuePair(name, value); - } - - /** - * @deprecated (4.4) use {@link com.tracelytics.ext.apache.http.message.TokenParser} - */ - @Deprecated - public NameValuePair parseNameValuePair(final CharArrayBuffer buffer, - final ParserCursor cursor, - final char[] delimiters) { - Args.notNull(buffer, "Char array buffer"); - Args.notNull(cursor, "Parser cursor"); - - final BitSet delimSet = new BitSet(); - if (delimiters != null) { - for (char delimiter: delimiters) { - delimSet.set(delimiter); - } - } - delimSet.set('='); - final String name = tokenParser.parseToken(buffer, cursor, delimSet); - if (cursor.atEnd()) { - return new BasicNameValuePair(name, null); - } - final int delim = buffer.charAt(cursor.getPos()); - cursor.updatePos(cursor.getPos() + 1); - if (delim != '=') { - return createNameValuePair(name, null); - } - delimSet.clear('='); - final String value = tokenParser.parseValue(buffer, cursor, delimSet); - if (!cursor.atEnd()) { - cursor.updatePos(cursor.getPos() + 1); - } - return createNameValuePair(name, value); - } - - /** - * Creates a name-value pair. - * Called from {@link #parseNameValuePair}. - * - * @param name the name - * @param value the value, or {@code null} - * - * @return a name-value pair representing the arguments - */ - protected NameValuePair createNameValuePair(final String name, final String value) { - return new BasicNameValuePair(name, value); - } - -} - diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHttpEntityEnclosingRequest.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHttpEntityEnclosingRequest.java deleted file mode 100644 index 6004beaa..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHttpEntityEnclosingRequest.java +++ /dev/null @@ -1,78 +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 com.tracelytics.ext.apache.http.message; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpEntityEnclosingRequest; -import com.tracelytics.ext.apache.http.ProtocolVersion; -import com.tracelytics.ext.apache.http.RequestLine; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.protocol.HTTP; - -/** - * Basic implementation of {@link HttpEntityEnclosingRequest}. - * - * @since 4.0 - */ -@NotThreadSafe -public class BasicHttpEntityEnclosingRequest - extends BasicHttpRequest implements HttpEntityEnclosingRequest { - - private HttpEntity entity; - - public BasicHttpEntityEnclosingRequest(final String method, final String uri) { - super(method, uri); - } - - public BasicHttpEntityEnclosingRequest(final String method, final String uri, - final ProtocolVersion ver) { - super(method, uri, ver); - } - - public BasicHttpEntityEnclosingRequest(final RequestLine requestline) { - super(requestline); - } - - @Override - public HttpEntity getEntity() { - return this.entity; - } - - @Override - public void setEntity(final HttpEntity entity) { - this.entity = entity; - } - - @Override - public boolean expectContinue() { - final Header expect = getFirstHeader(HTTP.EXPECT_DIRECTIVE); - return expect != null && HTTP.EXPECT_CONTINUE.equalsIgnoreCase(expect.getValue()); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHttpRequest.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHttpRequest.java deleted file mode 100644 index e09a0ab2..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHttpRequest.java +++ /dev/null @@ -1,116 +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 com.tracelytics.ext.apache.http.message; - -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpVersion; -import com.tracelytics.ext.apache.http.ProtocolVersion; -import com.tracelytics.ext.apache.http.RequestLine; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Basic implementation of {@link HttpRequest}. - * - * @since 4.0 - */ -@NotThreadSafe -public class BasicHttpRequest extends AbstractHttpMessage implements HttpRequest { - - private final String method; - private final String uri; - - private RequestLine requestline; - - /** - * Creates an instance of this class using the given request method - * and URI. - * - * @param method request method. - * @param uri request URI. - */ - public BasicHttpRequest(final String method, final String uri) { - super(); - this.method = Args.notNull(method, "Method name"); - this.uri = Args.notNull(uri, "Request URI"); - this.requestline = null; - } - - /** - * Creates an instance of this class using the given request method, URI - * and the HTTP protocol version. - * - * @param method request method. - * @param uri request URI. - * @param ver HTTP protocol version. - */ - public BasicHttpRequest(final String method, final String uri, final ProtocolVersion ver) { - this(new BasicRequestLine(method, uri, ver)); - } - - /** - * Creates an instance of this class using the given request line. - * - * @param requestline request line. - */ - public BasicHttpRequest(final RequestLine requestline) { - super(); - this.requestline = Args.notNull(requestline, "Request line"); - this.method = requestline.getMethod(); - this.uri = requestline.getUri(); - } - - /** - * Returns the HTTP protocol version to be used for this request. - * - * @see #BasicHttpRequest(String, String) - */ - @Override - public ProtocolVersion getProtocolVersion() { - return getRequestLine().getProtocolVersion(); - } - - /** - * Returns the request line of this request. - * - * @see #BasicHttpRequest(String, String) - */ - @Override - public RequestLine getRequestLine() { - if (this.requestline == null) { - this.requestline = new BasicRequestLine(this.method, this.uri, HttpVersion.HTTP_1_1); - } - return this.requestline; - } - - @Override - public String toString() { - return this.method + ' ' + this.uri + ' ' + this.headergroup; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHttpResponse.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHttpResponse.java deleted file mode 100644 index de7be383..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicHttpResponse.java +++ /dev/null @@ -1,237 +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 com.tracelytics.ext.apache.http.message; - -import java.util.Locale; - -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.HttpVersion; -import com.tracelytics.ext.apache.http.ProtocolVersion; -import com.tracelytics.ext.apache.http.ReasonPhraseCatalog; -import com.tracelytics.ext.apache.http.StatusLine; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Basic implementation of {@link HttpResponse}. - * - * @see com.tracelytics.ext.apache.http.impl.DefaultHttpResponseFactory - * - * @since 4.0 - */ -@NotThreadSafe -public class BasicHttpResponse extends AbstractHttpMessage implements HttpResponse { - - private StatusLine statusline; - private ProtocolVersion ver; - private int code; - private String reasonPhrase; - private HttpEntity entity; - private final ReasonPhraseCatalog reasonCatalog; - private Locale locale; - - /** - * Creates a new response. - * This is the constructor to which all others map. - * - * @param statusline the status line - * @param catalog the reason phrase catalog, or - * {@code null} to disable automatic - * reason phrase lookup - * @param locale the locale for looking up reason phrases, or - * {@code null} for the system locale - */ - public BasicHttpResponse(final StatusLine statusline, - final ReasonPhraseCatalog catalog, - final Locale locale) { - super(); - this.statusline = Args.notNull(statusline, "Status line"); - this.ver = statusline.getProtocolVersion(); - this.code = statusline.getStatusCode(); - this.reasonPhrase = statusline.getReasonPhrase(); - this.reasonCatalog = catalog; - this.locale = locale; - } - - /** - * Creates a response from a status line. - * The response will not have a reason phrase catalog and - * use the system default locale. - * - * @param statusline the status line - */ - public BasicHttpResponse(final StatusLine statusline) { - super(); - this.statusline = Args.notNull(statusline, "Status line"); - this.ver = statusline.getProtocolVersion(); - this.code = statusline.getStatusCode(); - this.reasonPhrase = statusline.getReasonPhrase(); - this.reasonCatalog = null; - this.locale = null; - } - - /** - * Creates a response from elements of a status line. - * The response will not have a reason phrase catalog and - * use the system default locale. - * - * @param ver the protocol version of the response - * @param code the status code of the response - * @param reason the reason phrase to the status code, or - * {@code null} - */ - public BasicHttpResponse(final ProtocolVersion ver, - final int code, - final String reason) { - super(); - Args.notNegative(code, "Status code"); - this.statusline = null; - this.ver = ver; - this.code = code; - this.reasonPhrase = reason; - this.reasonCatalog = null; - this.locale = null; - } - - - // non-javadoc, see interface HttpMessage - @Override - public ProtocolVersion getProtocolVersion() { - return this.ver; - } - - // non-javadoc, see interface HttpResponse - @Override - public StatusLine getStatusLine() { - if (this.statusline == null) { - this.statusline = new BasicStatusLine( - this.ver != null ? this.ver : HttpVersion.HTTP_1_1, - this.code, - this.reasonPhrase != null ? this.reasonPhrase : getReason(this.code)); - } - return this.statusline; - } - - // non-javadoc, see interface HttpResponse - @Override - public HttpEntity getEntity() { - return this.entity; - } - - @Override - public Locale getLocale() { - return this.locale; - } - - // non-javadoc, see interface HttpResponse - @Override - public void setStatusLine(final StatusLine statusline) { - this.statusline = Args.notNull(statusline, "Status line"); - this.ver = statusline.getProtocolVersion(); - this.code = statusline.getStatusCode(); - this.reasonPhrase = statusline.getReasonPhrase(); - } - - // non-javadoc, see interface HttpResponse - @Override - public void setStatusLine(final ProtocolVersion ver, final int code) { - Args.notNegative(code, "Status code"); - this.statusline = null; - this.ver = ver; - this.code = code; - this.reasonPhrase = null; - } - - // non-javadoc, see interface HttpResponse - @Override - public void setStatusLine( - final ProtocolVersion ver, final int code, final String reason) { - Args.notNegative(code, "Status code"); - this.statusline = null; - this.ver = ver; - this.code = code; - this.reasonPhrase = reason; - } - - // non-javadoc, see interface HttpResponse - @Override - public void setStatusCode(final int code) { - Args.notNegative(code, "Status code"); - this.statusline = null; - this.code = code; - this.reasonPhrase = null; - } - - // non-javadoc, see interface HttpResponse - @Override - public void setReasonPhrase(final String reason) { - this.statusline = null; - this.reasonPhrase = reason; - } - - // non-javadoc, see interface HttpResponse - @Override - public void setEntity(final HttpEntity entity) { - this.entity = entity; - } - - @Override - public void setLocale(final Locale locale) { - this.locale = Args.notNull(locale, "Locale"); - this.statusline = null; - } - - /** - * Looks up a reason phrase. - * This method evaluates the currently set catalog and locale. - * It also handles a missing catalog. - * - * @param code the status code for which to look up the reason - * - * @return the reason phrase, or {@code null} if there is none - */ - protected String getReason(final int code) { - return this.reasonCatalog != null ? this.reasonCatalog.getReason(code, - this.locale != null ? this.locale : Locale.getDefault()) : null; - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - sb.append(getStatusLine()); - sb.append(' '); - sb.append(this.headergroup); - if (this.entity != null) { - sb.append(' '); - sb.append(this.entity); - } - return sb.toString(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicLineFormatter.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicLineFormatter.java deleted file mode 100644 index 449988ed..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicLineFormatter.java +++ /dev/null @@ -1,323 +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 com.tracelytics.ext.apache.http.message; - -import com.tracelytics.ext.apache.http.FormattedHeader; -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.ProtocolVersion; -import com.tracelytics.ext.apache.http.RequestLine; -import com.tracelytics.ext.apache.http.StatusLine; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -/** - * Interface for formatting elements of the HEAD section of an HTTP message. - * This is the complement to {@link LineParser}. - * There are individual methods for formatting a request line, a - * status line, or a header line. The formatting does not include the - * trailing line break sequence CR-LF. - * The formatted lines are returned in memory, the formatter does not depend - * on any specific IO mechanism. - * Instances of this interface are expected to be stateless and thread-safe. - * - * @since 4.0 - */ -@Immutable -public class BasicLineFormatter implements LineFormatter { - - /** - * A default instance of this class, for use as default or fallback. - * Note that {@link BasicLineFormatter} is not a singleton, there can - * be many instances of the class itself and of derived classes. - * The instance here provides non-customized, default behavior. - * - * @deprecated (4.3) use {@link #INSTANCE} - */ - @Deprecated - public final static BasicLineFormatter DEFAULT = new BasicLineFormatter(); - - public final static BasicLineFormatter INSTANCE = new BasicLineFormatter(); - - public BasicLineFormatter() { - super(); - } - - /** - * Obtains a buffer for formatting. - * - * @param charBuffer a buffer already available, or {@code null} - * - * @return the cleared argument buffer if there is one, or - * a new empty buffer that can be used for formatting - */ - protected CharArrayBuffer initBuffer(final CharArrayBuffer charBuffer) { - CharArrayBuffer buffer = charBuffer; - if (buffer != null) { - buffer.clear(); - } else { - buffer = new CharArrayBuffer(64); - } - return buffer; - } - - - /** - * Formats a protocol version. - * - * @param version the protocol version to format - * @param formatter the formatter to use, or - * {@code null} for the - * {@link #INSTANCE default} - * - * @return the formatted protocol version - */ - public static - String formatProtocolVersion(final ProtocolVersion version, - final LineFormatter formatter) { - return (formatter != null ? formatter : BasicLineFormatter.INSTANCE) - .appendProtocolVersion(null, version).toString(); - } - - - // non-javadoc, see interface LineFormatter - @Override - public CharArrayBuffer appendProtocolVersion(final CharArrayBuffer buffer, - final ProtocolVersion version) { - Args.notNull(version, "Protocol version"); - // can't use initBuffer, that would clear the argument! - CharArrayBuffer result = buffer; - final int len = estimateProtocolVersionLen(version); - if (result == null) { - result = new CharArrayBuffer(len); - } else { - result.ensureCapacity(len); - } - - result.append(version.getProtocol()); - result.append('/'); - result.append(Integer.toString(version.getMajor())); - result.append('.'); - result.append(Integer.toString(version.getMinor())); - - return result; - } - - - /** - * Guesses the length of a formatted protocol version. - * Needed to guess the length of a formatted request or status line. - * - * @param version the protocol version to format, or {@code null} - * - * @return the estimated length of the formatted protocol version, - * in characters - */ - protected int estimateProtocolVersionLen(final ProtocolVersion version) { - return version.getProtocol().length() + 4; // room for "HTTP/1.1" - } - - - /** - * Formats a request line. - * - * @param reqline the request line to format - * @param formatter the formatter to use, or - * {@code null} for the - * {@link #INSTANCE default} - * - * @return the formatted request line - */ - public static String formatRequestLine(final RequestLine reqline, - final LineFormatter formatter) { - return (formatter != null ? formatter : BasicLineFormatter.INSTANCE) - .formatRequestLine(null, reqline).toString(); - } - - - // non-javadoc, see interface LineFormatter - @Override - public CharArrayBuffer formatRequestLine(final CharArrayBuffer buffer, - final RequestLine reqline) { - Args.notNull(reqline, "Request line"); - final CharArrayBuffer result = initBuffer(buffer); - doFormatRequestLine(result, reqline); - - return result; - } - - - /** - * Actually formats a request line. - * Called from {@link #formatRequestLine}. - * - * @param buffer the empty buffer into which to format, - * never {@code null} - * @param reqline the request line to format, never {@code null} - */ - protected void doFormatRequestLine(final CharArrayBuffer buffer, - final RequestLine reqline) { - final String method = reqline.getMethod(); - final String uri = reqline.getUri(); - - // room for "GET /index.html HTTP/1.1" - final int len = method.length() + 1 + uri.length() + 1 + - estimateProtocolVersionLen(reqline.getProtocolVersion()); - buffer.ensureCapacity(len); - - buffer.append(method); - buffer.append(' '); - buffer.append(uri); - buffer.append(' '); - appendProtocolVersion(buffer, reqline.getProtocolVersion()); - } - - - - /** - * Formats a status line. - * - * @param statline the status line to format - * @param formatter the formatter to use, or - * {@code null} for the - * {@link #INSTANCE default} - * - * @return the formatted status line - */ - public static String formatStatusLine(final StatusLine statline, - final LineFormatter formatter) { - return (formatter != null ? formatter : BasicLineFormatter.INSTANCE) - .formatStatusLine(null, statline).toString(); - } - - - // non-javadoc, see interface LineFormatter - @Override - public CharArrayBuffer formatStatusLine(final CharArrayBuffer buffer, - final StatusLine statline) { - Args.notNull(statline, "Status line"); - final CharArrayBuffer result = initBuffer(buffer); - doFormatStatusLine(result, statline); - - return result; - } - - - /** - * Actually formats a status line. - * Called from {@link #formatStatusLine}. - * - * @param buffer the empty buffer into which to format, - * never {@code null} - * @param statline the status line to format, never {@code null} - */ - protected void doFormatStatusLine(final CharArrayBuffer buffer, - final StatusLine statline) { - - int len = estimateProtocolVersionLen(statline.getProtocolVersion()) - + 1 + 3 + 1; // room for "HTTP/1.1 200 " - final String reason = statline.getReasonPhrase(); - if (reason != null) { - len += reason.length(); - } - buffer.ensureCapacity(len); - - appendProtocolVersion(buffer, statline.getProtocolVersion()); - buffer.append(' '); - buffer.append(Integer.toString(statline.getStatusCode())); - buffer.append(' '); // keep whitespace even if reason phrase is empty - if (reason != null) { - buffer.append(reason); - } - } - - - /** - * Formats a header. - * - * @param header the header to format - * @param formatter the formatter to use, or - * {@code null} for the - * {@link #INSTANCE default} - * - * @return the formatted header - */ - public static String formatHeader(final Header header, - final LineFormatter formatter) { - return (formatter != null ? formatter : BasicLineFormatter.INSTANCE) - .formatHeader(null, header).toString(); - } - - - // non-javadoc, see interface LineFormatter - @Override - public CharArrayBuffer formatHeader(final CharArrayBuffer buffer, - final Header header) { - Args.notNull(header, "Header"); - final CharArrayBuffer result; - - if (header instanceof FormattedHeader) { - // If the header is backed by a buffer, re-use the buffer - result = ((FormattedHeader)header).getBuffer(); - } else { - result = initBuffer(buffer); - doFormatHeader(result, header); - } - return result; - - } // formatHeader - - - /** - * Actually formats a header. - * Called from {@link #formatHeader}. - * - * @param buffer the empty buffer into which to format, - * never {@code null} - * @param header the header to format, never {@code null} - */ - protected void doFormatHeader(final CharArrayBuffer buffer, - final Header header) { - final String name = header.getName(); - final String value = header.getValue(); - - int len = name.length() + 2; - if (value != null) { - len += value.length(); - } - buffer.ensureCapacity(len); - - buffer.append(name); - buffer.append(": "); - if (value != null) { - buffer.append(value); - } - } - - -} // class BasicLineFormatter diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicLineParser.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicLineParser.java deleted file mode 100644 index f847f54f..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicLineParser.java +++ /dev/null @@ -1,461 +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 com.tracelytics.ext.apache.http.message; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpVersion; -import com.tracelytics.ext.apache.http.ParseException; -import com.tracelytics.ext.apache.http.ProtocolVersion; -import com.tracelytics.ext.apache.http.RequestLine; -import com.tracelytics.ext.apache.http.StatusLine; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.protocol.HTTP; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -/** - * Basic parser for lines in the head section of an HTTP message. - * There are individual methods for parsing a request line, a - * status line, or a header line. - * The lines to parse are passed in memory, the parser does not depend - * on any specific IO mechanism. - * Instances of this class are stateless and thread-safe. - * Derived classes MUST maintain these properties. - * - *

- * Note: This class was created by refactoring parsing code located in - * various other classes. The author tags from those other classes have - * been replicated here, although the association with the parsing code - * taken from there has not been traced. - *

- * - * @since 4.0 - */ -@Immutable -public class BasicLineParser implements LineParser { - - /** - * A default instance of this class, for use as default or fallback. - * Note that {@link BasicLineParser} is not a singleton, there can - * be many instances of the class itself and of derived classes. - * The instance here provides non-customized, default behavior. - * - * @deprecated (4.3) use {@link #INSTANCE} - */ - @Deprecated - public final static BasicLineParser DEFAULT = new BasicLineParser(); - - public final static BasicLineParser INSTANCE = new BasicLineParser(); - - /** - * A version of the protocol to parse. - * The version is typically not relevant, but the protocol name. - */ - protected final ProtocolVersion protocol; - - - /** - * Creates a new line parser for the given HTTP-like protocol. - * - * @param proto a version of the protocol to parse, or - * {@code null} for HTTP. The actual version - * is not relevant, only the protocol name. - */ - public BasicLineParser(final ProtocolVersion proto) { - this.protocol = proto != null? proto : HttpVersion.HTTP_1_1; - } - - - /** - * Creates a new line parser for HTTP. - */ - public BasicLineParser() { - this(null); - } - - - public static - ProtocolVersion parseProtocolVersion(final String value, - final LineParser parser) throws ParseException { - Args.notNull(value, "Value"); - - final CharArrayBuffer buffer = new CharArrayBuffer(value.length()); - buffer.append(value); - final ParserCursor cursor = new ParserCursor(0, value.length()); - return (parser != null ? parser : BasicLineParser.INSTANCE) - .parseProtocolVersion(buffer, cursor); - } - - - // non-javadoc, see interface LineParser - @Override - public ProtocolVersion parseProtocolVersion(final CharArrayBuffer buffer, - final ParserCursor cursor) throws ParseException { - Args.notNull(buffer, "Char array buffer"); - Args.notNull(cursor, "Parser cursor"); - final String protoname = this.protocol.getProtocol(); - final int protolength = protoname.length(); - - final int indexFrom = cursor.getPos(); - final int indexTo = cursor.getUpperBound(); - - skipWhitespace(buffer, cursor); - - int i = cursor.getPos(); - - // long enough for "HTTP/1.1"? - if (i + protolength + 4 > indexTo) { - throw new ParseException - ("Not a valid protocol version: " + - buffer.substring(indexFrom, indexTo)); - } - - // check the protocol name and slash - boolean ok = true; - for (int j=0; ok && (j buffer.length()) { - return false; - } - - - // just check protocol name and slash, no need to analyse the version - boolean ok = true; - for (int j=0; ok && (j. - * - */ - -package com.tracelytics.ext.apache.http.message; - -import java.util.List; -import java.util.NoSuchElementException; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HeaderIterator; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.Asserts; - -/** - * Implementation of a {@link HeaderIterator} based on a {@link List}. - * For use by {@link HeaderGroup}. - * - * @since 4.0 - */ -@NotThreadSafe -public class BasicListHeaderIterator implements HeaderIterator { - - /** - * A list of headers to iterate over. - * Not all elements of this array are necessarily part of the iteration. - */ - protected final List
allHeaders; - - - /** - * The position of the next header in {@link #allHeaders allHeaders}. - * Negative if the iteration is over. - */ - protected int currentIndex; - - - /** - * The position of the last returned header. - * Negative if none has been returned so far. - */ - protected int lastIndex; - - - /** - * The header name to filter by. - * {@code null} to iterate over all headers in the array. - */ - protected String headerName; - - - - /** - * Creates a new header iterator. - * - * @param headers a list of headers over which to iterate - * @param name the name of the headers over which to iterate, or - * {@code null} for any - */ - public BasicListHeaderIterator(final List
headers, final String name) { - super(); - this.allHeaders = Args.notNull(headers, "Header list"); - this.headerName = name; - this.currentIndex = findNext(-1); - this.lastIndex = -1; - } - - - /** - * Determines the index of the next header. - * - * @param pos one less than the index to consider first, - * -1 to search for the first header - * - * @return the index of the next header that matches the filter name, - * or negative if there are no more headers - */ - protected int findNext(final int pos) { - int from = pos; - if (from < -1) { - return -1; - } - - final int to = this.allHeaders.size()-1; - boolean found = false; - while (!found && (from < to)) { - from++; - found = filterHeader(from); - } - return found ? from : -1; - } - - - /** - * Checks whether a header is part of the iteration. - * - * @param index the index of the header to check - * - * @return {@code true} if the header should be part of the - * iteration, {@code false} to skip - */ - protected boolean filterHeader(final int index) { - if (this.headerName == null) { - return true; - } - - // non-header elements, including null, will trigger exceptions - final String name = (this.allHeaders.get(index)).getName(); - - return this.headerName.equalsIgnoreCase(name); - } - - - // non-javadoc, see interface HeaderIterator - @Override - public boolean hasNext() { - return (this.currentIndex >= 0); - } - - - /** - * Obtains the next header from this iteration. - * - * @return the next header in this iteration - * - * @throws NoSuchElementException if there are no more headers - */ - @Override - public Header nextHeader() - throws NoSuchElementException { - - final int current = this.currentIndex; - if (current < 0) { - throw new NoSuchElementException("Iteration already finished."); - } - - this.lastIndex = current; - this.currentIndex = findNext(current); - - return this.allHeaders.get(current); - } - - - /** - * Returns the next header. - * Same as {@link #nextHeader nextHeader}, but not type-safe. - * - * @return the next header in this iteration - * - * @throws NoSuchElementException if there are no more headers - */ - @Override - public final Object next() - throws NoSuchElementException { - return nextHeader(); - } - - - /** - * Removes the header that was returned last. - */ - @Override - public void remove() - throws UnsupportedOperationException { - Asserts.check(this.lastIndex >= 0, "No header to remove"); - this.allHeaders.remove(this.lastIndex); - this.lastIndex = -1; - this.currentIndex--; // adjust for the removed element - } -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicNameValuePair.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicNameValuePair.java deleted file mode 100644 index f1c2af4a..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicNameValuePair.java +++ /dev/null @@ -1,113 +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 com.tracelytics.ext.apache.http.message; - -import java.io.Serializable; - -import com.tracelytics.ext.apache.http.NameValuePair; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.LangUtils; - -/** - * Basic implementation of {@link NameValuePair}. - * - * @since 4.0 - */ -@Immutable -public class BasicNameValuePair implements NameValuePair, Cloneable, Serializable { - - private static final long serialVersionUID = -6437800749411518984L; - - private final String name; - private final String value; - - /** - * Default Constructor taking a name and a value. The value may be null. - * - * @param name The name. - * @param value The value. - */ - public BasicNameValuePair(final String name, final String value) { - super(); - this.name = Args.notNull(name, "Name"); - this.value = value; - } - - @Override - public String getName() { - return this.name; - } - - @Override - public String getValue() { - return this.value; - } - - @Override - public String toString() { - // don't call complex default formatting for a simple toString - - if (this.value == null) { - return name; - } - final int len = this.name.length() + 1 + this.value.length(); - final StringBuilder buffer = new StringBuilder(len); - buffer.append(this.name); - buffer.append("="); - buffer.append(this.value); - return buffer.toString(); - } - - @Override - public boolean equals(final Object object) { - if (this == object) { - return true; - } - if (object instanceof NameValuePair) { - final BasicNameValuePair that = (BasicNameValuePair) object; - return this.name.equals(that.name) - && LangUtils.equals(this.value, that.value); - } - return false; - } - - @Override - public int hashCode() { - int hash = LangUtils.HASH_SEED; - hash = LangUtils.hashCode(hash, this.name); - hash = LangUtils.hashCode(hash, this.value); - return hash; - } - - @Override - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicRequestLine.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicRequestLine.java deleted file mode 100644 index f1319a5b..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicRequestLine.java +++ /dev/null @@ -1,86 +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 com.tracelytics.ext.apache.http.message; - -import java.io.Serializable; - -import com.tracelytics.ext.apache.http.ProtocolVersion; -import com.tracelytics.ext.apache.http.RequestLine; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Basic implementation of {@link RequestLine}. - * - * @since 4.0 - */ -@Immutable -public class BasicRequestLine implements RequestLine, Cloneable, Serializable { - - private static final long serialVersionUID = 2810581718468737193L; - - private final ProtocolVersion protoversion; - private final String method; - private final String uri; - - public BasicRequestLine(final String method, - final String uri, - final ProtocolVersion version) { - super(); - this.method = Args.notNull(method, "Method"); - this.uri = Args.notNull(uri, "URI"); - this.protoversion = Args.notNull(version, "Version"); - } - - @Override - public String getMethod() { - return this.method; - } - - @Override - public ProtocolVersion getProtocolVersion() { - return this.protoversion; - } - - @Override - public String getUri() { - return this.uri; - } - - @Override - public String toString() { - // no need for non-default formatting in toString() - return BasicLineFormatter.INSTANCE.formatRequestLine(null, this).toString(); - } - - @Override - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicStatusLine.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicStatusLine.java deleted file mode 100644 index 119f7149..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicStatusLine.java +++ /dev/null @@ -1,103 +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 com.tracelytics.ext.apache.http.message; - -import java.io.Serializable; - -import com.tracelytics.ext.apache.http.ProtocolVersion; -import com.tracelytics.ext.apache.http.StatusLine; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Basic implementation of {@link StatusLine} - * - * @since 4.0 - */ -@Immutable -public class BasicStatusLine implements StatusLine, Cloneable, Serializable { - - private static final long serialVersionUID = -2443303766890459269L; - - // ----------------------------------------------------- Instance Variables - - /** The protocol version. */ - private final ProtocolVersion protoVersion; - - /** The status code. */ - private final int statusCode; - - /** The reason phrase. */ - private final String reasonPhrase; - - // ----------------------------------------------------------- Constructors - /** - * Creates a new status line with the given version, status, and reason. - * - * @param version the protocol version of the response - * @param statusCode the status code of the response - * @param reasonPhrase the reason phrase to the status code, or - * {@code null} - */ - public BasicStatusLine(final ProtocolVersion version, final int statusCode, - final String reasonPhrase) { - super(); - this.protoVersion = Args.notNull(version, "Version"); - this.statusCode = Args.notNegative(statusCode, "Status code"); - this.reasonPhrase = reasonPhrase; - } - - // --------------------------------------------------------- Public Methods - - @Override - public int getStatusCode() { - return this.statusCode; - } - - @Override - public ProtocolVersion getProtocolVersion() { - return this.protoVersion; - } - - @Override - public String getReasonPhrase() { - return this.reasonPhrase; - } - - @Override - public String toString() { - // no need for non-default formatting in toString() - return BasicLineFormatter.INSTANCE.formatStatusLine(null, this).toString(); - } - - @Override - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicTokenIterator.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicTokenIterator.java deleted file mode 100644 index cb0d8390..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BasicTokenIterator.java +++ /dev/null @@ -1,419 +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 com.tracelytics.ext.apache.http.message; - -import java.util.NoSuchElementException; - -import com.tracelytics.ext.apache.http.HeaderIterator; -import com.tracelytics.ext.apache.http.ParseException; -import com.tracelytics.ext.apache.http.TokenIterator; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Basic implementation of a {@link TokenIterator}. - * This implementation parses {@code #token} sequences as - * defined by RFC 2616, section 2. - * It extends that definition somewhat beyond US-ASCII. - * - * @since 4.0 - */ -@NotThreadSafe -public class BasicTokenIterator implements TokenIterator { - - /** The HTTP separator characters. Defined in RFC 2616, section 2.2. */ - // the order of the characters here is adjusted to put the - // most likely candidates at the beginning of the collection - public final static String HTTP_SEPARATORS = " ,;=()<>@:\\\"/[]?{}\t"; - - - /** The iterator from which to obtain the next header. */ - protected final HeaderIterator headerIt; - - /** - * The value of the current header. - * This is the header value that includes {@link #currentToken}. - * Undefined if the iteration is over. - */ - protected String currentHeader; - - /** - * The token to be returned by the next call to {@link #nextToken()}. - * {@code null} if the iteration is over. - */ - protected String currentToken; - - /** - * The position after {@link #currentToken} in {@link #currentHeader}. - * Undefined if the iteration is over. - */ - protected int searchPos; - - - /** - * Creates a new instance of {@link BasicTokenIterator}. - * - * @param headerIterator the iterator for the headers to tokenize - */ - public BasicTokenIterator(final HeaderIterator headerIterator) { - super(); - this.headerIt = Args.notNull(headerIterator, "Header iterator"); - this.searchPos = findNext(-1); - } - - - // non-javadoc, see interface TokenIterator - @Override - public boolean hasNext() { - return (this.currentToken != null); - } - - - /** - * Obtains the next token from this iteration. - * - * @return the next token in this iteration - * - * @throws NoSuchElementException if the iteration is already over - * @throws ParseException if an invalid header value is encountered - */ - @Override - public String nextToken() - throws NoSuchElementException, ParseException { - - if (this.currentToken == null) { - throw new NoSuchElementException("Iteration already finished."); - } - - final String result = this.currentToken; - // updates currentToken, may trigger ParseException: - this.searchPos = findNext(this.searchPos); - - return result; - } - - - /** - * Returns the next token. - * Same as {@link #nextToken}, but with generic return type. - * - * @return the next token in this iteration - * - * @throws NoSuchElementException if there are no more tokens - * @throws ParseException if an invalid header value is encountered - */ - @Override - public final Object next() - throws NoSuchElementException, ParseException { - return nextToken(); - } - - - /** - * Removing tokens is not supported. - * - * @throws UnsupportedOperationException always - */ - @Override - public final void remove() - throws UnsupportedOperationException { - - throw new UnsupportedOperationException - ("Removing tokens is not supported."); - } - - - /** - * Determines the next token. - * If found, the token is stored in {@link #currentToken}. - * The return value indicates the position after the token - * in {@link #currentHeader}. If necessary, the next header - * will be obtained from {@link #headerIt}. - * If not found, {@link #currentToken} is set to {@code null}. - * - * @param pos the position in the current header at which to - * start the search, -1 to search in the first header - * - * @return the position after the found token in the current header, or - * negative if there was no next token - * - * @throws ParseException if an invalid header value is encountered - */ - protected int findNext(final int pos) throws ParseException { - int from = pos; - if (from < 0) { - // called from the constructor, initialize the first header - if (!this.headerIt.hasNext()) { - return -1; - } - this.currentHeader = this.headerIt.nextHeader().getValue(); - from = 0; - } else { - // called after a token, make sure there is a separator - from = findTokenSeparator(from); - } - - final int start = findTokenStart(from); - if (start < 0) { - this.currentToken = null; - return -1; // nothing found - } - - final int end = findTokenEnd(start); - this.currentToken = createToken(this.currentHeader, start, end); - return end; - } - - - /** - * Creates a new token to be returned. - * Called from {@link #findNext findNext} after the token is identified. - * The default implementation simply calls - * {@link java.lang.String#substring String.substring}. - *

- * If header values are significantly longer than tokens, and some - * tokens are permanently referenced by the application, there can - * be problems with garbage collection. A substring will hold a - * reference to the full characters of the original string and - * therefore occupies more memory than might be expected. - * To avoid this, override this method and create a new string - * instead of a substring. - *

- * - * @param value the full header value from which to create a token - * @param start the index of the first token character - * @param end the index after the last token character - * - * @return a string representing the token identified by the arguments - */ - protected String createToken(final String value, final int start, final int end) { - return value.substring(start, end); - } - - - /** - * Determines the starting position of the next token. - * This method will iterate over headers if necessary. - * - * @param pos the position in the current header at which to - * start the search - * - * @return the position of the token start in the current header, - * negative if no token start could be found - */ - protected int findTokenStart(final int pos) { - int from = Args.notNegative(pos, "Search position"); - boolean found = false; - while (!found && (this.currentHeader != null)) { - - final int to = this.currentHeader.length(); - while (!found && (from < to)) { - - final char ch = this.currentHeader.charAt(from); - if (isTokenSeparator(ch) || isWhitespace(ch)) { - // whitspace and token separators are skipped - from++; - } else if (isTokenChar(this.currentHeader.charAt(from))) { - // found the start of a token - found = true; - } else { - throw new ParseException - ("Invalid character before token (pos " + from + - "): " + this.currentHeader); - } - } - if (!found) { - if (this.headerIt.hasNext()) { - this.currentHeader = this.headerIt.nextHeader().getValue(); - from = 0; - } else { - this.currentHeader = null; - } - } - } // while headers - - return found ? from : -1; - } - - - /** - * Determines the position of the next token separator. - * Because of multi-header joining rules, the end of a - * header value is a token separator. This method does - * therefore not need to iterate over headers. - * - * @param pos the position in the current header at which to - * start the search - * - * @return the position of a token separator in the current header, - * or at the end - * - * @throws ParseException - * if a new token is found before a token separator. - * RFC 2616, section 2.1 explicitly requires a comma between - * tokens for {@code #}. - */ - protected int findTokenSeparator(final int pos) { - int from = Args.notNegative(pos, "Search position"); - boolean found = false; - final int to = this.currentHeader.length(); - while (!found && (from < to)) { - final char ch = this.currentHeader.charAt(from); - if (isTokenSeparator(ch)) { - found = true; - } else if (isWhitespace(ch)) { - from++; - } else if (isTokenChar(ch)) { - throw new ParseException - ("Tokens without separator (pos " + from + - "): " + this.currentHeader); - } else { - throw new ParseException - ("Invalid character after token (pos " + from + - "): " + this.currentHeader); - } - } - - return from; - } - - - /** - * Determines the ending position of the current token. - * This method will not leave the current header value, - * since the end of the header value is a token boundary. - * - * @param from the position of the first character of the token - * - * @return the position after the last character of the token. - * The behavior is undefined if {@code from} does not - * point to a token character in the current header value. - */ - protected int findTokenEnd(final int from) { - Args.notNegative(from, "Search position"); - final int to = this.currentHeader.length(); - int end = from+1; - while ((end < to) && isTokenChar(this.currentHeader.charAt(end))) { - end++; - } - - return end; - } - - - /** - * Checks whether a character is a token separator. - * RFC 2616, section 2.1 defines comma as the separator for - * {@code #token} sequences. The end of a header value will - * also separate tokens, but that is not a character check. - * - * @param ch the character to check - * - * @return {@code true} if the character is a token separator, - * {@code false} otherwise - */ - protected boolean isTokenSeparator(final char ch) { - return (ch == ','); - } - - - /** - * Checks whether a character is a whitespace character. - * RFC 2616, section 2.2 defines space and horizontal tab as whitespace. - * The optional preceeding line break is irrelevant, since header - * continuation is handled transparently when parsing messages. - * - * @param ch the character to check - * - * @return {@code true} if the character is whitespace, - * {@code false} otherwise - */ - protected boolean isWhitespace(final char ch) { - - // we do not use Character.isWhitspace(ch) here, since that allows - // many control characters which are not whitespace as per RFC 2616 - return ((ch == '\t') || Character.isSpaceChar(ch)); - } - - - /** - * Checks whether a character is a valid token character. - * Whitespace, control characters, and HTTP separators are not - * valid token characters. The HTTP specification (RFC 2616, section 2.2) - * defines tokens only for the US-ASCII character set, this - * method extends the definition to other character sets. - * - * @param ch the character to check - * - * @return {@code true} if the character is a valid token start, - * {@code false} otherwise - */ - protected boolean isTokenChar(final char ch) { - - // common sense extension of ALPHA + DIGIT - if (Character.isLetterOrDigit(ch)) { - return true; - } - - // common sense extension of CTL - if (Character.isISOControl(ch)) { - return false; - } - - // no common sense extension for this - if (isHttpSeparator(ch)) { - return false; - } - - // RFC 2616, section 2.2 defines a token character as - // "any CHAR except CTLs or separators". The controls - // and separators are included in the checks above. - // This will yield unexpected results for Unicode format characters. - // If that is a problem, overwrite isHttpSeparator(char) to filter - // out the false positives. - return true; - } - - - /** - * Checks whether a character is an HTTP separator. - * The implementation in this class checks only for the HTTP separators - * defined in RFC 2616, section 2.2. If you need to detect other - * separators beyond the US-ASCII character set, override this method. - * - * @param ch the character to check - * - * @return {@code true} if the character is an HTTP separator - */ - protected boolean isHttpSeparator(final char ch) { - return (HTTP_SEPARATORS.indexOf(ch) >= 0); - } - - -} // class BasicTokenIterator - diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BufferedHeader.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BufferedHeader.java deleted file mode 100644 index b792e4ff..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/BufferedHeader.java +++ /dev/null @@ -1,135 +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 com.tracelytics.ext.apache.http.message; - -import java.io.Serializable; - -import com.tracelytics.ext.apache.http.FormattedHeader; -import com.tracelytics.ext.apache.http.HeaderElement; -import com.tracelytics.ext.apache.http.ParseException; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -/** - * This class represents a raw HTTP header whose content is parsed 'on demand' - * only when the header value needs to be consumed. - * - * @since 4.0 - */ -@NotThreadSafe -public class BufferedHeader implements FormattedHeader, Cloneable, Serializable { - - private static final long serialVersionUID = -2768352615787625448L; - - /** - * Header name. - */ - private final String name; - - /** - * The buffer containing the entire header line. - */ - private final CharArrayBuffer buffer; - - /** - * The beginning of the header value in the buffer - */ - private final int valuePos; - - - /** - * Creates a new header from a buffer. - * The name of the header will be parsed immediately, - * the value only if it is accessed. - * - * @param buffer the buffer containing the header to represent - * - * @throws ParseException in case of a parse error - */ - public BufferedHeader(final CharArrayBuffer buffer) - throws ParseException { - - super(); - Args.notNull(buffer, "Char array buffer"); - final int colon = buffer.indexOf(':'); - if (colon == -1) { - throw new ParseException - ("Invalid header: " + buffer.toString()); - } - final String s = buffer.substringTrimmed(0, colon); - if (s.length() == 0) { - throw new ParseException - ("Invalid header: " + buffer.toString()); - } - this.buffer = buffer; - this.name = s; - this.valuePos = colon + 1; - } - - - @Override - public String getName() { - return this.name; - } - - @Override - public String getValue() { - return this.buffer.substringTrimmed(this.valuePos, this.buffer.length()); - } - - @Override - public HeaderElement[] getElements() throws ParseException { - final ParserCursor cursor = new ParserCursor(0, this.buffer.length()); - cursor.updatePos(this.valuePos); - return BasicHeaderValueParser.INSTANCE.parseElements(this.buffer, cursor); - } - - @Override - public int getValuePos() { - return this.valuePos; - } - - @Override - public CharArrayBuffer getBuffer() { - return this.buffer; - } - - @Override - public String toString() { - return this.buffer.toString(); - } - - @Override - public Object clone() throws CloneNotSupportedException { - // buffer is considered immutable - // no need to make a copy of it - return super.clone(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/HeaderGroup.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/HeaderGroup.java deleted file mode 100644 index 422ae818..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/HeaderGroup.java +++ /dev/null @@ -1,311 +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 com.tracelytics.ext.apache.http.message; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Locale; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HeaderIterator; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -/** - * A class for combining a set of headers. - * This class allows for multiple headers with the same name and - * keeps track of the order in which headers were added. - * - * - * @since 4.0 - */ -@NotThreadSafe -public class HeaderGroup implements Cloneable, Serializable { - - private static final long serialVersionUID = 2608834160639271617L; - - /** The list of headers for this group, in the order in which they were added */ - private final List
headers; - - /** - * Constructor for HeaderGroup. - */ - public HeaderGroup() { - this.headers = new ArrayList
(16); - } - - /** - * Removes any contained headers. - */ - public void clear() { - headers.clear(); - } - - /** - * Adds the given header to the group. The order in which this header was - * added is preserved. - * - * @param header the header to add - */ - public void addHeader(final Header header) { - if (header == null) { - return; - } - headers.add(header); - } - - /** - * Removes the given header. - * - * @param header the header to remove - */ - public void removeHeader(final Header header) { - if (header == null) { - return; - } - headers.remove(header); - } - - /** - * Replaces the first occurence of the header with the same name. If no header with - * the same name is found the given header is added to the end of the list. - * - * @param header the new header that should replace the first header with the same - * name if present in the list. - */ - public void updateHeader(final Header header) { - if (header == null) { - return; - } - // HTTPCORE-361 : we don't use the for-each syntax, i.e. - // for (Header header : headers) - // as that creates an Iterator that needs to be garbage-collected - for (int i = 0; i < this.headers.size(); i++) { - final Header current = this.headers.get(i); - if (current.getName().equalsIgnoreCase(header.getName())) { - this.headers.set(i, header); - return; - } - } - this.headers.add(header); - } - - /** - * Sets all of the headers contained within this group overriding any - * existing headers. The headers are added in the order in which they appear - * in the array. - * - * @param headers the headers to set - */ - public void setHeaders(final Header[] headers) { - clear(); - if (headers == null) { - return; - } - Collections.addAll(this.headers, headers); - } - - /** - * Gets a header representing all of the header values with the given name. - * If more that one header with the given name exists the values will be - * combined with a "," as per RFC 2616. - * - *

Header name comparison is case insensitive. - * - * @param name the name of the header(s) to get - * @return a header with a condensed value or {@code null} if no - * headers by the given name are present - */ - public Header getCondensedHeader(final String name) { - final Header[] hdrs = getHeaders(name); - - if (hdrs.length == 0) { - return null; - } else if (hdrs.length == 1) { - return hdrs[0]; - } else { - final CharArrayBuffer valueBuffer = new CharArrayBuffer(128); - valueBuffer.append(hdrs[0].getValue()); - for (int i = 1; i < hdrs.length; i++) { - valueBuffer.append(", "); - valueBuffer.append(hdrs[i].getValue()); - } - - return new BasicHeader(name.toLowerCase(Locale.ROOT), valueBuffer.toString()); - } - } - - /** - * Gets all of the headers with the given name. The returned array - * maintains the relative order in which the headers were added. - * - *

Header name comparison is case insensitive. - * - * @param name the name of the header(s) to get - * - * @return an array of length ≥ 0 - */ - public Header[] getHeaders(final String name) { - final List

headersFound = new ArrayList
(); - // HTTPCORE-361 : we don't use the for-each syntax, i.e. - // for (Header header : headers) - // as that creates an Iterator that needs to be garbage-collected - for (int i = 0; i < this.headers.size(); i++) { - final Header header = this.headers.get(i); - if (header.getName().equalsIgnoreCase(name)) { - headersFound.add(header); - } - } - - return headersFound.toArray(new Header[headersFound.size()]); - } - - /** - * Gets the first header with the given name. - * - *

Header name comparison is case insensitive. - * - * @param name the name of the header to get - * @return the first header or {@code null} - */ - public Header getFirstHeader(final String name) { - // HTTPCORE-361 : we don't use the for-each syntax, i.e. - // for (Header header : headers) - // as that creates an Iterator that needs to be garbage-collected - for (int i = 0; i < this.headers.size(); i++) { - final Header header = this.headers.get(i); - if (header.getName().equalsIgnoreCase(name)) { - return header; - } - } - return null; - } - - /** - * Gets the last header with the given name. - * - *

Header name comparison is case insensitive. - * - * @param name the name of the header to get - * @return the last header or {@code null} - */ - public Header getLastHeader(final String name) { - // start at the end of the list and work backwards - for (int i = headers.size() - 1; i >= 0; i--) { - final Header header = headers.get(i); - if (header.getName().equalsIgnoreCase(name)) { - return header; - } - } - - return null; - } - - /** - * Gets all of the headers contained within this group. - * - * @return an array of length ≥ 0 - */ - public Header[] getAllHeaders() { - return headers.toArray(new Header[headers.size()]); - } - - /** - * Tests if headers with the given name are contained within this group. - * - *

Header name comparison is case insensitive. - * - * @param name the header name to test for - * @return {@code true} if at least one header with the name is - * contained, {@code false} otherwise - */ - public boolean containsHeader(final String name) { - // HTTPCORE-361 : we don't use the for-each syntax, i.e. - // for (Header header : headers) - // as that creates an Iterator that needs to be garbage-collected - for (int i = 0; i < this.headers.size(); i++) { - final Header header = this.headers.get(i); - if (header.getName().equalsIgnoreCase(name)) { - return true; - } - } - - return false; - } - - /** - * Returns an iterator over this group of headers. - * - * @return iterator over this group of headers. - * - * @since 4.0 - */ - public HeaderIterator iterator() { - return new BasicListHeaderIterator(this.headers, null); - } - - /** - * Returns an iterator over the headers with a given name in this group. - * - * @param name the name of the headers over which to iterate, or - * {@code null} for all headers - * - * @return iterator over some headers in this group. - * - * @since 4.0 - */ - public HeaderIterator iterator(final String name) { - return new BasicListHeaderIterator(this.headers, name); - } - - /** - * Returns a copy of this object - * - * @return copy of this object - * - * @since 4.0 - */ - public HeaderGroup copy() { - final HeaderGroup clone = new HeaderGroup(); - clone.headers.addAll(this.headers); - return clone; - } - - @Override - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } - - @Override - public String toString() { - return this.headers.toString(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/HeaderValueFormatter.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/HeaderValueFormatter.java deleted file mode 100644 index 53a6bba3..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/HeaderValueFormatter.java +++ /dev/null @@ -1,122 +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 com.tracelytics.ext.apache.http.message; - -import com.tracelytics.ext.apache.http.HeaderElement; -import com.tracelytics.ext.apache.http.NameValuePair; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -/** - * Interface for formatting elements of a header value. - * This is the complement to {@link HeaderValueParser}. - * Instances of this interface are expected to be stateless and thread-safe. - * - *

- * All formatting methods accept an optional buffer argument. - * If a buffer is passed in, the formatted element will be appended - * and the modified buffer is returned. If no buffer is passed in, - * a new buffer will be created and filled with the formatted element. - * In both cases, the caller is allowed to modify the returned buffer. - *

- * - * @since 4.0 - */ -public interface HeaderValueFormatter { - - /** - * Formats an array of header elements. - * - * @param buffer the buffer to append to, or - * {@code null} to create a new buffer - * @param elems the header elements to format - * @param quote {@code true} to always format with quoted values, - * {@code false} to use quotes only when necessary - * - * @return a buffer with the formatted header elements. - * If the {@code buffer} argument was not {@code null}, - * that buffer will be used and returned. - */ - CharArrayBuffer formatElements(CharArrayBuffer buffer, - HeaderElement[] elems, - boolean quote); - - /** - * Formats one header element. - * - * @param buffer the buffer to append to, or - * {@code null} to create a new buffer - * @param elem the header element to format - * @param quote {@code true} to always format with quoted values, - * {@code false} to use quotes only when necessary - * - * @return a buffer with the formatted header element. - * If the {@code buffer} argument was not {@code null}, - * that buffer will be used and returned. - */ - CharArrayBuffer formatHeaderElement(CharArrayBuffer buffer, - HeaderElement elem, - boolean quote); - - /** - * Formats the parameters of a header element. - * That's a list of name-value pairs, to be separated by semicolons. - * This method will not generate a leading semicolon. - * - * @param buffer the buffer to append to, or - * {@code null} to create a new buffer - * @param nvps the parameters (name-value pairs) to format - * @param quote {@code true} to always format with quoted values, - * {@code false} to use quotes only when necessary - * - * @return a buffer with the formatted parameters. - * If the {@code buffer} argument was not {@code null}, - * that buffer will be used and returned. - */ - CharArrayBuffer formatParameters(CharArrayBuffer buffer, - NameValuePair[] nvps, - boolean quote); - - /** - * Formats one name-value pair, where the value is optional. - * - * @param buffer the buffer to append to, or - * {@code null} to create a new buffer - * @param nvp the name-value pair to format - * @param quote {@code true} to always format with a quoted value, - * {@code false} to use quotes only when necessary - * - * @return a buffer with the formatted name-value pair. - * If the {@code buffer} argument was not {@code null}, - * that buffer will be used and returned. - */ - CharArrayBuffer formatNameValuePair(CharArrayBuffer buffer, - NameValuePair nvp, - boolean quote); - -} - diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/HeaderValueParser.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/HeaderValueParser.java deleted file mode 100644 index 472d9fef..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/HeaderValueParser.java +++ /dev/null @@ -1,134 +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 com.tracelytics.ext.apache.http.message; - -import com.tracelytics.ext.apache.http.HeaderElement; -import com.tracelytics.ext.apache.http.NameValuePair; -import com.tracelytics.ext.apache.http.ParseException; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -/** - * Interface for parsing header values into elements. - * Instances of this interface are expected to be stateless and thread-safe. - * - * @since 4.0 - */ -public interface HeaderValueParser { - - /** - * Parses a header value into elements. - * Parse errors are indicated as {@code RuntimeException}. - *

- * Some HTTP headers (such as the set-cookie header) have values that - * can be decomposed into multiple elements. In order to be processed - * by this parser, such headers must be in the following form: - *

- *
-     * header  = [ element ] *( "," [ element ] )
-     * element = name [ "=" [ value ] ] *( ";" [ param ] )
-     * param   = name [ "=" [ value ] ]
-     *
-     * name    = token
-     * value   = ( token | quoted-string )
-     *
-     * token         = 1*<any char except "=", ",", ";", <"> and
-     *                       white space>
-     * quoted-string = <"> *( text | quoted-char ) <">
-     * text          = any char except <">
-     * quoted-char   = "\" char
-     * 
- *

- * Any amount of white space is allowed between any part of the - * header, element or param and is ignored. A missing value in any - * element or param will be stored as the empty {@link String}; - * if the "=" is also missing null will be stored instead. - *

- * - * @param buffer buffer holding the header value to parse - * @param cursor the parser cursor containing the current position and - * the bounds within the buffer for the parsing operation - * - * @return an array holding all elements of the header value - * - * @throws ParseException in case of a parsing error - */ - HeaderElement[] parseElements( - CharArrayBuffer buffer, - ParserCursor cursor) throws ParseException; - - /** - * Parses a single header element. - * A header element consist of a semicolon-separate list - * of name=value definitions. - * - * @param buffer buffer holding the element to parse - * @param cursor the parser cursor containing the current position and - * the bounds within the buffer for the parsing operation - * - * @return the parsed element - * - * @throws ParseException in case of a parse error - */ - HeaderElement parseHeaderElement( - CharArrayBuffer buffer, - ParserCursor cursor) throws ParseException; - - /** - * Parses a list of name-value pairs. - * These lists are used to specify parameters to a header element. - * Parse errors are indicated as {@code ParseException}. - * - * @param buffer buffer holding the name-value list to parse - * @param cursor the parser cursor containing the current position and - * the bounds within the buffer for the parsing operation - * - * @return an array holding all items of the name-value list - * - * @throws ParseException in case of a parse error - */ - NameValuePair[] parseParameters( - CharArrayBuffer buffer, - ParserCursor cursor) throws ParseException; - - - /** - * Parses a name=value specification, where the = and value are optional. - * - * @param buffer the buffer holding the name-value pair to parse - * @param cursor the parser cursor containing the current position and - * the bounds within the buffer for the parsing operation - * - * @return the name-value pair, where the value is {@code null} - * if no value is specified - */ - NameValuePair parseNameValuePair( - CharArrayBuffer buffer, - ParserCursor cursor) throws ParseException; - -} - diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/LineFormatter.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/LineFormatter.java deleted file mode 100644 index 392f99cb..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/LineFormatter.java +++ /dev/null @@ -1,132 +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 com.tracelytics.ext.apache.http.message; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.ProtocolVersion; -import com.tracelytics.ext.apache.http.RequestLine; -import com.tracelytics.ext.apache.http.StatusLine; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -/** - * Interface for formatting elements of the HEAD section of an HTTP message. - * This is the complement to {@link LineParser}. - * There are individual methods for formatting a request line, a - * status line, or a header line. The formatting does not include the - * trailing line break sequence CR-LF. - * Instances of this interface are expected to be stateless and thread-safe. - * - *

- * The formatted lines are returned in memory, the formatter does not depend - * on any specific IO mechanism. - * In order to avoid unnecessary creation of temporary objects, - * a buffer can be passed as argument to all formatting methods. - * The implementation may or may not actually use that buffer for formatting. - * If it is used, the buffer will first be cleared by the - * {@code formatXXX} methods. - * The argument buffer can always be re-used after the call. The buffer - * returned as the result, if it is different from the argument buffer, - * MUST NOT be modified. - *

- * - * @since 4.0 - */ -public interface LineFormatter { - - /** - * Formats a protocol version. - * This method does not follow the general contract for - * {@code buffer} arguments. - * It does not clear the argument buffer, but appends instead. - * The returned buffer can always be modified by the caller. - * Because of these differing conventions, it is not named - * {@code formatProtocolVersion}. - * - * @param buffer a buffer to which to append, or {@code null} - * @param version the protocol version to format - * - * @return a buffer with the formatted protocol version appended. - * The caller is allowed to modify the result buffer. - * If the {@code buffer} argument is not {@code null}, - * the returned buffer is the argument buffer. - */ - CharArrayBuffer appendProtocolVersion(CharArrayBuffer buffer, - ProtocolVersion version); - - /** - * Formats a request line. - * - * @param buffer a buffer available for formatting, or - * {@code null}. - * The buffer will be cleared before use. - * @param reqline the request line to format - * - * @return the formatted request line - */ - CharArrayBuffer formatRequestLine(CharArrayBuffer buffer, - RequestLine reqline); - - /** - * Formats a status line. - * - * @param buffer a buffer available for formatting, or - * {@code null}. - * The buffer will be cleared before use. - * @param statline the status line to format - * - * @return the formatted status line - * - * @throws com.tracelytics.ext.apache.http.ParseException in case of a parse error - */ - CharArrayBuffer formatStatusLine(CharArrayBuffer buffer, - StatusLine statline); - - /** - * Formats a header. - * Due to header continuation, the result may be multiple lines. - * In order to generate well-formed HTTP, the lines in the result - * must be separated by the HTTP line break sequence CR-LF. - * There is no trailing CR-LF in the result. - *

- * See the class comment for details about the buffer argument. - *

- * - * @param buffer a buffer available for formatting, or - * {@code null}. - * The buffer will be cleared before use. - * @param header the header to format - * - * @return a buffer holding the formatted header, never {@code null}. - * The returned buffer may be different from the argument buffer. - * - * @throws com.tracelytics.ext.apache.http.ParseException in case of a parse error - */ - CharArrayBuffer formatHeader(CharArrayBuffer buffer, - Header header); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/LineParser.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/LineParser.java deleted file mode 100644 index 140c1f6c..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/LineParser.java +++ /dev/null @@ -1,137 +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 com.tracelytics.ext.apache.http.message; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.ParseException; -import com.tracelytics.ext.apache.http.ProtocolVersion; -import com.tracelytics.ext.apache.http.RequestLine; -import com.tracelytics.ext.apache.http.StatusLine; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -/** - * Interface for parsing lines in the HEAD section of an HTTP message. - * There are individual methods for parsing a request line, a - * status line, or a header line. - * The lines to parse are passed in memory, the parser does not depend - * on any specific IO mechanism. - * Instances of this interface are expected to be stateless and thread-safe. - * - * @since 4.0 - */ -public interface LineParser { - - /** - * Parses the textual representation of a protocol version. - * This is needed for parsing request lines (last element) - * as well as status lines (first element). - * - * @param buffer a buffer holding the protocol version to parse - * @param cursor the parser cursor containing the current position and - * the bounds within the buffer for the parsing operation - * - * @return the parsed protocol version - * - * @throws ParseException in case of a parse error - */ - ProtocolVersion parseProtocolVersion( - CharArrayBuffer buffer, - ParserCursor cursor) throws ParseException; - - /** - * Checks whether there likely is a protocol version in a line. - * This method implements a heuristic to check for a - * likely protocol version specification. It does not - * guarantee that {@link #parseProtocolVersion} would not - * detect a parse error. - * This can be used to detect garbage lines before a request - * or status line. - * - * @param buffer a buffer holding the line to inspect - * @param cursor the cursor at which to check for a protocol version, or - * negative for "end of line". Whether the check tolerates - * whitespace before or after the protocol version is - * implementation dependent. - * - * @return {@code true} if there is a protocol version at the - * argument index (possibly ignoring whitespace), - * {@code false} otherwise - */ - boolean hasProtocolVersion( - CharArrayBuffer buffer, - ParserCursor cursor); - - /** - * Parses a request line. - * - * @param buffer a buffer holding the line to parse - * @param cursor the parser cursor containing the current position and - * the bounds within the buffer for the parsing operation - * - * @return the parsed request line - * - * @throws ParseException in case of a parse error - */ - RequestLine parseRequestLine( - CharArrayBuffer buffer, - ParserCursor cursor) throws ParseException; - - /** - * Parses a status line. - * - * @param buffer a buffer holding the line to parse - * @param cursor the parser cursor containing the current position and - * the bounds within the buffer for the parsing operation - * - * @return the parsed status line - * - * @throws ParseException in case of a parse error - */ - StatusLine parseStatusLine( - CharArrayBuffer buffer, - ParserCursor cursor) throws ParseException; - - /** - * Creates a header from a line. - * The full header line is expected here. Header continuation lines - * must be joined by the caller before invoking this method. - * - * @param buffer a buffer holding the full header line. - * This buffer MUST NOT be re-used afterwards, since - * the returned object may reference the contents later. - * - * @return the header in the argument buffer. - * The returned object MAY be a wrapper for the argument buffer. - * The argument buffer MUST NOT be re-used or changed afterwards. - * - * @throws ParseException in case of a parse error - */ - Header parseHeader(CharArrayBuffer buffer) - throws ParseException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/ParserCursor.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/ParserCursor.java deleted file mode 100644 index e739b94d..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/ParserCursor.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 com.tracelytics.ext.apache.http.message; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; - -/** - * This class represents a context of a parsing operation: - *
    - *
  • the current position the parsing operation is expected to start at
  • - *
  • the bounds limiting the scope of the parsing operation
  • - *
- * - * @since 4.0 - */ -@NotThreadSafe -public class ParserCursor { - - private final int lowerBound; - private final int upperBound; - private int pos; - - public ParserCursor(final int lowerBound, final int upperBound) { - super(); - if (lowerBound < 0) { - throw new IndexOutOfBoundsException("Lower bound cannot be negative"); - } - if (lowerBound > upperBound) { - throw new IndexOutOfBoundsException("Lower bound cannot be greater then upper bound"); - } - this.lowerBound = lowerBound; - this.upperBound = upperBound; - this.pos = lowerBound; - } - - public int getLowerBound() { - return this.lowerBound; - } - - public int getUpperBound() { - return this.upperBound; - } - - public int getPos() { - return this.pos; - } - - public void updatePos(final int pos) { - if (pos < this.lowerBound) { - throw new IndexOutOfBoundsException("pos: "+pos+" < lowerBound: "+this.lowerBound); - } - if (pos > this.upperBound) { - throw new IndexOutOfBoundsException("pos: "+pos+" > upperBound: "+this.upperBound); - } - this.pos = pos; - } - - public boolean atEnd() { - return this.pos >= this.upperBound; - } - - @Override - public String toString() { - final StringBuilder buffer = new StringBuilder(); - buffer.append('['); - buffer.append(Integer.toString(this.lowerBound)); - buffer.append('>'); - buffer.append(Integer.toString(this.pos)); - buffer.append('>'); - buffer.append(Integer.toString(this.upperBound)); - buffer.append(']'); - return buffer.toString(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/TokenParser.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/TokenParser.java deleted file mode 100644 index 68fac874..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/TokenParser.java +++ /dev/null @@ -1,267 +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 com.tracelytics.ext.apache.http.message; - -import java.util.BitSet; - -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.CharArrayBuffer; - -/** - * Low level parser for header field elements. The parsing routines of this class are designed - * to produce near zero intermediate garbage and make no intermediate copies of input data. - *

- * This class is immutable and thread safe. - * - * @since 4.4 - */ -@Immutable -public class TokenParser { - - public static BitSet INIT_BITSET(final int ... b) { - final BitSet bitset = new BitSet(); - for (final int aB : b) { - bitset.set(aB); - } - return bitset; - } - - /** US-ASCII CR, carriage return (13) */ - public static final char CR = '\r'; - - /** US-ASCII LF, line feed (10) */ - public static final char LF = '\n'; - - /** US-ASCII SP, space (32) */ - public static final char SP = ' '; - - /** US-ASCII HT, horizontal-tab (9) */ - public static final char HT = '\t'; - - /** Double quote */ - public static final char DQUOTE = '\"'; - - /** Backward slash / escape character */ - public static final char ESCAPE = '\\'; - - public static boolean isWhitespace(final char ch) { - return ch == SP || ch == HT || ch == CR || ch == LF; - } - - public static final TokenParser INSTANCE = new TokenParser(); - - /** - * Extracts from the sequence of chars a token terminated with any of the given delimiters - * discarding semantically insignificant whitespace characters. - * - * @param buf buffer with the sequence of chars to be parsed - * @param cursor defines the bounds and current position of the buffer - * @param delimiters set of delimiting characters. Can be {@code null} if the token - * is not delimited by any character. - */ - public String parseToken(final CharArrayBuffer buf, final ParserCursor cursor, final BitSet delimiters) { - final StringBuilder dst = new StringBuilder(); - boolean whitespace = false; - while (!cursor.atEnd()) { - final char current = buf.charAt(cursor.getPos()); - if (delimiters != null && delimiters.get(current)) { - break; - } else if (isWhitespace(current)) { - skipWhiteSpace(buf, cursor); - whitespace = true; - } else { - if (whitespace && dst.length() > 0) { - dst.append(' '); - } - copyContent(buf, cursor, delimiters, dst); - whitespace = false; - } - } - return dst.toString(); - } - - /** - * Extracts from the sequence of chars a value which can be enclosed in quote marks and - * terminated with any of the given delimiters discarding semantically insignificant - * whitespace characters. - * - * @param buf buffer with the sequence of chars to be parsed - * @param cursor defines the bounds and current position of the buffer - * @param delimiters set of delimiting characters. Can be {@code null} if the value - * is not delimited by any character. - */ - public String parseValue(final CharArrayBuffer buf, final ParserCursor cursor, final BitSet delimiters) { - final StringBuilder dst = new StringBuilder(); - boolean whitespace = false; - while (!cursor.atEnd()) { - final char current = buf.charAt(cursor.getPos()); - if (delimiters != null && delimiters.get(current)) { - break; - } else if (isWhitespace(current)) { - skipWhiteSpace(buf, cursor); - whitespace = true; - } else if (current == DQUOTE) { - if (whitespace && dst.length() > 0) { - dst.append(' '); - } - copyQuotedContent(buf, cursor, dst); - whitespace = false; - } else { - if (whitespace && dst.length() > 0) { - dst.append(' '); - } - copyUnquotedContent(buf, cursor, delimiters, dst); - whitespace = false; - } - } - return dst.toString(); - } - - /** - * Skips semantically insignificant whitespace characters and moves the cursor to the closest - * non-whitespace character. - * - * @param buf buffer with the sequence of chars to be parsed - * @param cursor defines the bounds and current position of the buffer - */ - public void skipWhiteSpace(final CharArrayBuffer buf, final ParserCursor cursor) { - int pos = cursor.getPos(); - final int indexFrom = cursor.getPos(); - final int indexTo = cursor.getUpperBound(); - for (int i = indexFrom; i < indexTo; i++) { - final char current = buf.charAt(i); - if (!isWhitespace(current)) { - break; - } else { - pos++; - } - } - cursor.updatePos(pos); - } - - /** - * Transfers content into the destination buffer until a whitespace character or any of - * the given delimiters is encountered. - * - * @param buf buffer with the sequence of chars to be parsed - * @param cursor defines the bounds and current position of the buffer - * @param delimiters set of delimiting characters. Can be {@code null} if the value - * is delimited by a whitespace only. - * @param dst destination buffer - */ - public void copyContent(final CharArrayBuffer buf, final ParserCursor cursor, final BitSet delimiters, - final StringBuilder dst) { - int pos = cursor.getPos(); - final int indexFrom = cursor.getPos(); - final int indexTo = cursor.getUpperBound(); - for (int i = indexFrom; i < indexTo; i++) { - final char current = buf.charAt(i); - if ((delimiters != null && delimiters.get(current)) || isWhitespace(current)) { - break; - } else { - pos++; - dst.append(current); - } - } - cursor.updatePos(pos); - } - - /** - * Transfers content into the destination buffer until a whitespace character, a quote, - * or any of the given delimiters is encountered. - * - * @param buf buffer with the sequence of chars to be parsed - * @param cursor defines the bounds and current position of the buffer - * @param delimiters set of delimiting characters. Can be {@code null} if the value - * is delimited by a whitespace or a quote only. - * @param dst destination buffer - */ - public void copyUnquotedContent(final CharArrayBuffer buf, final ParserCursor cursor, - final BitSet delimiters, final StringBuilder dst) { - int pos = cursor.getPos(); - final int indexFrom = cursor.getPos(); - final int indexTo = cursor.getUpperBound(); - for (int i = indexFrom; i < indexTo; i++) { - final char current = buf.charAt(i); - if ((delimiters != null && delimiters.get(current)) - || isWhitespace(current) || current == DQUOTE) { - break; - } else { - pos++; - dst.append(current); - } - } - cursor.updatePos(pos); - } - - /** - * Transfers content enclosed with quote marks into the destination buffer. - * - * @param buf buffer with the sequence of chars to be parsed - * @param cursor defines the bounds and current position of the buffer - * @param dst destination buffer - */ - public void copyQuotedContent(final CharArrayBuffer buf, final ParserCursor cursor, - final StringBuilder dst) { - if (cursor.atEnd()) { - return; - } - int pos = cursor.getPos(); - int indexFrom = cursor.getPos(); - final int indexTo = cursor.getUpperBound(); - char current = buf.charAt(pos); - if (current != DQUOTE) { - return; - } - pos++; - indexFrom++; - boolean escaped = false; - for (int i = indexFrom; i < indexTo; i++, pos++) { - current = buf.charAt(i); - if (escaped) { - if (current != DQUOTE && current != ESCAPE) { - dst.append(ESCAPE); - } - dst.append(current); - escaped = false; - } else { - if (current == DQUOTE) { - pos++; - break; - } - if (current == ESCAPE) { - escaped = true; - } else if (current != CR && current != LF) { - dst.append(current); - } - } - } - cursor.updatePos(pos); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/package-info.java deleted file mode 100644 index 8b20d2dd..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/message/package-info.java +++ /dev/null @@ -1,32 +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 - * . - * - */ - -/** - * Core HTTP message components, message element parser - * and writer APIs and their default implementations. - */ -package com.tracelytics.ext.apache.http.message; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/package-info.java deleted file mode 100644 index 1d279655..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/package-info.java +++ /dev/null @@ -1,43 +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 - * . - * - */ - -/** - * Core HTTP component APIs and primitives. - *

- * These deal with the fundamental things required for using the - * HTTP protocol, such as representing a - * {@link com.tracelytics.ext.apache.http.HttpMessage message} including it's - * {@link com.tracelytics.ext.apache.http.Header headers} and optional - * {@link com.tracelytics.ext.apache.http.HttpEntity entity}, and - * {@link com.tracelytics.ext.apache.http.HttpConnection connections} - * over which messages are sent. In order to prepare messages - * before sending or after receiving, there are interceptors for - * {@link com.tracelytics.ext.apache.http.HttpRequestInterceptor requests} and - * {@link com.tracelytics.ext.apache.http.HttpResponseInterceptor responses}. - *

- */ -package com.tracelytics.ext.apache.http; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/AbstractHttpParams.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/AbstractHttpParams.java deleted file mode 100644 index 418e10a0..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/AbstractHttpParams.java +++ /dev/null @@ -1,135 +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 com.tracelytics.ext.apache.http.params; - -import java.util.Set; - -/** - * Abstract base class for parameter collections. - * Type specific setters and getters are mapped to the abstract, - * generic getters and setters. - * - * @since 4.0 - * - * @deprecated (4.3) use configuration classes provided 'com.tracelytics.ext.apache.http.config' - * and 'com.tracelytics.ext.apache.http.client.config' - */ -@Deprecated -public abstract class AbstractHttpParams implements HttpParams, HttpParamsNames { - - /** - * Instantiates parameters. - */ - protected AbstractHttpParams() { - super(); - } - - @Override - public long getLongParameter(final String name, final long defaultValue) { - final Object param = getParameter(name); - if (param == null) { - return defaultValue; - } - return ((Long) param).longValue(); - } - - @Override - public HttpParams setLongParameter(final String name, final long value) { - setParameter(name, Long.valueOf(value)); - return this; - } - - @Override - public int getIntParameter(final String name, final int defaultValue) { - final Object param = getParameter(name); - if (param == null) { - return defaultValue; - } - return ((Integer) param).intValue(); - } - - @Override - public HttpParams setIntParameter(final String name, final int value) { - setParameter(name, Integer.valueOf(value)); - return this; - } - - @Override - public double getDoubleParameter(final String name, final double defaultValue) { - final Object param = getParameter(name); - if (param == null) { - return defaultValue; - } - return ((Double) param).doubleValue(); - } - - @Override - public HttpParams setDoubleParameter(final String name, final double value) { - setParameter(name, Double.valueOf(value)); - return this; - } - - @Override - public boolean getBooleanParameter(final String name, final boolean defaultValue) { - final Object param = getParameter(name); - if (param == null) { - return defaultValue; - } - return ((Boolean) param).booleanValue(); - } - - @Override - public HttpParams setBooleanParameter(final String name, final boolean value) { - setParameter(name, value ? Boolean.TRUE : Boolean.FALSE); - return this; - } - - @Override - public boolean isParameterTrue(final String name) { - return getBooleanParameter(name, false); - } - - @Override - public boolean isParameterFalse(final String name) { - return !getBooleanParameter(name, false); - } - - /** - * {@inheritDoc} - *

- * Dummy implementation - must be overridden by subclasses. - * - * @since 4.2 - * @throws UnsupportedOperationException - always - */ - @Override - public Set getNames(){ - throw new UnsupportedOperationException(); - } - -} // class AbstractHttpParams diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/BasicHttpParams.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/BasicHttpParams.java deleted file mode 100644 index 5960d564..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/BasicHttpParams.java +++ /dev/null @@ -1,194 +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 com.tracelytics.ext.apache.http.params; - -import java.io.Serializable; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; - -/** - * Default implementation of {@link HttpParams} interface. - *

- * Please note access to the internal structures of this class is not - * synchronized and therefore this class may be thread-unsafe. - * - * @since 4.0 - * - * @deprecated (4.3) use configuration classes provided 'com.tracelytics.ext.apache.http.config' - * and 'com.tracelytics.ext.apache.http.client.config' - */ -@Deprecated -@ThreadSafe -public class BasicHttpParams extends AbstractHttpParams implements Serializable, Cloneable { - - private static final long serialVersionUID = -7086398485908701455L; - - /** Map of HTTP parameters that this collection contains. */ - private final Map parameters = new ConcurrentHashMap(); - - public BasicHttpParams() { - super(); - } - - @Override - public Object getParameter(final String name) { - return this.parameters.get(name); - } - - @Override - public HttpParams setParameter(final String name, final Object value) { - if (name == null) { - return this; - } - if (value != null) { - this.parameters.put(name, value); - } else { - this.parameters.remove(name); - } - return this; - } - - @Override - public boolean removeParameter(final String name) { - //this is to avoid the case in which the key has a null value - if (this.parameters.containsKey(name)) { - this.parameters.remove(name); - return true; - } else { - return false; - } - } - - /** - * Assigns the value to all the parameter with the given names - * - * @param names array of parameter names - * @param value parameter value - */ - public void setParameters(final String[] names, final Object value) { - for (final String name : names) { - setParameter(name, value); - } - } - - /** - * Is the parameter set? - *

- * Uses {@link #getParameter(String)} (which is overrideable) to - * fetch the parameter value, if any. - *

- * Also @see {@link #isParameterSetLocally(String)} - * - * @param name parameter name - * @return true if parameter is defined and non-null - */ - public boolean isParameterSet(final String name) { - return getParameter(name) != null; - } - - /** - * Is the parameter set in this object? - *

- * The parameter value is fetched directly. - *

- * Also @see {@link #isParameterSet(String)} - * - * @param name parameter name - * @return true if parameter is defined and non-null - */ - public boolean isParameterSetLocally(final String name) { - return this.parameters.get(name) != null; - } - - /** - * Removes all parameters from this collection. - */ - public void clear() { - this.parameters.clear(); - } - - /** - * Creates a copy of these parameters. - * This implementation calls {@link #clone()}. - * - * @return a new set of params holding a copy of the - * local parameters in this object. - * - * @throws UnsupportedOperationException if the clone() fails - */ - @Override - public HttpParams copy() { - try { - return (HttpParams) clone(); - } catch (final CloneNotSupportedException ex) { - throw new UnsupportedOperationException("Cloning not supported"); - } - } - - /** - * Clones the instance. - * Uses {@link #copyParams(HttpParams)} to copy the parameters. - */ - @Override - public Object clone() throws CloneNotSupportedException { - final BasicHttpParams clone = (BasicHttpParams) super.clone(); - copyParams(clone); - return clone; - } - - /** - * Copies the locally defined parameters to the argument parameters. - * This method is called from {@link #clone()}. - * - * @param target the parameters to which to copy - * @since 4.2 - */ - public void copyParams(final HttpParams target) { - for (final Map.Entry me : this.parameters.entrySet()) { - target.setParameter(me.getKey(), me.getValue()); - } - } - - /** - * Returns the current set of names. - * - * Changes to the underlying HttpParams are not reflected - * in the set - it is a snapshot. - * - * @return the names, as a Set<String> - * @since 4.2 - */ - @Override - public Set getNames() { - return new HashSet(this.parameters.keySet()); - } -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/CoreConnectionPNames.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/CoreConnectionPNames.java deleted file mode 100644 index 5a27bae8..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/CoreConnectionPNames.java +++ /dev/null @@ -1,170 +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 com.tracelytics.ext.apache.http.params; - -/** - * Defines parameter names for connections in HttpCore. - * - * @since 4.0 - * - * @deprecated (4.3) use configuration classes provided 'com.tracelytics.ext.apache.http.config' - * and 'com.tracelytics.ext.apache.http.client.config' - */ -@Deprecated -public interface CoreConnectionPNames { - - /** - * Defines the socket timeout ({@code SO_TIMEOUT}) in milliseconds, - * which is the timeout for waiting for data or, put differently, - * a maximum period inactivity between two consecutive data packets). - * A timeout value of zero is interpreted as an infinite timeout. - *

- * This parameter expects a value of type {@link Integer}. - *

- * @see java.net.SocketOptions#SO_TIMEOUT - */ - public static final String SO_TIMEOUT = "http.socket.timeout"; - - /** - * Determines whether Nagle's algorithm is to be used. The Nagle's algorithm - * tries to conserve bandwidth by minimizing the number of segments that are - * sent. When applications wish to decrease network latency and increase - * performance, they can disable Nagle's algorithm (that is enable - * TCP_NODELAY). Data will be sent earlier, at the cost of an increase - * in bandwidth consumption. - *

- * This parameter expects a value of type {@link Boolean}. - *

- * @see java.net.SocketOptions#TCP_NODELAY - */ - public static final String TCP_NODELAY = "http.tcp.nodelay"; - - /** - * Determines the size of the internal socket buffer used to buffer data - * while receiving / transmitting HTTP messages. - *

- * This parameter expects a value of type {@link Integer}. - *

- */ - public static final String SOCKET_BUFFER_SIZE = "http.socket.buffer-size"; - - /** - * Sets SO_LINGER with the specified linger time in seconds. The maximum - * timeout value is platform specific. Value {@code 0} implies that - * the option is disabled. Value {@code -1} implies that the JRE - * default is used. The setting only affects the socket close operation. - *

- * This parameter expects a value of type {@link Integer}. - *

- * @see java.net.SocketOptions#SO_LINGER - */ - public static final String SO_LINGER = "http.socket.linger"; - - /** - * Defines whether the socket can be bound even though a previous connection is - * still in a timeout state. - *

- * This parameter expects a value of type {@link Boolean}. - *

- * @see java.net.Socket#setReuseAddress(boolean) - * - * @since 4.1 - */ - public static final String SO_REUSEADDR = "http.socket.reuseaddr"; - - /** - * Determines the timeout in milliseconds until a connection is established. - * A timeout value of zero is interpreted as an infinite timeout. - *

- * Please note this parameter can only be applied to connections that - * are bound to a particular local address. - *

- * This parameter expects a value of type {@link Integer}. - *

- */ - public static final String CONNECTION_TIMEOUT = "http.connection.timeout"; - - /** - * Determines whether stale connection check is to be used. The stale - * connection check can cause up to 30 millisecond overhead per request and - * should be used only when appropriate. For performance critical - * operations this check should be disabled. - *

- * This parameter expects a value of type {@link Boolean}. - *

- */ - public static final String STALE_CONNECTION_CHECK = "http.connection.stalecheck"; - - /** - * Determines the maximum line length limit. If set to a positive value, - * any HTTP line exceeding this limit will cause an IOException. A negative - * or zero value will effectively disable the check. - *

- * This parameter expects a value of type {@link Integer}. - *

- */ - public static final String MAX_LINE_LENGTH = "http.connection.max-line-length"; - - /** - * Determines the maximum HTTP header count allowed. If set to a positive - * value, the number of HTTP headers received from the data stream exceeding - * this limit will cause an IOException. A negative or zero value will - * effectively disable the check. - *

- * This parameter expects a value of type {@link Integer}. - *

- */ - public static final String MAX_HEADER_COUNT = "http.connection.max-header-count"; - - /** - * Defines the size limit below which data chunks should be buffered in a session I/O buffer - * in order to minimize native method invocations on the underlying network socket. - * The optimal value of this parameter can be platform specific and defines a trade-off - * between performance of memory copy operations and that of native method invocation. - *

- * This parameter expects a value of type {@link Integer}. - *

- * - * @since 4.1 - */ - public static final String MIN_CHUNK_LIMIT = "http.connection.min-chunk-limit"; - - - /** - * Defines whether or not TCP is to send automatically a keepalive probe to the peer - * after an interval of inactivity (no data exchanged in either direction) between this - * host and the peer. The purpose of this option is to detect if the peer host crashes. - *

- * This parameter expects a value of type {@link Boolean}. - *

- * @see java.net.SocketOptions#SO_KEEPALIVE - * @since 4.2 - */ - public static final String SO_KEEPALIVE = "http.socket.keepalive"; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/CoreProtocolPNames.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/CoreProtocolPNames.java deleted file mode 100644 index 017707ec..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/CoreProtocolPNames.java +++ /dev/null @@ -1,152 +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 com.tracelytics.ext.apache.http.params; - -/** - * Defines parameter names for protocol execution in HttpCore. - * - * @since 4.0 - * - * @deprecated (4.3) use configuration classes provided 'com.tracelytics.ext.apache.http.config' - * and 'com.tracelytics.ext.apache.http.client.config' - */ -@Deprecated -public interface CoreProtocolPNames { - - /** - * Defines the {@link com.tracelytics.ext.apache.http.ProtocolVersion} used per default. - *

- * This parameter expects a value of type {@link com.tracelytics.ext.apache.http.ProtocolVersion}. - *

- */ - public static final String PROTOCOL_VERSION = "http.protocol.version"; - - /** - * Defines the charset to be used for encoding HTTP protocol elements. - *

- * This parameter expects a value of type {@link String}. - *

- */ - public static final String HTTP_ELEMENT_CHARSET = "http.protocol.element-charset"; - - /** - * Defines the charset to be used per default for encoding content body. - *

- * This parameter expects a value of type {@link String}. - *

- */ - public static final String HTTP_CONTENT_CHARSET = "http.protocol.content-charset"; - - /** - * Defines the content of the {@code User-Agent} header. - *

- * This parameter expects a value of type {@link String}. - *

- */ - public static final String USER_AGENT = "http.useragent"; - - /** - * Defines the content of the {@code Server} header. - *

- * This parameter expects a value of type {@link String}. - *

- */ - public static final String ORIGIN_SERVER = "http.origin-server"; - - /** - * Defines whether responses with an invalid {@code Transfer-Encoding} - * header should be rejected. - *

- * This parameter expects a value of type {@link Boolean}. - *

- */ - public static final String STRICT_TRANSFER_ENCODING = "http.protocol.strict-transfer-encoding"; - - /** - *

- * Activates 'Expect: 100-Continue' handshake for the - * entity enclosing methods. The purpose of the 'Expect: 100-Continue' - * handshake is to allow a client that is sending a request message with - * a request body to determine if the origin server is willing to - * accept the request (based on the request headers) before the client - * sends the request body. - *

- * - *

- * The use of the 'Expect: 100-continue' handshake can result in - * a noticeable performance improvement for entity enclosing requests - * (such as POST and PUT) that require the target server's - * authentication. - *

- * - *

- * 'Expect: 100-continue' handshake should be used with - * caution, as it may cause problems with HTTP servers and - * proxies that do not support HTTP/1.1 protocol. - *

- * - * This parameter expects a value of type {@link Boolean}. - */ - public static final String USE_EXPECT_CONTINUE = "http.protocol.expect-continue"; - - /** - *

- * Defines the maximum period of time in milliseconds the client should spend - * waiting for a 100-continue response. - *

- * - * This parameter expects a value of type {@link Integer}. - */ - public static final String WAIT_FOR_CONTINUE = "http.protocol.wait-for-continue"; - - /** - *

- * Defines the action to perform upon receiving a malformed input. If the input byte sequence - * is not legal for this charset then the input is said to be malformed - *

- * - * This parameter expects a value of type {@link java.nio.charset.CodingErrorAction} - * - * @since 4.2 - */ - public static final String HTTP_MALFORMED_INPUT_ACTION = "http.malformed.input.action"; - - /** - *

- * Defines the action to perform upon receiving an unmappable input. If the input byte sequence - * is legal but cannot be mapped to a valid Unicode character then the input is said to be - * unmappable - *

- * - * This parameter expects a value of type {@link java.nio.charset.CodingErrorAction} - * - * @since 4.2 - */ - public static final String HTTP_UNMAPPABLE_INPUT_ACTION = "http.unmappable.input.action"; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/DefaultedHttpParams.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/DefaultedHttpParams.java deleted file mode 100644 index 99e3dc58..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/DefaultedHttpParams.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 com.tracelytics.ext.apache.http.params; - -import java.util.HashSet; -import java.util.Set; - -import com.tracelytics.ext.apache.http.util.Args; - -/** - * {@link HttpParams} implementation that delegates resolution of a parameter - * to the given default {@link HttpParams} instance if the parameter is not - * present in the local one. The state of the local collection can be mutated, - * whereas the default collection is treated as read-only. - * - * @since 4.0 - * - * @deprecated (4.3) use configuration classes provided 'com.tracelytics.ext.apache.http.config' - * and 'com.tracelytics.ext.apache.http.client.config' - */ -@Deprecated -public final class DefaultedHttpParams extends AbstractHttpParams { - - private final HttpParams local; - private final HttpParams defaults; - - /** - * Create the defaulted set of HttpParams. - * - * @param local the mutable set of HttpParams - * @param defaults the default set of HttpParams, not mutated by this class - */ - public DefaultedHttpParams(final HttpParams local, final HttpParams defaults) { - super(); - this.local = Args.notNull(local, "Local HTTP parameters"); - this.defaults = defaults; - } - - /** - * Creates a copy of the local collection with the same default - */ - public HttpParams copy() { - final HttpParams clone = this.local.copy(); - return new DefaultedHttpParams(clone, this.defaults); - } - - /** - * Retrieves the value of the parameter from the local collection and, if the - * parameter is not set locally, delegates its resolution to the default - * collection. - */ - public Object getParameter(final String name) { - Object obj = this.local.getParameter(name); - if (obj == null && this.defaults != null) { - obj = this.defaults.getParameter(name); - } - return obj; - } - - /** - * Attempts to remove the parameter from the local collection. This method - * does not modify the default collection. - */ - public boolean removeParameter(final String name) { - return this.local.removeParameter(name); - } - - /** - * Sets the parameter in the local collection. This method does not - * modify the default collection. - */ - public HttpParams setParameter(final String name, final Object value) { - return this.local.setParameter(name, value); - } - - /** - * - * @return the default HttpParams collection - */ - public HttpParams getDefaults() { - return this.defaults; - } - - /** - * Returns the current set of names - * from both the local and default HttpParams instances. - * - * Changes to the underlying HttpParams intances are not reflected - * in the set - it is a snapshot. - * - * @return the combined set of names, as a Set<String> - * @since 4.2 - * @throws UnsupportedOperationException if either the local or default HttpParams instances do not implement HttpParamsNames - */ - @Override - public Set getNames() { - final Set combined = new HashSet(getNames(defaults)); - combined.addAll(getNames(this.local)); - return combined ; - } - - /** - * Returns the current set of defaults names. - * - * Changes to the underlying HttpParams are not reflected - * in the set - it is a snapshot. - * - * @return the names, as a Set<String> - * @since 4.2 - * @throws UnsupportedOperationException if the default HttpParams instance does not implement HttpParamsNames - */ - public Set getDefaultNames() { - return new HashSet(getNames(this.defaults)); - } - - /** - * Returns the current set of local names. - * - * Changes to the underlying HttpParams are not reflected - * in the set - it is a snapshot. - * - * @return the names, as a Set<String> - * @since 4.2 - * @throws UnsupportedOperationException if the local HttpParams instance does not implement HttpParamsNames - */ - public Set getLocalNames() { - return new HashSet(getNames(this.local)); - } - - // Helper method - private Set getNames(final HttpParams params) { - if (params instanceof HttpParamsNames) { - return ((HttpParamsNames) params).getNames(); - } - throw new UnsupportedOperationException("HttpParams instance does not implement HttpParamsNames"); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpAbstractParamBean.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpAbstractParamBean.java deleted file mode 100644 index ee3565b3..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpAbstractParamBean.java +++ /dev/null @@ -1,48 +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 com.tracelytics.ext.apache.http.params; - -import com.tracelytics.ext.apache.http.util.Args; - -/** - * @since 4.0 - * - * @deprecated (4.3) use configuration classes provided 'com.tracelytics.ext.apache.http.config' - * and 'com.tracelytics.ext.apache.http.client.config' - */ -@Deprecated -public abstract class HttpAbstractParamBean { - - protected final HttpParams params; - - public HttpAbstractParamBean (final HttpParams params) { - super(); - this.params = Args.notNull(params, "HTTP parameters"); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpConnectionParamBean.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpConnectionParamBean.java deleted file mode 100644 index 767bc693..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpConnectionParamBean.java +++ /dev/null @@ -1,71 +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 com.tracelytics.ext.apache.http.params; - -/** - * This is a Java Bean class that can be used to wrap an instance of - * {@link HttpParams} and manipulate HTTP connection parameters using Java Beans - * conventions. - * - * @since 4.0 - * - * @deprecated (4.3) use configuration classes provided 'com.tracelytics.ext.apache.http.config' - * and 'com.tracelytics.ext.apache.http.client.config' - */ -@Deprecated -public class HttpConnectionParamBean extends HttpAbstractParamBean { - - public HttpConnectionParamBean (final HttpParams params) { - super(params); - } - - public void setSoTimeout (final int soTimeout) { - HttpConnectionParams.setSoTimeout(params, soTimeout); - } - - public void setTcpNoDelay (final boolean tcpNoDelay) { - HttpConnectionParams.setTcpNoDelay(params, tcpNoDelay); - } - - public void setSocketBufferSize (final int socketBufferSize) { - HttpConnectionParams.setSocketBufferSize(params, socketBufferSize); - } - - public void setLinger (final int linger) { - HttpConnectionParams.setLinger(params, linger); - } - - public void setConnectionTimeout (final int connectionTimeout) { - HttpConnectionParams.setConnectionTimeout(params, connectionTimeout); - } - - public void setStaleCheckingEnabled (final boolean staleCheckingEnabled) { - HttpConnectionParams.setStaleCheckingEnabled(params, staleCheckingEnabled); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpConnectionParams.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpConnectionParams.java deleted file mode 100644 index 51199785..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpConnectionParams.java +++ /dev/null @@ -1,243 +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 com.tracelytics.ext.apache.http.params; - -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Utility class for accessing connection parameters in {@link HttpParams}. - * - * @since 4.0 - * - * @deprecated (4.3) use configuration classes provided 'com.tracelytics.ext.apache.http.config' - * and 'com.tracelytics.ext.apache.http.client.config' - */ -@Deprecated -public final class HttpConnectionParams implements CoreConnectionPNames { - - private HttpConnectionParams() { - super(); - } - - /** - * Obtains value of the {@link CoreConnectionPNames#SO_TIMEOUT} parameter. - * If not set, defaults to {@code 0}. - * - * @param params HTTP parameters. - * @return SO_TIMEOUT. - */ - public static int getSoTimeout(final HttpParams params) { - Args.notNull(params, "HTTP parameters"); - return params.getIntParameter(CoreConnectionPNames.SO_TIMEOUT, 0); - } - - /** - * Sets value of the {@link CoreConnectionPNames#SO_TIMEOUT} parameter. - * - * @param params HTTP parameters. - * @param timeout SO_TIMEOUT. - */ - public static void setSoTimeout(final HttpParams params, final int timeout) { - Args.notNull(params, "HTTP parameters"); - params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, timeout); - - } - - /** - * Obtains value of the {@link CoreConnectionPNames#SO_REUSEADDR} parameter. - * If not set, defaults to {@code false}. - * - * @param params HTTP parameters. - * @return SO_REUSEADDR. - * - * @since 4.1 - */ - public static boolean getSoReuseaddr(final HttpParams params) { - Args.notNull(params, "HTTP parameters"); - return params.getBooleanParameter(CoreConnectionPNames.SO_REUSEADDR, false); - } - - /** - * Sets value of the {@link CoreConnectionPNames#SO_REUSEADDR} parameter. - * - * @param params HTTP parameters. - * @param reuseaddr SO_REUSEADDR. - * - * @since 4.1 - */ - public static void setSoReuseaddr(final HttpParams params, final boolean reuseaddr) { - Args.notNull(params, "HTTP parameters"); - params.setBooleanParameter(CoreConnectionPNames.SO_REUSEADDR, reuseaddr); - } - - /** - * Obtains value of the {@link CoreConnectionPNames#TCP_NODELAY} parameter. - * If not set, defaults to {@code true}. - * - * @param params HTTP parameters. - * @return Nagle's algorithm flag - */ - public static boolean getTcpNoDelay(final HttpParams params) { - Args.notNull(params, "HTTP parameters"); - return params.getBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true); - } - - /** - * Sets value of the {@link CoreConnectionPNames#TCP_NODELAY} parameter. - * - * @param params HTTP parameters. - * @param value Nagle's algorithm flag - */ - public static void setTcpNoDelay(final HttpParams params, final boolean value) { - Args.notNull(params, "HTTP parameters"); - params.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, value); - } - - /** - * Obtains value of the {@link CoreConnectionPNames#SOCKET_BUFFER_SIZE} - * parameter. If not set, defaults to {@code -1}. - * - * @param params HTTP parameters. - * @return socket buffer size - */ - public static int getSocketBufferSize(final HttpParams params) { - Args.notNull(params, "HTTP parameters"); - return params.getIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, -1); - } - - /** - * Sets value of the {@link CoreConnectionPNames#SOCKET_BUFFER_SIZE} - * parameter. - * - * @param params HTTP parameters. - * @param size socket buffer size - */ - public static void setSocketBufferSize(final HttpParams params, final int size) { - Args.notNull(params, "HTTP parameters"); - params.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, size); - } - - /** - * Obtains value of the {@link CoreConnectionPNames#SO_LINGER} parameter. - * If not set, defaults to {@code -1}. - * - * @param params HTTP parameters. - * @return SO_LINGER. - */ - public static int getLinger(final HttpParams params) { - Args.notNull(params, "HTTP parameters"); - return params.getIntParameter(CoreConnectionPNames.SO_LINGER, -1); - } - - /** - * Sets value of the {@link CoreConnectionPNames#SO_LINGER} parameter. - * - * @param params HTTP parameters. - * @param value SO_LINGER. - */ - public static void setLinger(final HttpParams params, final int value) { - Args.notNull(params, "HTTP parameters"); - params.setIntParameter(CoreConnectionPNames.SO_LINGER, value); - } - - /** - * Obtains value of the {@link CoreConnectionPNames#CONNECTION_TIMEOUT} - * parameter. If not set, defaults to {@code 0}. - * - * @param params HTTP parameters. - * @return connect timeout. - */ - public static int getConnectionTimeout(final HttpParams params) { - Args.notNull(params, "HTTP parameters"); - return params.getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 0); - } - - /** - * Sets value of the {@link CoreConnectionPNames#CONNECTION_TIMEOUT} - * parameter. - * - * @param params HTTP parameters. - * @param timeout connect timeout. - */ - public static void setConnectionTimeout(final HttpParams params, final int timeout) { - Args.notNull(params, "HTTP parameters"); - params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); - } - - /** - * Obtains value of the {@link CoreConnectionPNames#STALE_CONNECTION_CHECK} - * parameter. If not set, defaults to {@code true}. - * - * @param params HTTP parameters. - * @return stale connection check flag. - */ - public static boolean isStaleCheckingEnabled(final HttpParams params) { - Args.notNull(params, "HTTP parameters"); - return params.getBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, true); - } - - /** - * Sets value of the {@link CoreConnectionPNames#STALE_CONNECTION_CHECK} - * parameter. - * - * @param params HTTP parameters. - * @param value stale connection check flag. - */ - public static void setStaleCheckingEnabled(final HttpParams params, final boolean value) { - Args.notNull(params, "HTTP parameters"); - params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, value); - } - - /** - * Obtains value of the {@link CoreConnectionPNames#SO_KEEPALIVE} parameter. - * If not set, defaults to {@code false}. - * - * @param params HTTP parameters. - * @return SO_KEEPALIVE. - * - * @since 4.2 - */ - public static boolean getSoKeepalive(final HttpParams params) { - Args.notNull(params, "HTTP parameters"); - return params.getBooleanParameter(CoreConnectionPNames.SO_KEEPALIVE, false); - } - - /** - * Sets value of the {@link CoreConnectionPNames#SO_KEEPALIVE} parameter. - * - * @param params HTTP parameters. - * @param enableKeepalive SO_KEEPALIVE. - * - * @since 4.2 - */ - public static void setSoKeepalive(final HttpParams params, final boolean enableKeepalive) { - Args.notNull(params, "HTTP parameters"); - params.setBooleanParameter(CoreConnectionPNames.SO_KEEPALIVE, enableKeepalive); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpParamConfig.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpParamConfig.java deleted file mode 100644 index f1696e46..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpParamConfig.java +++ /dev/null @@ -1,78 +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 com.tracelytics.ext.apache.http.params; - -import java.nio.charset.Charset; -import java.nio.charset.CodingErrorAction; - -import com.tracelytics.ext.apache.http.config.ConnectionConfig; -import com.tracelytics.ext.apache.http.config.MessageConstraints; -import com.tracelytics.ext.apache.http.config.SocketConfig; - -/** - * @deprecated (4.3) provided for compatibility with {@link HttpParams}. Do not use. - * - * @since 4.3 - */ -@Deprecated -public final class HttpParamConfig { - - private HttpParamConfig() { - } - - public static SocketConfig getSocketConfig(final HttpParams params) { - return SocketConfig.custom() - .setSoTimeout(params.getIntParameter(CoreConnectionPNames.SO_TIMEOUT, 0)) - .setSoReuseAddress(params.getBooleanParameter(CoreConnectionPNames.SO_REUSEADDR, false)) - .setSoKeepAlive(params.getBooleanParameter(CoreConnectionPNames.SO_KEEPALIVE, false)) - .setSoLinger(params.getIntParameter(CoreConnectionPNames.SO_LINGER, -1)) - .setTcpNoDelay(params.getBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)) - .build(); - } - - public static MessageConstraints getMessageConstraints(final HttpParams params) { - return MessageConstraints.custom() - .setMaxHeaderCount(params.getIntParameter(CoreConnectionPNames.MAX_HEADER_COUNT, -1)) - .setMaxLineLength(params.getIntParameter(CoreConnectionPNames.MAX_LINE_LENGTH, -1)) - .build(); - } - - public static ConnectionConfig getConnectionConfig(final HttpParams params) { - final MessageConstraints messageConstraints = getMessageConstraints(params); - final String csname = (String) params.getParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET); - return ConnectionConfig.custom() - .setCharset(csname != null ? Charset.forName(csname) : null) - .setMalformedInputAction((CodingErrorAction) - params.getParameter(CoreProtocolPNames.HTTP_MALFORMED_INPUT_ACTION)) - .setMalformedInputAction((CodingErrorAction) - params.getParameter(CoreProtocolPNames.HTTP_UNMAPPABLE_INPUT_ACTION)) - .setMessageConstraints(messageConstraints) - .build(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpParams.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpParams.java deleted file mode 100644 index 70e57fbd..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpParams.java +++ /dev/null @@ -1,195 +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 com.tracelytics.ext.apache.http.params; - -/** - * HttpParams interface represents a collection of immutable values that define - * a runtime behavior of a component. HTTP parameters should be simple objects: - * integers, doubles, strings, collections and objects that remain immutable - * at runtime. HttpParams is expected to be used in 'write once - read many' mode. - * Once initialized, HTTP parameters are not expected to mutate in - * the course of HTTP message processing. - *

- * The purpose of this interface is to define a behavior of other components. - * Usually each complex component has its own HTTP parameter collection. - *

- * Instances of this interface can be linked together to form a hierarchy. - * In the simplest form one set of parameters can use content of another one - * to obtain default values of parameters not present in the local set. - * - * @since 4.0 - * - * @deprecated (4.3) use configuration classes provided 'com.tracelytics.ext.apache.http.config' - * and 'com.tracelytics.ext.apache.http.client.config' - */ -@Deprecated -public interface HttpParams { - - /** - * Obtains the value of the given parameter. - * - * @param name the parent name. - * - * @return an object that represents the value of the parameter, - * {@code null} if the parameter is not set or if it - * is explicitly set to {@code null} - * - * @see #setParameter(String, Object) - */ - Object getParameter(String name); - - /** - * Assigns the value to the parameter with the given name. - * - * @param name parameter name - * @param value parameter value - */ - HttpParams setParameter(String name, Object value); - - /** - * Creates a copy of these parameters. - * - * @return a new set of parameters holding the same values as this one - */ - HttpParams copy(); - - /** - * Removes the parameter with the specified name. - * - * @param name parameter name - * - * @return true if the parameter existed and has been removed, false else. - */ - boolean removeParameter(String name); - - /** - * Returns a {@link Long} parameter value with the given name. - * If the parameter is not explicitly set, the default value is returned. - * - * @param name the parent name. - * @param defaultValue the default value. - * - * @return a {@link Long} that represents the value of the parameter. - * - * @see #setLongParameter(String, long) - */ - long getLongParameter(String name, long defaultValue); - - /** - * Assigns a {@link Long} to the parameter with the given name - * - * @param name parameter name - * @param value parameter value - */ - HttpParams setLongParameter(String name, long value); - - /** - * Returns an {@link Integer} parameter value with the given name. - * If the parameter is not explicitly set, the default value is returned. - * - * @param name the parent name. - * @param defaultValue the default value. - * - * @return a {@link Integer} that represents the value of the parameter. - * - * @see #setIntParameter(String, int) - */ - int getIntParameter(String name, int defaultValue); - - /** - * Assigns an {@link Integer} to the parameter with the given name - * - * @param name parameter name - * @param value parameter value - */ - HttpParams setIntParameter(String name, int value); - - /** - * Returns a {@link Double} parameter value with the given name. - * If the parameter is not explicitly set, the default value is returned. - * - * @param name the parent name. - * @param defaultValue the default value. - * - * @return a {@link Double} that represents the value of the parameter. - * - * @see #setDoubleParameter(String, double) - */ - double getDoubleParameter(String name, double defaultValue); - - /** - * Assigns a {@link Double} to the parameter with the given name - * - * @param name parameter name - * @param value parameter value - */ - HttpParams setDoubleParameter(String name, double value); - - /** - * Returns a {@link Boolean} parameter value with the given name. - * If the parameter is not explicitly set, the default value is returned. - * - * @param name the parent name. - * @param defaultValue the default value. - * - * @return a {@link Boolean} that represents the value of the parameter. - * - * @see #setBooleanParameter(String, boolean) - */ - boolean getBooleanParameter(String name, boolean defaultValue); - - /** - * Assigns a {@link Boolean} to the parameter with the given name - * - * @param name parameter name - * @param value parameter value - */ - HttpParams setBooleanParameter(String name, boolean value); - - /** - * Checks if a boolean parameter is set to {@code true}. - * - * @param name parameter name - * - * @return {@code true} if the parameter is set to value {@code true}, - * {@code false} if it is not set or set to {@code false} - */ - boolean isParameterTrue(String name); - - /** - * Checks if a boolean parameter is not set or {@code false}. - * - * @param name parameter name - * - * @return {@code true} if the parameter is either not set or - * set to value {@code false}, - * {@code false} if it is set to {@code true} - */ - boolean isParameterFalse(String name); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpParamsNames.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpParamsNames.java deleted file mode 100644 index 1efa1fc1..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpParamsNames.java +++ /dev/null @@ -1,57 +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 com.tracelytics.ext.apache.http.params; - -import java.util.Set; - -/** - * Gives access to the full set of parameter names. - * - * @see HttpParams - * - * @since 4.2 - * - * @deprecated (4.3) use configuration classes provided 'com.tracelytics.ext.apache.http.config' - * and 'com.tracelytics.ext.apache.http.client.config' - */ -@Deprecated -public interface HttpParamsNames { - - /** - * Returns the current set of names; - * in the case of stacked parameters, returns the names - * from all the participating HttpParams instances. - * - * Changes to the underlying HttpParams are not reflected - * in the set - it is a snapshot. - * - * @return the names, as a Set<String> - */ - Set getNames(); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpProtocolParamBean.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpProtocolParamBean.java deleted file mode 100644 index fe9fbc19..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpProtocolParamBean.java +++ /dev/null @@ -1,69 +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 com.tracelytics.ext.apache.http.params; - -import com.tracelytics.ext.apache.http.HttpVersion; - -/** - * This is a Java Bean class that can be used to wrap an instance of - * {@link HttpParams} and manipulate HTTP protocol parameters using Java Beans - * conventions. - * - * @since 4.0 - * - * @deprecated (4.3) use configuration classes provided 'com.tracelytics.ext.apache.http.config' - * and 'com.tracelytics.ext.apache.http.client.config' - */ -@Deprecated -public class HttpProtocolParamBean extends HttpAbstractParamBean { - - public HttpProtocolParamBean (final HttpParams params) { - super(params); - } - - public void setHttpElementCharset (final String httpElementCharset) { - HttpProtocolParams.setHttpElementCharset(params, httpElementCharset); - } - - public void setContentCharset (final String contentCharset) { - HttpProtocolParams.setContentCharset(params, contentCharset); - } - - public void setVersion (final HttpVersion version) { - HttpProtocolParams.setVersion(params, version); - } - - public void setUserAgent (final String userAgent) { - HttpProtocolParams.setUserAgent(params, userAgent); - } - - public void setUseExpectContinue (final boolean useExpectContinue) { - HttpProtocolParams.setUseExpectContinue(params, useExpectContinue); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpProtocolParams.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpProtocolParams.java deleted file mode 100644 index 115eff8b..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/HttpProtocolParams.java +++ /dev/null @@ -1,240 +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 com.tracelytics.ext.apache.http.params; - -import java.nio.charset.CodingErrorAction; - -import com.tracelytics.ext.apache.http.HttpVersion; -import com.tracelytics.ext.apache.http.ProtocolVersion; -import com.tracelytics.ext.apache.http.protocol.HTTP; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Utility class for accessing protocol parameters in {@link HttpParams}. - * - * @since 4.0 - * - * @deprecated (4.3) use configuration classes provided 'com.tracelytics.ext.apache.http.config' - * and 'com.tracelytics.ext.apache.http.client.config' - */ -@Deprecated -public final class HttpProtocolParams implements CoreProtocolPNames { - - private HttpProtocolParams() { - super(); - } - - /** - * Obtains value of the {@link CoreProtocolPNames#HTTP_ELEMENT_CHARSET} parameter. - * If not set, defaults to {@code US-ASCII}. - * - * @param params HTTP parameters. - * @return HTTP element charset. - */ - public static String getHttpElementCharset(final HttpParams params) { - Args.notNull(params, "HTTP parameters"); - String charset = (String) params.getParameter - (CoreProtocolPNames.HTTP_ELEMENT_CHARSET); - if (charset == null) { - charset = HTTP.DEF_PROTOCOL_CHARSET.name(); - } - return charset; - } - - /** - * Sets value of the {@link CoreProtocolPNames#HTTP_ELEMENT_CHARSET} parameter. - * - * @param params HTTP parameters. - * @param charset HTTP element charset. - */ - public static void setHttpElementCharset(final HttpParams params, final String charset) { - Args.notNull(params, "HTTP parameters"); - params.setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET, charset); - } - - /** - * Obtains value of the {@link CoreProtocolPNames#HTTP_CONTENT_CHARSET} parameter. - * If not set, defaults to {@code ISO-8859-1}. - * - * @param params HTTP parameters. - * @return HTTP content charset. - */ - public static String getContentCharset(final HttpParams params) { - Args.notNull(params, "HTTP parameters"); - String charset = (String) params.getParameter - (CoreProtocolPNames.HTTP_CONTENT_CHARSET); - if (charset == null) { - charset = HTTP.DEF_CONTENT_CHARSET.name(); - } - return charset; - } - - /** - * Sets value of the {@link CoreProtocolPNames#HTTP_CONTENT_CHARSET} parameter. - * - * @param params HTTP parameters. - * @param charset HTTP content charset. - */ - public static void setContentCharset(final HttpParams params, final String charset) { - Args.notNull(params, "HTTP parameters"); - params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, charset); - } - - /** - * Obtains value of the {@link CoreProtocolPNames#PROTOCOL_VERSION} parameter. - * If not set, defaults to {@link HttpVersion#HTTP_1_1}. - * - * @param params HTTP parameters. - * @return HTTP protocol version. - */ - public static ProtocolVersion getVersion(final HttpParams params) { - Args.notNull(params, "HTTP parameters"); - final Object param = params.getParameter - (CoreProtocolPNames.PROTOCOL_VERSION); - if (param == null) { - return HttpVersion.HTTP_1_1; - } - return (ProtocolVersion)param; - } - - /** - * Sets value of the {@link CoreProtocolPNames#PROTOCOL_VERSION} parameter. - * - * @param params HTTP parameters. - * @param version HTTP protocol version. - */ - public static void setVersion(final HttpParams params, final ProtocolVersion version) { - Args.notNull(params, "HTTP parameters"); - params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, version); - } - - /** - * Obtains value of the {@link CoreProtocolPNames#USER_AGENT} parameter. - * If not set, returns {@code null}. - * - * @param params HTTP parameters. - * @return User agent string. - */ - public static String getUserAgent(final HttpParams params) { - Args.notNull(params, "HTTP parameters"); - return (String) params.getParameter(CoreProtocolPNames.USER_AGENT); - } - - /** - * Sets value of the {@link CoreProtocolPNames#USER_AGENT} parameter. - * - * @param params HTTP parameters. - * @param useragent User agent string. - */ - public static void setUserAgent(final HttpParams params, final String useragent) { - Args.notNull(params, "HTTP parameters"); - params.setParameter(CoreProtocolPNames.USER_AGENT, useragent); - } - - /** - * Obtains value of the {@link CoreProtocolPNames#USE_EXPECT_CONTINUE} parameter. - * If not set, returns {@code false}. - * - * @param params HTTP parameters. - * @return User agent string. - */ - public static boolean useExpectContinue(final HttpParams params) { - Args.notNull(params, "HTTP parameters"); - return params.getBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); - } - - /** - * Sets value of the {@link CoreProtocolPNames#USE_EXPECT_CONTINUE} parameter. - * - * @param params HTTP parameters. - * @param b expect-continue flag. - */ - public static void setUseExpectContinue(final HttpParams params, final boolean b) { - Args.notNull(params, "HTTP parameters"); - params.setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, b); - } - - /** - * Obtains value of the {@link CoreProtocolPNames#HTTP_MALFORMED_INPUT_ACTION} parameter. - * @param params HTTP parameters. - * @return Action to perform upon receiving a malformed input - * - * @since 4.2 - */ - public static CodingErrorAction getMalformedInputAction(final HttpParams params) { - Args.notNull(params, "HTTP parameters"); - final Object param = params.getParameter(CoreProtocolPNames.HTTP_MALFORMED_INPUT_ACTION); - if (param == null) { - // the default CodingErrorAction - return CodingErrorAction.REPORT; - } - return (CodingErrorAction) param; - } - - /** - * Sets value of the {@link CoreProtocolPNames#HTTP_MALFORMED_INPUT_ACTION} parameter. - * @param params HTTP parameters - * @param action action to perform on malformed inputs - * - * @since 4.2 - */ - public static void setMalformedInputAction(final HttpParams params, final CodingErrorAction action) { - Args.notNull(params, "HTTP parameters"); - params.setParameter(CoreProtocolPNames.HTTP_MALFORMED_INPUT_ACTION, action); - } - - /** - * Obtains the value of the {@link CoreProtocolPNames#HTTP_UNMAPPABLE_INPUT_ACTION} parameter. - * @param params HTTP parameters - * @return Action to perform upon receiving a unmapped input - * - * @since 4.2 - */ - public static CodingErrorAction getUnmappableInputAction(final HttpParams params) { - Args.notNull(params, "HTTP parameters"); - final Object param = params.getParameter(CoreProtocolPNames.HTTP_UNMAPPABLE_INPUT_ACTION); - if (param == null) { - // the default CodingErrorAction - return CodingErrorAction.REPORT; - } - return (CodingErrorAction) param; - } - - /** - * Sets the value of the {@link CoreProtocolPNames#HTTP_UNMAPPABLE_INPUT_ACTION} parameter. - * @param params HTTP parameters - * @param action action to perform on un mappable inputs - * - * @since 4.2 - */ - public static void setUnmappableInputAction(final HttpParams params, final CodingErrorAction action) { - Args.notNull(params, "HTTP parameters"); - params.setParameter(CoreProtocolPNames.HTTP_UNMAPPABLE_INPUT_ACTION, action); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/SyncBasicHttpParams.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/SyncBasicHttpParams.java deleted file mode 100644 index 152f3e04..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/SyncBasicHttpParams.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 com.tracelytics.ext.apache.http.params; - -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; - -/** - * Thread-safe extension of the {@link BasicHttpParams}. - * - * @since 4.1 - * - * @deprecated (4.3) use configuration classes provided 'com.tracelytics.ext.apache.http.config' - * and 'com.tracelytics.ext.apache.http.client.config' - */ -@ThreadSafe -@Deprecated -public class SyncBasicHttpParams extends BasicHttpParams { - - private static final long serialVersionUID = 5387834869062660642L; - - public SyncBasicHttpParams() { - super(); - } - - @Override - public synchronized boolean removeParameter(final String name) { - return super.removeParameter(name); - } - - @Override - public synchronized HttpParams setParameter(final String name, final Object value) { - return super.setParameter(name, value); - } - - @Override - public synchronized Object getParameter(final String name) { - return super.getParameter(name); - } - - @Override - public synchronized boolean isParameterSet(final String name) { - return super.isParameterSet(name); - } - - @Override - public synchronized boolean isParameterSetLocally(final String name) { - return super.isParameterSetLocally(name); - } - - @Override - public synchronized void setParameters(final String[] names, final Object value) { - super.setParameters(names, value); - } - - @Override - public synchronized void clear() { - super.clear(); - } - - @Override - public synchronized Object clone() throws CloneNotSupportedException { - return super.clone(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/package-info.java deleted file mode 100644 index fa664f60..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/params/package-info.java +++ /dev/null @@ -1,32 +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 - * . - * - */ - -/** - * Deprecated. - * @deprecated (4.3). - */ -package com.tracelytics.ext.apache.http.params; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/AbstractConnPool.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/AbstractConnPool.java deleted file mode 100644 index be50913a..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/AbstractConnPool.java +++ /dev/null @@ -1,599 +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 com.tracelytics.ext.apache.http.pool; - -import java.io.IOException; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.concurrent.FutureCallback; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.Asserts; - -/** - * Abstract synchronous (blocking) pool of connections. - *

- * Please note that this class does not maintain its own pool of execution {@link Thread}s. - * Therefore, one must call {@link Future#get()} or {@link Future#get(long, TimeUnit)} - * method on the {@link Future} object returned by the - * {@link #lease(Object, Object, FutureCallback)} method in order for the lease operation - * to complete. - * - * @param the route type that represents the opposite endpoint of a pooled - * connection. - * @param the connection type. - * @param the type of the pool entry containing a pooled connection. - * @since 4.2 - */ -@ThreadSafe -public abstract class AbstractConnPool> - implements ConnPool, ConnPoolControl { - - private final Lock lock; - private final ConnFactory connFactory; - private final Map> routeToPool; - private final Set leased; - private final LinkedList available; - private final LinkedList> pending; - private final Map maxPerRoute; - - private volatile boolean isShutDown; - private volatile int defaultMaxPerRoute; - private volatile int maxTotal; - private volatile int validateAfterInactivity; - - public AbstractConnPool( - final ConnFactory connFactory, - final int defaultMaxPerRoute, - final int maxTotal) { - super(); - this.connFactory = Args.notNull(connFactory, "Connection factory"); - this.defaultMaxPerRoute = Args.positive(defaultMaxPerRoute, "Max per route value"); - this.maxTotal = Args.positive(maxTotal, "Max total value"); - this.lock = new ReentrantLock(); - this.routeToPool = new HashMap>(); - this.leased = new HashSet(); - this.available = new LinkedList(); - this.pending = new LinkedList>(); - this.maxPerRoute = new HashMap(); - } - - /** - * Creates a new entry for the given connection with the given route. - */ - protected abstract E createEntry(T route, C conn); - - /** - * @since 4.3 - */ - protected void onLease(final E entry) { - } - - /** - * @since 4.3 - */ - protected void onRelease(final E entry) { - } - - /** - * @since 4.4 - */ - protected void onReuse(final E entry) { - } - - /** - * @since 4.4 - */ - protected boolean validate(final E entry) { - return true; - } - - public boolean isShutdown() { - return this.isShutDown; - } - - /** - * Shuts down the pool. - */ - public void shutdown() throws IOException { - if (this.isShutDown) { - return ; - } - this.isShutDown = true; - this.lock.lock(); - try { - for (final E entry: this.available) { - entry.close(); - } - for (final E entry: this.leased) { - entry.close(); - } - for (final RouteSpecificPool pool: this.routeToPool.values()) { - pool.shutdown(); - } - this.routeToPool.clear(); - this.leased.clear(); - this.available.clear(); - } finally { - this.lock.unlock(); - } - } - - private RouteSpecificPool getPool(final T route) { - RouteSpecificPool pool = this.routeToPool.get(route); - if (pool == null) { - pool = new RouteSpecificPool(route) { - - @Override - protected E createEntry(final C conn) { - return AbstractConnPool.this.createEntry(route, conn); - } - - }; - this.routeToPool.put(route, pool); - } - return pool; - } - - /** - * {@inheritDoc} - *

- * Please note that this class does not maintain its own pool of execution - * {@link Thread}s. Therefore, one must call {@link Future#get()} - * or {@link Future#get(long, TimeUnit)} method on the {@link Future} - * returned by this method in order for the lease operation to complete. - */ - @Override - public Future lease(final T route, final Object state, final FutureCallback callback) { - Args.notNull(route, "Route"); - Asserts.check(!this.isShutDown, "Connection pool shut down"); - return new PoolEntryFuture(this.lock, callback) { - - @Override - public E getPoolEntry( - final long timeout, - final TimeUnit tunit) - throws InterruptedException, TimeoutException, IOException { - final E entry = getPoolEntryBlocking(route, state, timeout, tunit, this); - onLease(entry); - return entry; - } - - }; - } - - /** - * Attempts to lease a connection for the given route and with the given - * state from the pool. - *

- * Please note that this class does not maintain its own pool of execution - * {@link Thread}s. Therefore, one must call {@link Future#get()} - * or {@link Future#get(long, TimeUnit)} method on the {@link Future} - * returned by this method in order for the lease operation to complete. - * - * @param route route of the connection. - * @param state arbitrary object that represents a particular state - * (usually a security principal or a unique token identifying - * the user whose credentials have been used while establishing the connection). - * May be {@code null}. - * @return future for a leased pool entry. - */ - public Future lease(final T route, final Object state) { - return lease(route, state, null); - } - - private E getPoolEntryBlocking( - final T route, final Object state, - final long timeout, final TimeUnit tunit, - final PoolEntryFuture future) - throws IOException, InterruptedException, TimeoutException { - - Date deadline = null; - if (timeout > 0) { - deadline = new Date - (System.currentTimeMillis() + tunit.toMillis(timeout)); - } - - this.lock.lock(); - try { - final RouteSpecificPool pool = getPool(route); - E entry = null; - while (entry == null) { - Asserts.check(!this.isShutDown, "Connection pool shut down"); - for (;;) { - entry = pool.getFree(state); - if (entry == null) { - break; - } - if (entry.isExpired(System.currentTimeMillis())) { - entry.close(); - } else if (this.validateAfterInactivity > 0) { - if (entry.getUpdated() + this.validateAfterInactivity <= System.currentTimeMillis()) { - if (!validate(entry)) { - entry.close(); - } - } - } - if (entry.isClosed()) { - this.available.remove(entry); - pool.free(entry, false); - } else { - break; - } - } - if (entry != null) { - this.available.remove(entry); - this.leased.add(entry); - onReuse(entry); - return entry; - } - - // New connection is needed - final int maxPerRoute = getMax(route); - // Shrink the pool prior to allocating a new connection - final int excess = Math.max(0, pool.getAllocatedCount() + 1 - maxPerRoute); - if (excess > 0) { - for (int i = 0; i < excess; i++) { - final E lastUsed = pool.getLastUsed(); - if (lastUsed == null) { - break; - } - lastUsed.close(); - this.available.remove(lastUsed); - pool.remove(lastUsed); - } - } - - if (pool.getAllocatedCount() < maxPerRoute) { - final int totalUsed = this.leased.size(); - final int freeCapacity = Math.max(this.maxTotal - totalUsed, 0); - if (freeCapacity > 0) { - final int totalAvailable = this.available.size(); - if (totalAvailable > freeCapacity - 1) { - if (!this.available.isEmpty()) { - final E lastUsed = this.available.removeLast(); - lastUsed.close(); - final RouteSpecificPool otherpool = getPool(lastUsed.getRoute()); - otherpool.remove(lastUsed); - } - } - final C conn = this.connFactory.create(route); - entry = pool.add(conn); - this.leased.add(entry); - return entry; - } - } - - boolean success = false; - try { - pool.queue(future); - this.pending.add(future); - success = future.await(deadline); - } finally { - // In case of 'success', we were woken up by the - // connection pool and should now have a connection - // waiting for us, or else we're shutting down. - // Just continue in the loop, both cases are checked. - pool.unqueue(future); - this.pending.remove(future); - } - // check for spurious wakeup vs. timeout - if (!success && (deadline != null) && - (deadline.getTime() <= System.currentTimeMillis())) { - break; - } - } - throw new TimeoutException("Timeout waiting for connection"); - } finally { - this.lock.unlock(); - } - } - - @Override - public void release(final E entry, final boolean reusable) { - this.lock.lock(); - try { - if (this.leased.remove(entry)) { - final RouteSpecificPool pool = getPool(entry.getRoute()); - pool.free(entry, reusable); - if (reusable && !this.isShutDown) { - this.available.addFirst(entry); - onRelease(entry); - } else { - entry.close(); - } - PoolEntryFuture future = pool.nextPending(); - if (future != null) { - this.pending.remove(future); - } else { - future = this.pending.poll(); - } - if (future != null) { - future.wakeup(); - } - } - } finally { - this.lock.unlock(); - } - } - - private int getMax(final T route) { - final Integer v = this.maxPerRoute.get(route); - if (v != null) { - return v.intValue(); - } else { - return this.defaultMaxPerRoute; - } - } - - @Override - public void setMaxTotal(final int max) { - Args.positive(max, "Max value"); - this.lock.lock(); - try { - this.maxTotal = max; - } finally { - this.lock.unlock(); - } - } - - @Override - public int getMaxTotal() { - this.lock.lock(); - try { - return this.maxTotal; - } finally { - this.lock.unlock(); - } - } - - @Override - public void setDefaultMaxPerRoute(final int max) { - Args.positive(max, "Max per route value"); - this.lock.lock(); - try { - this.defaultMaxPerRoute = max; - } finally { - this.lock.unlock(); - } - } - - @Override - public int getDefaultMaxPerRoute() { - this.lock.lock(); - try { - return this.defaultMaxPerRoute; - } finally { - this.lock.unlock(); - } - } - - @Override - public void setMaxPerRoute(final T route, final int max) { - Args.notNull(route, "Route"); - Args.positive(max, "Max per route value"); - this.lock.lock(); - try { - this.maxPerRoute.put(route, Integer.valueOf(max)); - } finally { - this.lock.unlock(); - } - } - - @Override - public int getMaxPerRoute(final T route) { - Args.notNull(route, "Route"); - this.lock.lock(); - try { - return getMax(route); - } finally { - this.lock.unlock(); - } - } - - @Override - public PoolStats getTotalStats() { - this.lock.lock(); - try { - return new PoolStats( - this.leased.size(), - this.pending.size(), - this.available.size(), - this.maxTotal); - } finally { - this.lock.unlock(); - } - } - - @Override - public PoolStats getStats(final T route) { - Args.notNull(route, "Route"); - this.lock.lock(); - try { - final RouteSpecificPool pool = getPool(route); - return new PoolStats( - pool.getLeasedCount(), - pool.getPendingCount(), - pool.getAvailableCount(), - getMax(route)); - } finally { - this.lock.unlock(); - } - } - - /** - * Returns snapshot of all knows routes - * @return the set of routes - * - * @since 4.4 - */ - public Set getRoutes() { - this.lock.lock(); - try { - return new HashSet(routeToPool.keySet()); - } finally { - this.lock.unlock(); - } - } - - /** - * Enumerates all available connections. - * - * @since 4.3 - */ - protected void enumAvailable(final PoolEntryCallback callback) { - this.lock.lock(); - try { - final Iterator it = this.available.iterator(); - while (it.hasNext()) { - final E entry = it.next(); - callback.process(entry); - if (entry.isClosed()) { - final RouteSpecificPool pool = getPool(entry.getRoute()); - pool.remove(entry); - it.remove(); - } - } - purgePoolMap(); - } finally { - this.lock.unlock(); - } - } - - /** - * Enumerates all leased connections. - * - * @since 4.3 - */ - protected void enumLeased(final PoolEntryCallback callback) { - this.lock.lock(); - try { - final Iterator it = this.leased.iterator(); - while (it.hasNext()) { - final E entry = it.next(); - callback.process(entry); - } - } finally { - this.lock.unlock(); - } - } - - private void purgePoolMap() { - final Iterator>> it = this.routeToPool.entrySet().iterator(); - while (it.hasNext()) { - final Map.Entry> entry = it.next(); - final RouteSpecificPool pool = entry.getValue(); - if (pool.getPendingCount() + pool.getAllocatedCount() == 0) { - it.remove(); - } - } - } - - /** - * Closes connections that have been idle longer than the given period - * of time and evicts them from the pool. - * - * @param idletime maximum idle time. - * @param tunit time unit. - */ - public void closeIdle(final long idletime, final TimeUnit tunit) { - Args.notNull(tunit, "Time unit"); - long time = tunit.toMillis(idletime); - if (time < 0) { - time = 0; - } - final long deadline = System.currentTimeMillis() - time; - enumAvailable(new PoolEntryCallback() { - - @Override - public void process(final PoolEntry entry) { - if (entry.getUpdated() <= deadline) { - entry.close(); - } - } - - }); - } - - /** - * Closes expired connections and evicts them from the pool. - */ - public void closeExpired() { - final long now = System.currentTimeMillis(); - enumAvailable(new PoolEntryCallback() { - - @Override - public void process(final PoolEntry entry) { - if (entry.isExpired(now)) { - entry.close(); - } - } - - }); - } - - /** - * @return the number of milliseconds - * @since 4.4 - */ - public int getValidateAfterInactivity() { - return this.validateAfterInactivity; - } - - /** - * @param ms the number of milliseconds - * @since 4.4 - */ - public void setValidateAfterInactivity(final int ms) { - this.validateAfterInactivity = ms; - } - - @Override - public String toString() { - final StringBuilder buffer = new StringBuilder(); - buffer.append("[leased: "); - buffer.append(this.leased); - buffer.append("][available: "); - buffer.append(this.available); - buffer.append("][pending: "); - buffer.append(this.pending); - buffer.append("]"); - return buffer.toString(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/ConnFactory.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/ConnFactory.java deleted file mode 100644 index fde65030..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/ConnFactory.java +++ /dev/null @@ -1,44 +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 com.tracelytics.ext.apache.http.pool; - -import java.io.IOException; - -/** - * Factory for poolable blocking connections. - * - * @param the route type that represents the opposite endpoint of a pooled - * connection. - * @param the connection type. - * @since 4.2 - */ -public interface ConnFactory { - - C create(T route) throws IOException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/ConnPool.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/ConnPool.java deleted file mode 100644 index 4285a569..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/ConnPool.java +++ /dev/null @@ -1,68 +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 com.tracelytics.ext.apache.http.pool; - -import java.util.concurrent.Future; - -import com.tracelytics.ext.apache.http.concurrent.FutureCallback; - -/** - * {@code ConnPool} represents a shared pool connections can be leased from - * and released back to. - * - * @param the route type that represents the opposite endpoint of a pooled - * connection. - * @param the type of the pool entry containing a pooled connection. - * @since 4.2 - */ -public interface ConnPool { - - /** - * Attempts to lease a connection for the given route and with the given - * state from the pool. - * - * @param route route of the connection. - * @param state arbitrary object that represents a particular state - * (usually a security principal or a unique token identifying - * the user whose credentials have been used while establishing the connection). - * May be {@code null}. - * @param callback operation completion callback. - * - * @return future for a leased pool entry. - */ - Future lease(final T route, final Object state, final FutureCallback callback); - - /** - * Releases the pool entry back to the pool. - * - * @param entry pool entry leased from the pool - * @param reusable flag indicating whether or not the released connection - * is in a consistent state and is safe for further use. - */ - void release(E entry, boolean reusable); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/ConnPoolControl.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/ConnPoolControl.java deleted file mode 100644 index 0a66b80c..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/ConnPoolControl.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 com.tracelytics.ext.apache.http.pool; - -/** - * Interface to control runtime properties of a {@link ConnPool} such as - * maximum total number of connections or maximum connections per route - * allowed. - * - * @param the route type that represents the opposite endpoint of a pooled - * connection. - * @since 4.2 - */ -public interface ConnPoolControl { - - void setMaxTotal(int max); - - int getMaxTotal(); - - void setDefaultMaxPerRoute(int max); - - int getDefaultMaxPerRoute(); - - void setMaxPerRoute(final T route, int max); - - int getMaxPerRoute(final T route); - - PoolStats getTotalStats(); - - PoolStats getStats(final T route); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/PoolEntry.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/PoolEntry.java deleted file mode 100644 index ecbe147f..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/PoolEntry.java +++ /dev/null @@ -1,194 +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 com.tracelytics.ext.apache.http.pool; - -import java.util.concurrent.TimeUnit; - -import com.tracelytics.ext.apache.http.annotation.GuardedBy; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Pool entry containing a pool connection object along with its route. - *

- * The connection contained by the pool entry may have an expiration time which - * can be either set upon construction time or updated with - * the {@link #updateExpiry(long, TimeUnit)}. - *

- * Pool entry may also have an object associated with it that represents - * a connection state (usually a security principal or a unique token identifying - * the user whose credentials have been used while establishing the connection). - * - * @param the route type that represents the opposite endpoint of a pooled - * connection. - * @param the connection type. - * @since 4.2 - */ -@ThreadSafe -public abstract class PoolEntry { - - private final String id; - private final T route; - private final C conn; - private final long created; - private final long validityDeadline; - - @GuardedBy("this") - private long updated; - - @GuardedBy("this") - private long expiry; - - private volatile Object state; - - /** - * Creates new {@code PoolEntry} instance. - * - * @param id unique identifier of the pool entry. May be {@code null}. - * @param route route to the opposite endpoint. - * @param conn the connection. - * @param timeToLive maximum time to live. May be zero if the connection - * does not have an expiry deadline. - * @param tunit time unit. - */ - public PoolEntry(final String id, final T route, final C conn, - final long timeToLive, final TimeUnit tunit) { - super(); - Args.notNull(route, "Route"); - Args.notNull(conn, "Connection"); - Args.notNull(tunit, "Time unit"); - this.id = id; - this.route = route; - this.conn = conn; - this.created = System.currentTimeMillis(); - if (timeToLive > 0) { - this.validityDeadline = this.created + tunit.toMillis(timeToLive); - } else { - this.validityDeadline = Long.MAX_VALUE; - } - this.expiry = this.validityDeadline; - } - - /** - * Creates new {@code PoolEntry} instance without an expiry deadline. - * - * @param id unique identifier of the pool entry. May be {@code null}. - * @param route route to the opposite endpoint. - * @param conn the connection. - */ - public PoolEntry(final String id, final T route, final C conn) { - this(id, route, conn, 0, TimeUnit.MILLISECONDS); - } - - public String getId() { - return this.id; - } - - public T getRoute() { - return this.route; - } - - public C getConnection() { - return this.conn; - } - - public long getCreated() { - return this.created; - } - - /** - * @since 4.4 - */ - public long getValidityDeadline() { - return this.validityDeadline; - } - - /** - * @deprecated use {@link #getValidityDeadline()} - */ - @Deprecated - public long getValidUnit() { - return this.validityDeadline; - } - - public Object getState() { - return this.state; - } - - public void setState(final Object state) { - this.state = state; - } - - public synchronized long getUpdated() { - return this.updated; - } - - public synchronized long getExpiry() { - return this.expiry; - } - - public synchronized void updateExpiry(final long time, final TimeUnit tunit) { - Args.notNull(tunit, "Time unit"); - this.updated = System.currentTimeMillis(); - final long newExpiry; - if (time > 0) { - newExpiry = this.updated + tunit.toMillis(time); - } else { - newExpiry = Long.MAX_VALUE; - } - this.expiry = Math.min(newExpiry, this.validityDeadline); - } - - public synchronized boolean isExpired(final long now) { - return now >= this.expiry; - } - - /** - * Invalidates the pool entry and closes the pooled connection associated - * with it. - */ - public abstract void close(); - - /** - * Returns {@code true} if the pool entry has been invalidated. - */ - public abstract boolean isClosed(); - - @Override - public String toString() { - final StringBuilder buffer = new StringBuilder(); - buffer.append("[id:"); - buffer.append(this.id); - buffer.append("][route:"); - buffer.append(this.route); - buffer.append("][state:"); - buffer.append(this.state); - buffer.append("]"); - return buffer.toString(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/PoolEntryCallback.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/PoolEntryCallback.java deleted file mode 100644 index 80f96df1..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/PoolEntryCallback.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 com.tracelytics.ext.apache.http.pool; - -/** - * Pool entry callabck. - * - * @param the route type that represents the opposite endpoint of a pooled - * connection. - * @param the connection type. - * @since 4.3 - */ -public interface PoolEntryCallback { - - void process(PoolEntry entry); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/PoolEntryFuture.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/PoolEntryFuture.java deleted file mode 100644 index 012e5978..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/PoolEntryFuture.java +++ /dev/null @@ -1,160 +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 com.tracelytics.ext.apache.http.pool; - -import java.io.IOException; -import java.util.Date; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.locks.Condition; -import java.util.concurrent.locks.Lock; - -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.concurrent.FutureCallback; -import com.tracelytics.ext.apache.http.util.Args; - -@ThreadSafe -abstract class PoolEntryFuture implements Future { - - private final Lock lock; - private final FutureCallback callback; - private final Condition condition; - private volatile boolean cancelled; - private volatile boolean completed; - private T result; - - PoolEntryFuture(final Lock lock, final FutureCallback callback) { - super(); - this.lock = lock; - this.condition = lock.newCondition(); - this.callback = callback; - } - - @Override - public boolean cancel(final boolean mayInterruptIfRunning) { - this.lock.lock(); - try { - if (this.completed) { - return false; - } - this.completed = true; - this.cancelled = true; - if (this.callback != null) { - this.callback.cancelled(); - } - this.condition.signalAll(); - return true; - } finally { - this.lock.unlock(); - } - } - - @Override - public boolean isCancelled() { - return this.cancelled; - } - - @Override - public boolean isDone() { - return this.completed; - } - - @Override - public T get() throws InterruptedException, ExecutionException { - try { - return get(0, TimeUnit.MILLISECONDS); - } catch (final TimeoutException ex) { - throw new ExecutionException(ex); - } - } - - @Override - public T get( - final long timeout, - final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { - Args.notNull(unit, "Time unit"); - this.lock.lock(); - try { - if (this.completed) { - return this.result; - } - this.result = getPoolEntry(timeout, unit); - this.completed = true; - if (this.callback != null) { - this.callback.completed(this.result); - } - return result; - } catch (final IOException ex) { - this.completed = true; - this.result = null; - if (this.callback != null) { - this.callback.failed(ex); - } - throw new ExecutionException(ex); - } finally { - this.lock.unlock(); - } - } - - protected abstract T getPoolEntry( - long timeout, TimeUnit unit) throws IOException, InterruptedException, TimeoutException; - - public boolean await(final Date deadline) throws InterruptedException { - this.lock.lock(); - try { - if (this.cancelled) { - throw new InterruptedException("Operation interrupted"); - } - final boolean success; - if (deadline != null) { - success = this.condition.awaitUntil(deadline); - } else { - this.condition.await(); - success = true; - } - if (this.cancelled) { - throw new InterruptedException("Operation interrupted"); - } - return success; - } finally { - this.lock.unlock(); - } - - } - - public void wakeup() { - this.lock.lock(); - try { - this.condition.signalAll(); - } finally { - this.lock.unlock(); - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/PoolStats.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/PoolStats.java deleted file mode 100644 index d79fd2d5..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/PoolStats.java +++ /dev/null @@ -1,114 +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 com.tracelytics.ext.apache.http.pool; - -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * Pool statistics. - *

- * The total number of connections in the pool is equal to {@code available} plus {@code leased}. - *

- * - * @since 4.2 - */ -@Immutable -public class PoolStats { - - private final int leased; - private final int pending; - private final int available; - private final int max; - - public PoolStats(final int leased, final int pending, final int free, final int max) { - super(); - this.leased = leased; - this.pending = pending; - this.available = free; - this.max = max; - } - - /** - * Gets the number of persistent connections tracked by the connection manager currently being used to execute - * requests. - *

- * The total number of connections in the pool is equal to {@code available} plus {@code leased}. - *

- * - * @return the number of persistent connections. - */ - public int getLeased() { - return this.leased; - } - - /** - * Gets the number of connection requests being blocked awaiting a free connection. This can happen only if there - * are more worker threads contending for fewer connections. - * - * @return the number of connection requests being blocked awaiting a free connection. - */ - public int getPending() { - return this.pending; - } - - /** - * Gets the number idle persistent connections. - *

- * The total number of connections in the pool is equal to {@code available} plus {@code leased}. - *

- * - * @return number idle persistent connections. - */ - public int getAvailable() { - return this.available; - } - - /** - * Gets the maximum number of allowed persistent connections. - * - * @return the maximum number of allowed persistent connections. - */ - public int getMax() { - return this.max; - } - - @Override - public String toString() { - final StringBuilder buffer = new StringBuilder(); - buffer.append("[leased: "); - buffer.append(this.leased); - buffer.append("; pending: "); - buffer.append(this.pending); - buffer.append("; available: "); - buffer.append(this.available); - buffer.append("; max: "); - buffer.append(this.max); - buffer.append("]"); - return buffer.toString(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/RouteSpecificPool.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/RouteSpecificPool.java deleted file mode 100644 index 2a9e00bd..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/RouteSpecificPool.java +++ /dev/null @@ -1,184 +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 com.tracelytics.ext.apache.http.pool; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.Set; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.Asserts; - -@NotThreadSafe -abstract class RouteSpecificPool> { - - private final T route; - private final Set leased; - private final LinkedList available; - private final LinkedList> pending; - - RouteSpecificPool(final T route) { - super(); - this.route = route; - this.leased = new HashSet(); - this.available = new LinkedList(); - this.pending = new LinkedList>(); - } - - protected abstract E createEntry(C conn); - - public final T getRoute() { - return route; - } - - public int getLeasedCount() { - return this.leased.size(); - } - - public int getPendingCount() { - return this.pending.size(); - } - - public int getAvailableCount() { - return this.available.size(); - } - - public int getAllocatedCount() { - return this.available.size() + this.leased.size(); - } - - public E getFree(final Object state) { - if (!this.available.isEmpty()) { - if (state != null) { - final Iterator it = this.available.iterator(); - while (it.hasNext()) { - final E entry = it.next(); - if (state.equals(entry.getState())) { - it.remove(); - this.leased.add(entry); - return entry; - } - } - } - final Iterator it = this.available.iterator(); - while (it.hasNext()) { - final E entry = it.next(); - if (entry.getState() == null) { - it.remove(); - this.leased.add(entry); - return entry; - } - } - } - return null; - } - - public E getLastUsed() { - if (!this.available.isEmpty()) { - return this.available.getLast(); - } else { - return null; - } - } - - public boolean remove(final E entry) { - Args.notNull(entry, "Pool entry"); - if (!this.available.remove(entry)) { - if (!this.leased.remove(entry)) { - return false; - } - } - return true; - } - - public void free(final E entry, final boolean reusable) { - Args.notNull(entry, "Pool entry"); - final boolean found = this.leased.remove(entry); - Asserts.check(found, "Entry %s has not been leased from this pool", entry); - if (reusable) { - this.available.addFirst(entry); - } - } - - public E add(final C conn) { - final E entry = createEntry(conn); - this.leased.add(entry); - return entry; - } - - public void queue(final PoolEntryFuture future) { - if (future == null) { - return; - } - this.pending.add(future); - } - - public PoolEntryFuture nextPending() { - return this.pending.poll(); - } - - public void unqueue(final PoolEntryFuture future) { - if (future == null) { - return; - } - - this.pending.remove(future); - } - - public void shutdown() { - for (final PoolEntryFuture future: this.pending) { - future.cancel(true); - } - this.pending.clear(); - for (final E entry: this.available) { - entry.close(); - } - this.available.clear(); - for (final E entry: this.leased) { - entry.close(); - } - this.leased.clear(); - } - - @Override - public String toString() { - final StringBuilder buffer = new StringBuilder(); - buffer.append("[route: "); - buffer.append(this.route); - buffer.append("][leased: "); - buffer.append(this.leased.size()); - buffer.append("][available: "); - buffer.append(this.available.size()); - buffer.append("][pending: "); - buffer.append(this.pending.size()); - buffer.append("]"); - return buffer.toString(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/package-info.java deleted file mode 100644 index 343e1d0c..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/pool/package-info.java +++ /dev/null @@ -1,32 +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 - * . - * - */ - -/** - * Client side connection pools APIs for synchronous, blocking - * communication. - */ -package com.tracelytics.ext.apache.http.pool; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/BasicHttpContext.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/BasicHttpContext.java deleted file mode 100644 index d75c98ce..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/BasicHttpContext.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 com.tracelytics.ext.apache.http.protocol; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Default implementation of {@link HttpContext}. - *

- * Please note instances of this class can be thread unsafe if the - * parent context is not thread safe. - * - * @since 4.0 - */ -@ThreadSafe -public class BasicHttpContext implements HttpContext { - - private final HttpContext parentContext; - private final Map map; - - public BasicHttpContext() { - this(null); - } - - public BasicHttpContext(final HttpContext parentContext) { - super(); - this.map = new ConcurrentHashMap(); - this.parentContext = parentContext; - } - - @Override - public Object getAttribute(final String id) { - Args.notNull(id, "Id"); - Object obj = this.map.get(id); - if (obj == null && this.parentContext != null) { - obj = this.parentContext.getAttribute(id); - } - return obj; - } - - @Override - public void setAttribute(final String id, final Object obj) { - Args.notNull(id, "Id"); - if (obj != null) { - this.map.put(id, obj); - } else { - this.map.remove(id); - } - } - - @Override - public Object removeAttribute(final String id) { - Args.notNull(id, "Id"); - return this.map.remove(id); - } - - /** - * @since 4.2 - */ - public void clear() { - this.map.clear(); - } - - @Override - public String toString() { - return this.map.toString(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/BasicHttpProcessor.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/BasicHttpProcessor.java deleted file mode 100644 index 4b7c7e45..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/BasicHttpProcessor.java +++ /dev/null @@ -1,246 +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 com.tracelytics.ext.apache.http.protocol; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpRequestInterceptor; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.HttpResponseInterceptor; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Default implementation of {@link HttpProcessor}. - *

- * Please note access to the internal structures of this class is not - * synchronized and therefore this class may be thread-unsafe. - * - * @since 4.0 - * - * @deprecated (4.3) - */ -@NotThreadSafe -@Deprecated -public final class BasicHttpProcessor implements - HttpProcessor, HttpRequestInterceptorList, HttpResponseInterceptorList, Cloneable { - - // Don't allow direct access, as nulls are not allowed - protected final List requestInterceptors = new ArrayList(); - protected final List responseInterceptors = new ArrayList(); - - public void addRequestInterceptor(final HttpRequestInterceptor itcp) { - if (itcp == null) { - return; - } - this.requestInterceptors.add(itcp); - } - - public void addRequestInterceptor( - final HttpRequestInterceptor itcp, final int index) { - if (itcp == null) { - return; - } - this.requestInterceptors.add(index, itcp); - } - - public void addResponseInterceptor( - final HttpResponseInterceptor itcp, final int index) { - if (itcp == null) { - return; - } - this.responseInterceptors.add(index, itcp); - } - - public void removeRequestInterceptorByClass(final Class clazz) { - for (final Iterator it = this.requestInterceptors.iterator(); - it.hasNext(); ) { - final Object request = it.next(); - if (request.getClass().equals(clazz)) { - it.remove(); - } - } - } - - public void removeResponseInterceptorByClass(final Class clazz) { - for (final Iterator it = this.responseInterceptors.iterator(); - it.hasNext(); ) { - final Object request = it.next(); - if (request.getClass().equals(clazz)) { - it.remove(); - } - } - } - - public final void addInterceptor(final HttpRequestInterceptor interceptor) { - addRequestInterceptor(interceptor); - } - - public final void addInterceptor(final HttpRequestInterceptor interceptor, final int index) { - addRequestInterceptor(interceptor, index); - } - - public int getRequestInterceptorCount() { - return this.requestInterceptors.size(); - } - - public HttpRequestInterceptor getRequestInterceptor(final int index) { - if ((index < 0) || (index >= this.requestInterceptors.size())) { - return null; - } - return this.requestInterceptors.get(index); - } - - public void clearRequestInterceptors() { - this.requestInterceptors.clear(); - } - - public void addResponseInterceptor(final HttpResponseInterceptor itcp) { - if (itcp == null) { - return; - } - this.responseInterceptors.add(itcp); - } - - public final void addInterceptor(final HttpResponseInterceptor interceptor) { - addResponseInterceptor(interceptor); - } - - public final void addInterceptor(final HttpResponseInterceptor interceptor, final int index) { - addResponseInterceptor(interceptor, index); - } - - public int getResponseInterceptorCount() { - return this.responseInterceptors.size(); - } - - public HttpResponseInterceptor getResponseInterceptor(final int index) { - if ((index < 0) || (index >= this.responseInterceptors.size())) { - return null; - } - return this.responseInterceptors.get(index); - } - - public void clearResponseInterceptors() { - this.responseInterceptors.clear(); - } - - /** - * Sets the interceptor lists. - * First, both interceptor lists maintained by this processor - * will be cleared. - * Subsequently, - * elements of the argument list that are request interceptors will be - * added to the request interceptor list. - * Elements that are response interceptors will be - * added to the response interceptor list. - * Elements that are both request and response interceptor will be - * added to both lists. - * Elements that are neither request nor response interceptor - * will be ignored. - * - * @param list the list of request and response interceptors - * from which to initialize - */ - public void setInterceptors(final List list) { - Args.notNull(list, "Inteceptor list"); - this.requestInterceptors.clear(); - this.responseInterceptors.clear(); - for (final Object obj : list) { - if (obj instanceof HttpRequestInterceptor) { - addInterceptor((HttpRequestInterceptor) obj); - } - if (obj instanceof HttpResponseInterceptor) { - addInterceptor((HttpResponseInterceptor) obj); - } - } - } - - /** - * Clears both interceptor lists maintained by this processor. - */ - public void clearInterceptors() { - clearRequestInterceptors(); - clearResponseInterceptors(); - } - - public void process( - final HttpRequest request, - final HttpContext context) - throws IOException, HttpException { - for (final HttpRequestInterceptor interceptor : this.requestInterceptors) { - interceptor.process(request, context); - } - } - - public void process( - final HttpResponse response, - final HttpContext context) - throws IOException, HttpException { - for (final HttpResponseInterceptor interceptor : this.responseInterceptors) { - interceptor.process(response, context); - } - } - - /** - * Sets up the target to have the same list of interceptors - * as the current instance. - * - * @param target object to be initialised - */ - protected void copyInterceptors(final BasicHttpProcessor target) { - target.requestInterceptors.clear(); - target.requestInterceptors.addAll(this.requestInterceptors); - target.responseInterceptors.clear(); - target.responseInterceptors.addAll(this.responseInterceptors); - } - - /** - * Creates a copy of this instance - * - * @return new instance of the BasicHttpProcessor - */ - public BasicHttpProcessor copy() { - final BasicHttpProcessor clone = new BasicHttpProcessor(); - copyInterceptors(clone); - return clone; - } - - @Override - public Object clone() throws CloneNotSupportedException { - final BasicHttpProcessor clone = (BasicHttpProcessor) super.clone(); - copyInterceptors(clone); - return clone; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/ChainBuilder.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/ChainBuilder.java deleted file mode 100644 index 5cf66a8a..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/ChainBuilder.java +++ /dev/null @@ -1,126 +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 com.tracelytics.ext.apache.http.protocol; - -import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.Map; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; - -/** - * Builder class to build a linked list (chain) of unique class instances. Each class can have - * only one instance in the list. Useful for building lists of protocol interceptors. - * - * @see ImmutableHttpProcessor - * - * @since 4.3 - */ -@NotThreadSafe -final class ChainBuilder { - - private final LinkedList list; - private final Map, E> uniqueClasses; - - public ChainBuilder() { - this.list = new LinkedList(); - this.uniqueClasses = new HashMap, E>(); - } - - private void ensureUnique(final E e) { - final E previous = this.uniqueClasses.remove(e.getClass()); - if (previous != null) { - this.list.remove(previous); - } - this.uniqueClasses.put(e.getClass(), e); - } - - public ChainBuilder addFirst(final E e) { - if (e == null) { - return this; - } - ensureUnique(e); - this.list.addFirst(e); - return this; - } - - public ChainBuilder addLast(final E e) { - if (e == null) { - return this; - } - ensureUnique(e); - this.list.addLast(e); - return this; - } - - public ChainBuilder addAllFirst(final Collection c) { - if (c == null) { - return this; - } - for (final E e: c) { - addFirst(e); - } - return this; - } - - public ChainBuilder addAllFirst(final E... c) { - if (c == null) { - return this; - } - for (final E e: c) { - addFirst(e); - } - return this; - } - - public ChainBuilder addAllLast(final Collection c) { - if (c == null) { - return this; - } - for (final E e: c) { - addLast(e); - } - return this; - } - - public ChainBuilder addAllLast(final E... c) { - if (c == null) { - return this; - } - for (final E e: c) { - addLast(e); - } - return this; - } - - public LinkedList build() { - return new LinkedList(this.list); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/DefaultedHttpContext.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/DefaultedHttpContext.java deleted file mode 100644 index 4074a79c..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/DefaultedHttpContext.java +++ /dev/null @@ -1,84 +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 com.tracelytics.ext.apache.http.protocol; - -import com.tracelytics.ext.apache.http.util.Args; - -/** - * {@link HttpContext} implementation that delegates resolution of an attribute - * to the given default {@link HttpContext} instance if the attribute is not - * present in the local one. The state of the local context can be mutated, - * whereas the default context is treated as read-only. - * - * @since 4.0 - * - * @deprecated (4.3) no longer used. - */ -@Deprecated -public final class DefaultedHttpContext implements HttpContext { - - private final HttpContext local; - private final HttpContext defaults; - - public DefaultedHttpContext(final HttpContext local, final HttpContext defaults) { - super(); - this.local = Args.notNull(local, "HTTP context"); - this.defaults = defaults; - } - - public Object getAttribute(final String id) { - final Object obj = this.local.getAttribute(id); - if (obj == null) { - return this.defaults.getAttribute(id); - } else { - return obj; - } - } - - public Object removeAttribute(final String id) { - return this.local.removeAttribute(id); - } - - public void setAttribute(final String id, final Object obj) { - this.local.setAttribute(id, obj); - } - - public HttpContext getDefaults() { - return this.defaults; - } - - @Override - public String toString() { - final StringBuilder buf = new StringBuilder(); - buf.append("[local: ").append(this.local); - buf.append("defaults: ").append(this.defaults); - buf.append("]"); - return buf.toString(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/ExecutionContext.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/ExecutionContext.java deleted file mode 100644 index 767c5412..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/ExecutionContext.java +++ /dev/null @@ -1,80 +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 com.tracelytics.ext.apache.http.protocol; - -/** - * {@link HttpContext} attribute names for protocol execution. - * - * @since 4.0 - * - * @deprecated (4.3) use {@link HttpCoreContext}. - */ -@Deprecated -public interface ExecutionContext { - - /** - * Attribute name of a {@link com.tracelytics.ext.apache.http.HttpConnection} object that - * represents the actual HTTP connection. - */ - public static final String HTTP_CONNECTION = "http.connection"; - - /** - * Attribute name of a {@link com.tracelytics.ext.apache.http.HttpRequest} object that - * represents the actual HTTP request. - */ - public static final String HTTP_REQUEST = "http.request"; - - /** - * Attribute name of a {@link com.tracelytics.ext.apache.http.HttpResponse} object that - * represents the actual HTTP response. - */ - public static final String HTTP_RESPONSE = "http.response"; - - /** - * Attribute name of a {@link com.tracelytics.ext.apache.http.HttpHost} object that - * represents the connection target. - */ - public static final String HTTP_TARGET_HOST = "http.target_host"; - - /** - * Attribute name of a {@link com.tracelytics.ext.apache.http.HttpHost} object that - * represents the connection proxy. - * - * @deprecated (4.3) do not use. - */ - @Deprecated - public static final String HTTP_PROXY_HOST = "http.proxy_host"; - - /** - * Attribute name of a {@link Boolean} object that represents the - * the flag indicating whether the actual request has been fully transmitted - * to the target host. - */ - public static final String HTTP_REQ_SENT = "http.request_sent"; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HTTP.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HTTP.java deleted file mode 100644 index 45710223..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HTTP.java +++ /dev/null @@ -1,135 +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 com.tracelytics.ext.apache.http.protocol; - -import java.nio.charset.Charset; - -import com.tracelytics.ext.apache.http.Consts; - -/** - * Constants and static helpers related to the HTTP protocol. - * - * @since 4.0 - */ -public final class HTTP { - - public static final int CR = 13; // - public static final int LF = 10; // - public static final int SP = 32; // - public static final int HT = 9; // - - /** HTTP header definitions */ - public static final String TRANSFER_ENCODING = "Transfer-Encoding"; - public static final String CONTENT_LEN = "Content-Length"; - public static final String CONTENT_TYPE = "Content-Type"; - public static final String CONTENT_ENCODING = "Content-Encoding"; - public static final String EXPECT_DIRECTIVE = "Expect"; - public static final String CONN_DIRECTIVE = "Connection"; - public static final String TARGET_HOST = "Host"; - public static final String USER_AGENT = "User-Agent"; - public static final String DATE_HEADER = "Date"; - public static final String SERVER_HEADER = "Server"; - - /** HTTP expectations */ - public static final String EXPECT_CONTINUE = "100-continue"; - - /** HTTP connection control */ - public static final String CONN_CLOSE = "Close"; - public static final String CONN_KEEP_ALIVE = "Keep-Alive"; - - /** Transfer encoding definitions */ - public static final String CHUNK_CODING = "chunked"; - public static final String IDENTITY_CODING = "identity"; - - public static final Charset DEF_CONTENT_CHARSET = Consts.ISO_8859_1; - public static final Charset DEF_PROTOCOL_CHARSET = Consts.ASCII; - - /** - * @deprecated (4.2) - */ - @Deprecated - public static final String UTF_8 = "UTF-8"; - /** - * @deprecated (4.2) - */ - @Deprecated - public static final String UTF_16 = "UTF-16"; - /** - * @deprecated (4.2) - */ - @Deprecated - public static final String US_ASCII = "US-ASCII"; - /** - * @deprecated (4.2) - */ - @Deprecated - public static final String ASCII = "ASCII"; - /** - * @deprecated (4.2) - */ - @Deprecated - public static final String ISO_8859_1 = "ISO-8859-1"; - /** - * @deprecated (4.2) - */ - @Deprecated - public static final String DEFAULT_CONTENT_CHARSET = ISO_8859_1; - /** - * @deprecated (4.2) - */ - @Deprecated - public static final String DEFAULT_PROTOCOL_CHARSET = US_ASCII; - /** - * @deprecated (4.2) - */ - @Deprecated - public final static String OCTET_STREAM_TYPE = "application/octet-stream"; - /** - * @deprecated (4.2) - */ - @Deprecated - public final static String PLAIN_TEXT_TYPE = "text/plain"; - /** - * @deprecated (4.2) - */ - @Deprecated - public final static String CHARSET_PARAM = "; charset="; - /** - * @deprecated (4.2) - */ - @Deprecated - public final static String DEFAULT_CONTENT_TYPE = OCTET_STREAM_TYPE; - - public static boolean isWhitespace(final char ch) { - return ch == SP || ch == HT || ch == CR || ch == LF; - } - - private HTTP() { - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpContext.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpContext.java deleted file mode 100644 index aed2dfb5..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpContext.java +++ /dev/null @@ -1,75 +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 com.tracelytics.ext.apache.http.protocol; - -/** - * HttpContext represents execution state of an HTTP process. It is a structure - * that can be used to map an attribute name to an attribute value. - *

- * The primary purpose of the HTTP context is to facilitate information sharing - * among various logically related components. HTTP context can be used - * to store a processing state for one message or several consecutive messages. - * Multiple logically related messages can participate in a logical session - * if the same context is reused between consecutive messages. - *

/ - * IMPORTANT: Please note HTTP context implementation, even when thread safe, - * may not be used concurrently by multiple threads, as the context may contain - * thread unsafe attributes. - * - * @since 4.0 - */ -public interface HttpContext { - - /** The prefix reserved for use by HTTP components. "http." */ - public static final String RESERVED_PREFIX = "http."; - - /** - * Obtains attribute with the given name. - * - * @param id the attribute name. - * @return attribute value, or {@code null} if not set. - */ - Object getAttribute(String id); - - /** - * Sets value of the attribute with the given name. - * - * @param id the attribute name. - * @param obj the attribute value. - */ - void setAttribute(String id, Object obj); - - /** - * Removes attribute with the given name from the context. - * - * @param id the attribute name. - * @return attribute value, or {@code null} if not set. - */ - Object removeAttribute(String id); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpCoreContext.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpCoreContext.java deleted file mode 100644 index 0cc0a340..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpCoreContext.java +++ /dev/null @@ -1,155 +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 com.tracelytics.ext.apache.http.protocol; - -import com.tracelytics.ext.apache.http.HttpConnection; -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Implementation of {@link HttpContext} that provides convenience - * setters for user assignable attributes and getter for readable attributes. - * - * @since 4.3 - */ -@NotThreadSafe -public class HttpCoreContext implements HttpContext { - - /** - * Attribute name of a {@link com.tracelytics.ext.apache.http.HttpConnection} object that - * represents the actual HTTP connection. - */ - public static final String HTTP_CONNECTION = "http.connection"; - - /** - * Attribute name of a {@link com.tracelytics.ext.apache.http.HttpRequest} object that - * represents the actual HTTP request. - */ - public static final String HTTP_REQUEST = "http.request"; - - /** - * Attribute name of a {@link com.tracelytics.ext.apache.http.HttpResponse} object that - * represents the actual HTTP response. - */ - public static final String HTTP_RESPONSE = "http.response"; - - /** - * Attribute name of a {@link com.tracelytics.ext.apache.http.HttpHost} object that - * represents the connection target. - */ - public static final String HTTP_TARGET_HOST = "http.target_host"; - - /** - * Attribute name of a {@link Boolean} object that represents the - * the flag indicating whether the actual request has been fully transmitted - * to the target host. - */ - public static final String HTTP_REQ_SENT = "http.request_sent"; - - public static HttpCoreContext create() { - return new HttpCoreContext(new BasicHttpContext()); - } - - public static HttpCoreContext adapt(final HttpContext context) { - Args.notNull(context, "HTTP context"); - if (context instanceof HttpCoreContext) { - return (HttpCoreContext) context; - } else { - return new HttpCoreContext(context); - } - } - - private final HttpContext context; - - public HttpCoreContext(final HttpContext context) { - super(); - this.context = context; - } - - public HttpCoreContext() { - super(); - this.context = new BasicHttpContext(); - } - - @Override - public Object getAttribute(final String id) { - return context.getAttribute(id); - } - - @Override - public void setAttribute(final String id, final Object obj) { - context.setAttribute(id, obj); - } - - @Override - public Object removeAttribute(final String id) { - return context.removeAttribute(id); - } - - public T getAttribute(final String attribname, final Class clazz) { - Args.notNull(clazz, "Attribute class"); - final Object obj = getAttribute(attribname); - if (obj == null) { - return null; - } - return clazz.cast(obj); - } - - public T getConnection(final Class clazz) { - return getAttribute(HTTP_CONNECTION, clazz); - } - - public HttpConnection getConnection() { - return getAttribute(HTTP_CONNECTION, HttpConnection.class); - } - - public HttpRequest getRequest() { - return getAttribute(HTTP_REQUEST, HttpRequest.class); - } - - public boolean isRequestSent() { - final Boolean b = getAttribute(HTTP_REQ_SENT, Boolean.class); - return b != null && b.booleanValue(); - } - - public HttpResponse getResponse() { - return getAttribute(HTTP_RESPONSE, HttpResponse.class); - } - - public void setTargetHost(final HttpHost host) { - setAttribute(HTTP_TARGET_HOST, host); - } - - public HttpHost getTargetHost() { - return getAttribute(HTTP_TARGET_HOST, HttpHost.class); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpDateGenerator.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpDateGenerator.java deleted file mode 100644 index 28ff1685..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpDateGenerator.java +++ /dev/null @@ -1,77 +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 com.tracelytics.ext.apache.http.protocol; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; -import java.util.TimeZone; - -import com.tracelytics.ext.apache.http.annotation.GuardedBy; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; - -/** - * Generates a date in the format required by the HTTP protocol. - * - * @since 4.0 - */ -@ThreadSafe -public class HttpDateGenerator { - - /** Date format pattern used to generate the header in RFC 1123 format. */ - public static final - String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz"; - - /** The time zone to use in the date header. */ - public static final TimeZone GMT = TimeZone.getTimeZone("GMT"); - - @GuardedBy("this") - private final DateFormat dateformat; - @GuardedBy("this") - private long dateAsLong = 0L; - @GuardedBy("this") - private String dateAsText = null; - - public HttpDateGenerator() { - super(); - this.dateformat = new SimpleDateFormat(PATTERN_RFC1123, Locale.US); - this.dateformat.setTimeZone(GMT); - } - - public synchronized String getCurrentDate() { - final long now = System.currentTimeMillis(); - if (now - this.dateAsLong > 1000) { - // Generate new date string - this.dateAsText = this.dateformat.format(new Date(now)); - this.dateAsLong = now; - } - return this.dateAsText; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpExpectationVerifier.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpExpectationVerifier.java deleted file mode 100644 index d703819e..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpExpectationVerifier.java +++ /dev/null @@ -1,81 +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 com.tracelytics.ext.apache.http.protocol; - -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpResponse; - -/** - * Defines an interface to verify whether an incoming HTTP request meets - * the target server's expectations. - *

- * The Expect request-header field is used to indicate that particular - * server behaviors are required by the client. - *

- *
- *    Expect       =  "Expect" ":" 1#expectation
- *
- *    expectation  =  "100-continue" | expectation-extension
- *    expectation-extension =  token [ "=" ( token | quoted-string )
- *                             *expect-params ]
- *    expect-params =  ";" token [ "=" ( token | quoted-string ) ]
- *
- *

- * A server that does not understand or is unable to comply with any of - * the expectation values in the Expect field of a request MUST respond - * with appropriate error status. The server MUST respond with a 417 - * (Expectation Failed) status if any of the expectations cannot be met - * or, if there are other problems with the request, some other 4xx - * status. - *

- * - * @since 4.0 - */ -public interface HttpExpectationVerifier { - - /** - * Verifies whether the given request meets the server's expectations. - *

- * If the request fails to meet particular criteria, this method can - * trigger a terminal response back to the client by setting the status - * code of the response object to a value greater or equal to - * {@code 200}. In this case the client will not have to transmit - * the request body. If the request meets expectations this method can - * terminate without modifying the response object. Per default the status - * code of the response object will be set to {@code 100}. - * - * @param request the HTTP request. - * @param response the HTTP response. - * @param context the HTTP context. - * @throws HttpException in case of an HTTP protocol violation. - */ - void verify(HttpRequest request, HttpResponse response, HttpContext context) - throws HttpException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpProcessor.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpProcessor.java deleted file mode 100644 index 85618aa7..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpProcessor.java +++ /dev/null @@ -1,55 +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 com.tracelytics.ext.apache.http.protocol; - -import com.tracelytics.ext.apache.http.HttpRequestInterceptor; -import com.tracelytics.ext.apache.http.HttpResponseInterceptor; - -/** - * HTTP protocol processor is a collection of protocol interceptors that - * implements the 'Chain of Responsibility' pattern, where each individual - * protocol interceptor is expected to work on a particular aspect of the HTTP - * protocol the interceptor is responsible for. - *

- * Usually the order in which interceptors are executed should not matter as - * long as they do not depend on a particular state of the execution context. - * If protocol interceptors have interdependencies and therefore must be - * executed in a particular order, they should be added to the protocol - * processor in the same sequence as their expected execution order. - *

- * Protocol interceptors must be implemented as thread-safe. Similarly to - * servlets, protocol interceptors should not use instance variables unless - * access to those variables is synchronized. - * - * @since 4.0 - */ -public interface HttpProcessor - extends HttpRequestInterceptor, HttpResponseInterceptor { - - // no additional methods -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpProcessorBuilder.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpProcessorBuilder.java deleted file mode 100644 index 5c8dfc97..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpProcessorBuilder.java +++ /dev/null @@ -1,151 +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 com.tracelytics.ext.apache.http.protocol; - -import com.tracelytics.ext.apache.http.HttpRequestInterceptor; -import com.tracelytics.ext.apache.http.HttpResponseInterceptor; - -/** - * Builder for {@link HttpProcessor} instances. - * - * @since 4.3 - */ -public class HttpProcessorBuilder { - - private ChainBuilder requestChainBuilder; - private ChainBuilder responseChainBuilder; - - public static HttpProcessorBuilder create() { - return new HttpProcessorBuilder(); - } - - HttpProcessorBuilder() { - super(); - } - - private ChainBuilder getRequestChainBuilder() { - if (requestChainBuilder == null) { - requestChainBuilder = new ChainBuilder(); - } - return requestChainBuilder; - } - - private ChainBuilder getResponseChainBuilder() { - if (responseChainBuilder == null) { - responseChainBuilder = new ChainBuilder(); - } - return responseChainBuilder; - } - - public HttpProcessorBuilder addFirst(final HttpRequestInterceptor e) { - if (e == null) { - return this; - } - getRequestChainBuilder().addFirst(e); - return this; - } - - public HttpProcessorBuilder addLast(final HttpRequestInterceptor e) { - if (e == null) { - return this; - } - getRequestChainBuilder().addLast(e); - return this; - } - - public HttpProcessorBuilder add(final HttpRequestInterceptor e) { - return addLast(e); - } - - public HttpProcessorBuilder addAllFirst(final HttpRequestInterceptor... e) { - if (e == null) { - return this; - } - getRequestChainBuilder().addAllFirst(e); - return this; - } - - public HttpProcessorBuilder addAllLast(final HttpRequestInterceptor... e) { - if (e == null) { - return this; - } - getRequestChainBuilder().addAllLast(e); - return this; - } - - public HttpProcessorBuilder addAll(final HttpRequestInterceptor... e) { - return addAllLast(e); - } - - public HttpProcessorBuilder addFirst(final HttpResponseInterceptor e) { - if (e == null) { - return this; - } - getResponseChainBuilder().addFirst(e); - return this; - } - - public HttpProcessorBuilder addLast(final HttpResponseInterceptor e) { - if (e == null) { - return this; - } - getResponseChainBuilder().addLast(e); - return this; - } - - public HttpProcessorBuilder add(final HttpResponseInterceptor e) { - return addLast(e); - } - - public HttpProcessorBuilder addAllFirst(final HttpResponseInterceptor... e) { - if (e == null) { - return this; - } - getResponseChainBuilder().addAllFirst(e); - return this; - } - - public HttpProcessorBuilder addAllLast(final HttpResponseInterceptor... e) { - if (e == null) { - return this; - } - getResponseChainBuilder().addAllLast(e); - return this; - } - - public HttpProcessorBuilder addAll(final HttpResponseInterceptor... e) { - return addAllLast(e); - } - - public HttpProcessor build() { - return new ImmutableHttpProcessor( - requestChainBuilder != null ? requestChainBuilder.build() : null, - responseChainBuilder != null ? responseChainBuilder.build() : null); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpRequestExecutor.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpRequestExecutor.java deleted file mode 100644 index 16a967a9..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpRequestExecutor.java +++ /dev/null @@ -1,312 +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 com.tracelytics.ext.apache.http.protocol; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.HttpClientConnection; -import com.tracelytics.ext.apache.http.HttpEntityEnclosingRequest; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.HttpStatus; -import com.tracelytics.ext.apache.http.HttpVersion; -import com.tracelytics.ext.apache.http.ProtocolException; -import com.tracelytics.ext.apache.http.ProtocolVersion; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * {@code HttpRequestExecutor} is a client side HTTP protocol handler based - * on the blocking (classic) I/O model. - *

- * {@code HttpRequestExecutor} relies on {@link HttpProcessor} to generate - * mandatory protocol headers for all outgoing messages and apply common, - * cross-cutting message transformations to all incoming and outgoing messages. - * Application specific processing can be implemented outside - * {@code HttpRequestExecutor} once the request has been executed and - * a response has been received. - * - * @since 4.0 - */ -@Immutable -public class HttpRequestExecutor { - - public static final int DEFAULT_WAIT_FOR_CONTINUE = 3000; - - private final int waitForContinue; - - /** - * Creates new instance of HttpRequestExecutor. - * - * @since 4.3 - */ - public HttpRequestExecutor(final int waitForContinue) { - super(); - this.waitForContinue = Args.positive(waitForContinue, "Wait for continue time"); - } - - public HttpRequestExecutor() { - this(DEFAULT_WAIT_FOR_CONTINUE); - } - - /** - * Decide whether a response comes with an entity. - * The implementation in this class is based on RFC 2616. - *

- * Derived executors can override this method to handle - * methods and response codes not specified in RFC 2616. - *

- * - * @param request the request, to obtain the executed method - * @param response the response, to obtain the status code - */ - protected boolean canResponseHaveBody(final HttpRequest request, - final HttpResponse response) { - - if ("HEAD".equalsIgnoreCase(request.getRequestLine().getMethod())) { - return false; - } - final int status = response.getStatusLine().getStatusCode(); - return status >= HttpStatus.SC_OK - && status != HttpStatus.SC_NO_CONTENT - && status != HttpStatus.SC_NOT_MODIFIED - && status != HttpStatus.SC_RESET_CONTENT; - } - - /** - * Sends the request and obtain a response. - * - * @param request the request to execute. - * @param conn the connection over which to execute the request. - * - * @return the response to the request. - * - * @throws IOException in case of an I/O error. - * @throws HttpException in case of HTTP protocol violation or a processing - * problem. - */ - public HttpResponse execute( - final HttpRequest request, - final HttpClientConnection conn, - final HttpContext context) throws IOException, HttpException { - Args.notNull(request, "HTTP request"); - Args.notNull(conn, "Client connection"); - Args.notNull(context, "HTTP context"); - try { - HttpResponse response = doSendRequest(request, conn, context); - if (response == null) { - response = doReceiveResponse(request, conn, context); - } - return response; - } catch (final IOException ex) { - closeConnection(conn); - throw ex; - } catch (final HttpException ex) { - closeConnection(conn); - throw ex; - } catch (final RuntimeException ex) { - closeConnection(conn); - throw ex; - } - } - - private static void closeConnection(final HttpClientConnection conn) { - try { - conn.close(); - } catch (final IOException ignore) { - } - } - - /** - * Pre-process the given request using the given protocol processor and - * initiates the process of request execution. - * - * @param request the request to prepare - * @param processor the processor to use - * @param context the context for sending the request - * - * @throws IOException in case of an I/O error. - * @throws HttpException in case of HTTP protocol violation or a processing - * problem. - */ - public void preProcess( - final HttpRequest request, - final HttpProcessor processor, - final HttpContext context) throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - Args.notNull(processor, "HTTP processor"); - Args.notNull(context, "HTTP context"); - context.setAttribute(HttpCoreContext.HTTP_REQUEST, request); - processor.process(request, context); - } - - /** - * Send the given request over the given connection. - *

- * This method also handles the expect-continue handshake if necessary. - * If it does not have to handle an expect-continue handshake, it will - * not use the connection for reading or anything else that depends on - * data coming in over the connection. - * - * @param request the request to send, already - * {@link #preProcess preprocessed} - * @param conn the connection over which to send the request, - * already established - * @param context the context for sending the request - * - * @return a terminal response received as part of an expect-continue - * handshake, or - * {@code null} if the expect-continue handshake is not used - * - * @throws IOException in case of an I/O error. - * @throws HttpException in case of HTTP protocol violation or a processing - * problem. - */ - protected HttpResponse doSendRequest( - final HttpRequest request, - final HttpClientConnection conn, - final HttpContext context) throws IOException, HttpException { - Args.notNull(request, "HTTP request"); - Args.notNull(conn, "Client connection"); - Args.notNull(context, "HTTP context"); - - HttpResponse response = null; - - context.setAttribute(HttpCoreContext.HTTP_CONNECTION, conn); - context.setAttribute(HttpCoreContext.HTTP_REQ_SENT, Boolean.FALSE); - - conn.sendRequestHeader(request); - if (request instanceof HttpEntityEnclosingRequest) { - // Check for expect-continue handshake. We have to flush the - // headers and wait for an 100-continue response to handle it. - // If we get a different response, we must not send the entity. - boolean sendentity = true; - final ProtocolVersion ver = - request.getRequestLine().getProtocolVersion(); - if (((HttpEntityEnclosingRequest) request).expectContinue() && - !ver.lessEquals(HttpVersion.HTTP_1_0)) { - - conn.flush(); - // As suggested by RFC 2616 section 8.2.3, we don't wait for a - // 100-continue response forever. On timeout, send the entity. - if (conn.isResponseAvailable(this.waitForContinue)) { - response = conn.receiveResponseHeader(); - if (canResponseHaveBody(request, response)) { - conn.receiveResponseEntity(response); - } - final int status = response.getStatusLine().getStatusCode(); - if (status < 200) { - if (status != HttpStatus.SC_CONTINUE) { - throw new ProtocolException( - "Unexpected response: " + response.getStatusLine()); - } - // discard 100-continue - response = null; - } else { - sendentity = false; - } - } - } - if (sendentity) { - conn.sendRequestEntity((HttpEntityEnclosingRequest) request); - } - } - conn.flush(); - context.setAttribute(HttpCoreContext.HTTP_REQ_SENT, Boolean.TRUE); - return response; - } - - /** - * Waits for and receives a response. - * This method will automatically ignore intermediate responses - * with status code 1xx. - * - * @param request the request for which to obtain the response - * @param conn the connection over which the request was sent - * @param context the context for receiving the response - * - * @return the terminal response, not yet post-processed - * - * @throws IOException in case of an I/O error. - * @throws HttpException in case of HTTP protocol violation or a processing - * problem. - */ - protected HttpResponse doReceiveResponse( - final HttpRequest request, - final HttpClientConnection conn, - final HttpContext context) throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - Args.notNull(conn, "Client connection"); - Args.notNull(context, "HTTP context"); - HttpResponse response = null; - int statusCode = 0; - - while (response == null || statusCode < HttpStatus.SC_OK) { - - response = conn.receiveResponseHeader(); - if (canResponseHaveBody(request, response)) { - conn.receiveResponseEntity(response); - } - statusCode = response.getStatusLine().getStatusCode(); - - } // while intermediate response - - return response; - } - - /** - * Post-processes the given response using the given protocol processor and - * completes the process of request execution. - *

- * This method does not read the response entity, if any. - * The connection over which content of the response entity is being - * streamed from cannot be reused until - * {@link com.tracelytics.ext.apache.http.util.EntityUtils#consume(com.tracelytics.ext.apache.http.HttpEntity)} - * has been invoked. - * - * @param response the response object to post-process - * @param processor the processor to use - * @param context the context for post-processing the response - * - * @throws IOException in case of an I/O error. - * @throws HttpException in case of HTTP protocol violation or a processing - * problem. - */ - public void postProcess( - final HttpResponse response, - final HttpProcessor processor, - final HttpContext context) throws HttpException, IOException { - Args.notNull(response, "HTTP response"); - Args.notNull(processor, "HTTP processor"); - Args.notNull(context, "HTTP context"); - context.setAttribute(HttpCoreContext.HTTP_RESPONSE, response); - processor.process(response, context); - } - -} // class HttpRequestExecutor diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpRequestHandler.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpRequestHandler.java deleted file mode 100644 index f48309f3..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpRequestHandler.java +++ /dev/null @@ -1,62 +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 com.tracelytics.ext.apache.http.protocol; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpResponse; - -/** - * HttpRequestHandler represents a routine for processing of a specific group - * of HTTP requests. Protocol handlers are designed to take care of protocol - * specific aspects, whereas individual request handlers are expected to take - * care of application specific HTTP processing. The main purpose of a request - * handler is to generate a response object with a content entity to be sent - * back to the client in response to the given request - * - * @since 4.0 - */ -public interface HttpRequestHandler { - - /** - * Handles the request and produces a response to be sent back to - * the client. - * - * @param request the HTTP request. - * @param response the HTTP response. - * @param context the HTTP execution context. - * @throws IOException in case of an I/O error. - * @throws HttpException in case of HTTP protocol violation or a processing - * problem. - */ - void handle(HttpRequest request, HttpResponse response, HttpContext context) - throws HttpException, IOException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpRequestHandlerMapper.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpRequestHandlerMapper.java deleted file mode 100644 index 5280262d..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpRequestHandlerMapper.java +++ /dev/null @@ -1,50 +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 com.tracelytics.ext.apache.http.protocol; - -import com.tracelytics.ext.apache.http.HttpRequest; - -/** - * HttpRequestHandlerMapper can be used to resolve an instance of - * {@link HttpRequestHandler} matching a particular {@link HttpRequest}. Usually the - * mapped request handler will be used to process the request. - * - * @since 4.3 - */ -public interface HttpRequestHandlerMapper { - - /** - * Looks up a handler matching the given request. - * - * @param request the request to map to a handler - * @return HTTP request handler or {@code null} if no match - * is found. - */ - HttpRequestHandler lookup(HttpRequest request); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpRequestHandlerRegistry.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpRequestHandlerRegistry.java deleted file mode 100644 index bf7c6acb..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpRequestHandlerRegistry.java +++ /dev/null @@ -1,107 +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 com.tracelytics.ext.apache.http.protocol; - -import java.util.Map; - -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Maintains a map of HTTP request handlers keyed by a request URI pattern. - *
- * Patterns may have three formats: - *

    - *
  • {@code *}
  • - *
  • {@code *<uri>}
  • - *
  • {@code <uri>*}
  • - *
- *
- * This class can be used to resolve an instance of - * {@link HttpRequestHandler} matching a particular request URI. Usually the - * resolved request handler will be used to process the request with the - * specified request URI. - * - * @since 4.0 - * @deprecated (4.3) use {@link UriHttpRequestHandlerMapper} - */ -@ThreadSafe // provided injected dependencies are thread-safe -@Deprecated -public class HttpRequestHandlerRegistry implements HttpRequestHandlerResolver { - - private final UriPatternMatcher matcher; - - public HttpRequestHandlerRegistry() { - matcher = new UriPatternMatcher(); - } - - /** - * Registers the given {@link HttpRequestHandler} as a handler for URIs - * matching the given pattern. - * - * @param pattern the pattern to register the handler for. - * @param handler the handler. - */ - public void register(final String pattern, final HttpRequestHandler handler) { - Args.notNull(pattern, "URI request pattern"); - Args.notNull(handler, "Request handler"); - matcher.register(pattern, handler); - } - - /** - * Removes registered handler, if exists, for the given pattern. - * - * @param pattern the pattern to unregister the handler for. - */ - public void unregister(final String pattern) { - matcher.unregister(pattern); - } - - /** - * Sets handlers from the given map. - * @param map the map containing handlers keyed by their URI patterns. - */ - public void setHandlers(final Map map) { - matcher.setObjects(map); - } - - /** - * Get the handler map. - * @return The map of handlers and their associated URI patterns. - * - * @since 4.2 - */ - public Map getHandlers() { - return matcher.getObjects(); - } - - public HttpRequestHandler lookup(final String requestURI) { - return matcher.lookup(requestURI); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpRequestHandlerResolver.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpRequestHandlerResolver.java deleted file mode 100644 index 96735b87..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpRequestHandlerResolver.java +++ /dev/null @@ -1,51 +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 com.tracelytics.ext.apache.http.protocol; - -/** - * HttpRequestHandlerResolver can be used to resolve an instance of - * {@link HttpRequestHandler} matching a particular request URI. Usually the - * mapped request handler will be used to process the request with the - * specified request URI. - * - * @since 4.0 - * @deprecated see {@link HttpRequestHandlerMapper} - */ -@Deprecated -public interface HttpRequestHandlerResolver { - - /** - * Looks up a handler matching the given request URI. - * - * @param requestURI the request URI - * @return HTTP request handler or {@code null} if no match - * is found. - */ - HttpRequestHandler lookup(String requestURI); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpRequestInterceptorList.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpRequestInterceptorList.java deleted file mode 100644 index 161fbed6..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpRequestInterceptorList.java +++ /dev/null @@ -1,103 +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 com.tracelytics.ext.apache.http.protocol; - -import java.util.List; - -import com.tracelytics.ext.apache.http.HttpRequestInterceptor; - -/** - * Provides access to an ordered list of request interceptors. - * Lists are expected to be built upfront and used read-only afterwards - * for {@link HttpProcessor processing}. - * - * @since 4.0 - * - * @deprecated (4.3) - */ -@Deprecated -public interface HttpRequestInterceptorList { - - /** - * Appends a request interceptor to this list. - * - * @param interceptor the request interceptor to add - */ - void addRequestInterceptor(HttpRequestInterceptor interceptor); - - /** - * Inserts a request interceptor at the specified index. - * - * @param interceptor the request interceptor to add - * @param index the index to insert the interceptor at - */ - void addRequestInterceptor(HttpRequestInterceptor interceptor, int index); - - /** - * Obtains the current size of this list. - * - * @return the number of request interceptors in this list - */ - int getRequestInterceptorCount(); - - /** - * Obtains a request interceptor from this list. - * - * @param index the index of the interceptor to obtain, - * 0 for first - * - * @return the interceptor at the given index, or - * {@code null} if the index is out of range - */ - HttpRequestInterceptor getRequestInterceptor(int index); - - /** - * Removes all request interceptors from this list. - */ - void clearRequestInterceptors(); - - /** - * Removes all request interceptor of the specified class - * - * @param clazz the class of the instances to be removed. - */ - void removeRequestInterceptorByClass(Class clazz); - - /** - * Sets the request interceptors in this list. - * This list will be cleared and re-initialized to contain - * all request interceptors from the argument list. - * If the argument list includes elements that are not request - * interceptors, the behavior is implementation dependent. - * - * @param list the list of request interceptors - */ - void setInterceptors(List list); - -} - diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpResponseInterceptorList.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpResponseInterceptorList.java deleted file mode 100644 index 44e3874e..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpResponseInterceptorList.java +++ /dev/null @@ -1,103 +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 com.tracelytics.ext.apache.http.protocol; - -import java.util.List; - -import com.tracelytics.ext.apache.http.HttpResponseInterceptor; - -/** - * Provides access to an ordered list of response interceptors. - * Lists are expected to be built upfront and used read-only afterwards - * for {@link HttpProcessor processing}. - * - * @since 4.0 - * - * @deprecated (4.3) - */ -@Deprecated -public interface HttpResponseInterceptorList { - - /** - * Appends a response interceptor to this list. - * - * @param interceptor the response interceptor to add - */ - void addResponseInterceptor(HttpResponseInterceptor interceptor); - - /** - * Inserts a response interceptor at the specified index. - * - * @param interceptor the response interceptor to add - * @param index the index to insert the interceptor at - */ - void addResponseInterceptor(HttpResponseInterceptor interceptor, int index); - - /** - * Obtains the current size of this list. - * - * @return the number of response interceptors in this list - */ - int getResponseInterceptorCount(); - - /** - * Obtains a response interceptor from this list. - * - * @param index the index of the interceptor to obtain, - * 0 for first - * - * @return the interceptor at the given index, or - * {@code null} if the index is out of range - */ - HttpResponseInterceptor getResponseInterceptor(int index); - - /** - * Removes all response interceptors from this list. - */ - void clearResponseInterceptors(); - - /** - * Removes all response interceptor of the specified class - * - * @param clazz the class of the instances to be removed. - */ - void removeResponseInterceptorByClass(Class clazz); - - /** - * Sets the response interceptors in this list. - * This list will be cleared and re-initialized to contain - * all response interceptors from the argument list. - * If the argument list includes elements that are not response - * interceptors, the behavior is implementation dependent. - * - * @param list the list of response interceptors - */ - void setInterceptors(List list); - -} - diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpService.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpService.java deleted file mode 100644 index 762b1d6a..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/HttpService.java +++ /dev/null @@ -1,461 +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 com.tracelytics.ext.apache.http.protocol; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.ConnectionReuseStrategy; -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpEntityEnclosingRequest; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.HttpResponseFactory; -import com.tracelytics.ext.apache.http.HttpServerConnection; -import com.tracelytics.ext.apache.http.HttpStatus; -import com.tracelytics.ext.apache.http.HttpVersion; -import com.tracelytics.ext.apache.http.MethodNotSupportedException; -import com.tracelytics.ext.apache.http.ProtocolException; -import com.tracelytics.ext.apache.http.UnsupportedHttpVersionException; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.entity.ByteArrayEntity; -import com.tracelytics.ext.apache.http.impl.DefaultConnectionReuseStrategy; -import com.tracelytics.ext.apache.http.impl.DefaultHttpResponseFactory; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.util.Args; -import com.tracelytics.ext.apache.http.util.EncodingUtils; -import com.tracelytics.ext.apache.http.util.EntityUtils; - -/** - * {@code HttpService} is a server side HTTP protocol handler based on - * the classic (blocking) I/O model. - *

- * {@code HttpService} relies on {@link HttpProcessor} to generate mandatory - * protocol headers for all outgoing messages and apply common, cross-cutting - * message transformations to all incoming and outgoing messages, whereas - * individual {@link HttpRequestHandler}s are expected to implement - * application specific content generation and processing. - *

- * {@code HttpService} uses {@link HttpRequestHandlerMapper} to map - * matching request handler for a particular request URI of an incoming HTTP - * request. - *

- * {@code HttpService} can use optional {@link HttpExpectationVerifier} - * to ensure that incoming requests meet server's expectations. - * - * @since 4.0 - */ -@SuppressWarnings("deprecation") -@Immutable // provided injected dependencies are immutable and deprecated methods are not used -public class HttpService { - - /** - * TODO: make all variables final in the next major version - */ - private volatile HttpParams params = null; - private volatile HttpProcessor processor = null; - private volatile HttpRequestHandlerMapper handlerMapper = null; - private volatile ConnectionReuseStrategy connStrategy = null; - private volatile HttpResponseFactory responseFactory = null; - private volatile HttpExpectationVerifier expectationVerifier = null; - - /** - * Create a new HTTP service. - * - * @param processor the processor to use on requests and responses - * @param connStrategy the connection reuse strategy - * @param responseFactory the response factory - * @param handlerResolver the handler resolver. May be null. - * @param expectationVerifier the expectation verifier. May be null. - * @param params the HTTP parameters - * - * @since 4.1 - * @deprecated (4.3) use {@link HttpService#HttpService(HttpProcessor, ConnectionReuseStrategy, - * HttpResponseFactory, HttpRequestHandlerMapper, HttpExpectationVerifier)} - */ - @Deprecated - public HttpService( - final HttpProcessor processor, - final ConnectionReuseStrategy connStrategy, - final HttpResponseFactory responseFactory, - final HttpRequestHandlerResolver handlerResolver, - final HttpExpectationVerifier expectationVerifier, - final HttpParams params) { - this(processor, - connStrategy, - responseFactory, - new HttpRequestHandlerResolverAdapter(handlerResolver), - expectationVerifier); - this.params = params; - } - - /** - * Create a new HTTP service. - * - * @param processor the processor to use on requests and responses - * @param connStrategy the connection reuse strategy - * @param responseFactory the response factory - * @param handlerResolver the handler resolver. May be null. - * @param params the HTTP parameters - * - * @since 4.1 - * @deprecated (4.3) use {@link HttpService#HttpService(HttpProcessor, ConnectionReuseStrategy, - * HttpResponseFactory, HttpRequestHandlerMapper)} - */ - @Deprecated - public HttpService( - final HttpProcessor processor, - final ConnectionReuseStrategy connStrategy, - final HttpResponseFactory responseFactory, - final HttpRequestHandlerResolver handlerResolver, - final HttpParams params) { - this(processor, - connStrategy, - responseFactory, - new HttpRequestHandlerResolverAdapter(handlerResolver), - null); - this.params = params; - } - - /** - * Create a new HTTP service. - * - * @param proc the processor to use on requests and responses - * @param connStrategy the connection reuse strategy - * @param responseFactory the response factory - * - * @deprecated (4.1) use {@link HttpService#HttpService(HttpProcessor, - * ConnectionReuseStrategy, HttpResponseFactory, HttpRequestHandlerResolver, HttpParams)} - */ - @Deprecated - public HttpService( - final HttpProcessor proc, - final ConnectionReuseStrategy connStrategy, - final HttpResponseFactory responseFactory) { - super(); - setHttpProcessor(proc); - setConnReuseStrategy(connStrategy); - setResponseFactory(responseFactory); - } - - /** - * Create a new HTTP service. - * - * @param processor the processor to use on requests and responses - * @param connStrategy the connection reuse strategy. If {@code null} - * {@link DefaultConnectionReuseStrategy#INSTANCE} will be used. - * @param responseFactory the response factory. If {@code null} - * {@link DefaultHttpResponseFactory#INSTANCE} will be used. - * @param handlerMapper the handler mapper. May be null. - * @param expectationVerifier the expectation verifier. May be null. - * - * @since 4.3 - */ - public HttpService( - final HttpProcessor processor, - final ConnectionReuseStrategy connStrategy, - final HttpResponseFactory responseFactory, - final HttpRequestHandlerMapper handlerMapper, - final HttpExpectationVerifier expectationVerifier) { - super(); - this.processor = Args.notNull(processor, "HTTP processor"); - this.connStrategy = connStrategy != null ? connStrategy : - DefaultConnectionReuseStrategy.INSTANCE; - this.responseFactory = responseFactory != null ? responseFactory : - DefaultHttpResponseFactory.INSTANCE; - this.handlerMapper = handlerMapper; - this.expectationVerifier = expectationVerifier; - } - - /** - * Create a new HTTP service. - * - * @param processor the processor to use on requests and responses - * @param connStrategy the connection reuse strategy. If {@code null} - * {@link DefaultConnectionReuseStrategy#INSTANCE} will be used. - * @param responseFactory the response factory. If {@code null} - * {@link DefaultHttpResponseFactory#INSTANCE} will be used. - * @param handlerMapper the handler mapper. May be null. - * - * @since 4.3 - */ - public HttpService( - final HttpProcessor processor, - final ConnectionReuseStrategy connStrategy, - final HttpResponseFactory responseFactory, - final HttpRequestHandlerMapper handlerMapper) { - this(processor, connStrategy, responseFactory, handlerMapper, null); - } - - /** - * Create a new HTTP service. - * - * @param processor the processor to use on requests and responses - * @param handlerMapper the handler mapper. May be null. - * - * @since 4.3 - */ - public HttpService( - final HttpProcessor processor, final HttpRequestHandlerMapper handlerMapper) { - this(processor, null, null, handlerMapper, null); - } - - /** - * @deprecated (4.1) set {@link HttpProcessor} using constructor - */ - @Deprecated - public void setHttpProcessor(final HttpProcessor processor) { - Args.notNull(processor, "HTTP processor"); - this.processor = processor; - } - - /** - * @deprecated (4.1) set {@link ConnectionReuseStrategy} using constructor - */ - @Deprecated - public void setConnReuseStrategy(final ConnectionReuseStrategy connStrategy) { - Args.notNull(connStrategy, "Connection reuse strategy"); - this.connStrategy = connStrategy; - } - - /** - * @deprecated (4.1) set {@link HttpResponseFactory} using constructor - */ - @Deprecated - public void setResponseFactory(final HttpResponseFactory responseFactory) { - Args.notNull(responseFactory, "Response factory"); - this.responseFactory = responseFactory; - } - - /** - * @deprecated (4.1) set {@link HttpResponseFactory} using constructor - */ - @Deprecated - public void setParams(final HttpParams params) { - this.params = params; - } - - /** - * @deprecated (4.1) set {@link HttpRequestHandlerResolver} using constructor - */ - @Deprecated - public void setHandlerResolver(final HttpRequestHandlerResolver handlerResolver) { - this.handlerMapper = new HttpRequestHandlerResolverAdapter(handlerResolver); - } - - /** - * @deprecated (4.1) set {@link HttpExpectationVerifier} using constructor - */ - @Deprecated - public void setExpectationVerifier(final HttpExpectationVerifier expectationVerifier) { - this.expectationVerifier = expectationVerifier; - } - - /** - * @deprecated (4.3) no longer used. - */ - @Deprecated - public HttpParams getParams() { - return this.params; - } - - /** - * Handles receives one HTTP request over the given connection within the - * given execution context and sends a response back to the client. - * - * @param conn the active connection to the client - * @param context the actual execution context. - * @throws IOException in case of an I/O error. - * @throws HttpException in case of HTTP protocol violation or a processing - * problem. - */ - public void handleRequest( - final HttpServerConnection conn, - final HttpContext context) throws IOException, HttpException { - - context.setAttribute(HttpCoreContext.HTTP_CONNECTION, conn); - - HttpRequest request = null; - HttpResponse response = null; - - try { - request = conn.receiveRequestHeader(); - if (request instanceof HttpEntityEnclosingRequest) { - - if (((HttpEntityEnclosingRequest) request).expectContinue()) { - response = this.responseFactory.newHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_CONTINUE, context); - if (this.expectationVerifier != null) { - try { - this.expectationVerifier.verify(request, response, context); - } catch (final HttpException ex) { - response = this.responseFactory.newHttpResponse(HttpVersion.HTTP_1_0, - HttpStatus.SC_INTERNAL_SERVER_ERROR, context); - handleException(ex, response); - } - } - if (response.getStatusLine().getStatusCode() < 200) { - // Send 1xx response indicating the server expections - // have been met - conn.sendResponseHeader(response); - conn.flush(); - response = null; - conn.receiveRequestEntity((HttpEntityEnclosingRequest) request); - } - } else { - conn.receiveRequestEntity((HttpEntityEnclosingRequest) request); - } - } - - context.setAttribute(HttpCoreContext.HTTP_REQUEST, request); - - if (response == null) { - response = this.responseFactory.newHttpResponse(HttpVersion.HTTP_1_1, - HttpStatus.SC_OK, context); - this.processor.process(request, context); - doService(request, response, context); - } - - // Make sure the request content is fully consumed - if (request instanceof HttpEntityEnclosingRequest) { - final HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity(); - EntityUtils.consume(entity); - } - - } catch (final HttpException ex) { - response = this.responseFactory.newHttpResponse - (HttpVersion.HTTP_1_0, HttpStatus.SC_INTERNAL_SERVER_ERROR, - context); - handleException(ex, response); - } - - context.setAttribute(HttpCoreContext.HTTP_RESPONSE, response); - - this.processor.process(response, context); - conn.sendResponseHeader(response); - if (canResponseHaveBody(request, response)) { - conn.sendResponseEntity(response); - } - conn.flush(); - - if (!this.connStrategy.keepAlive(response, context)) { - conn.close(); - } - } - - private boolean canResponseHaveBody(final HttpRequest request, final HttpResponse response) { - if (request != null && "HEAD".equalsIgnoreCase(request.getRequestLine().getMethod())) { - return false; - } - final int status = response.getStatusLine().getStatusCode(); - return status >= HttpStatus.SC_OK - && status != HttpStatus.SC_NO_CONTENT - && status != HttpStatus.SC_NOT_MODIFIED - && status != HttpStatus.SC_RESET_CONTENT; - } - - /** - * Handles the given exception and generates an HTTP response to be sent - * back to the client to inform about the exceptional condition encountered - * in the course of the request processing. - * - * @param ex the exception. - * @param response the HTTP response. - */ - protected void handleException(final HttpException ex, final HttpResponse response) { - if (ex instanceof MethodNotSupportedException) { - response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED); - } else if (ex instanceof UnsupportedHttpVersionException) { - response.setStatusCode(HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED); - } else if (ex instanceof ProtocolException) { - response.setStatusCode(HttpStatus.SC_BAD_REQUEST); - } else { - response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); - } - String message = ex.getMessage(); - if (message == null) { - message = ex.toString(); - } - final byte[] msg = EncodingUtils.getAsciiBytes(message); - final ByteArrayEntity entity = new ByteArrayEntity(msg); - entity.setContentType("text/plain; charset=US-ASCII"); - response.setEntity(entity); - } - - /** - * The default implementation of this method attempts to resolve an - * {@link HttpRequestHandler} for the request URI of the given request - * and, if found, executes its - * {@link HttpRequestHandler#handle(HttpRequest, HttpResponse, HttpContext)} - * method. - *

- * Super-classes can override this method in order to provide a custom - * implementation of the request processing logic. - * - * @param request the HTTP request. - * @param response the HTTP response. - * @param context the execution context. - * @throws IOException in case of an I/O error. - * @throws HttpException in case of HTTP protocol violation or a processing - * problem. - */ - protected void doService( - final HttpRequest request, - final HttpResponse response, - final HttpContext context) throws HttpException, IOException { - HttpRequestHandler handler = null; - if (this.handlerMapper != null) { - handler = this.handlerMapper.lookup(request); - } - if (handler != null) { - handler.handle(request, response, context); - } else { - response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED); - } - } - - /** - * Adaptor class to transition from HttpRequestHandlerResolver to HttpRequestHandlerMapper. - */ - @Deprecated - private static class HttpRequestHandlerResolverAdapter implements HttpRequestHandlerMapper { - - private final HttpRequestHandlerResolver resolver; - - public HttpRequestHandlerResolverAdapter(final HttpRequestHandlerResolver resolver) { - this.resolver = resolver; - } - - @Override - public HttpRequestHandler lookup(final HttpRequest request) { - return resolver.lookup(request.getRequestLine().getUri()); - } - - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/ImmutableHttpProcessor.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/ImmutableHttpProcessor.java deleted file mode 100644 index 34e5cd1f..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/ImmutableHttpProcessor.java +++ /dev/null @@ -1,145 +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 com.tracelytics.ext.apache.http.protocol; - -import java.io.IOException; -import java.util.List; - -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpRequestInterceptor; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.HttpResponseInterceptor; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; - -/** - * Immutable {@link HttpProcessor}. - * - * @since 4.1 - */ -@ThreadSafe // provided injected dependencies are immutable -public final class ImmutableHttpProcessor implements HttpProcessor { - - private final HttpRequestInterceptor[] requestInterceptors; - private final HttpResponseInterceptor[] responseInterceptors; - - public ImmutableHttpProcessor( - final HttpRequestInterceptor[] requestInterceptors, - final HttpResponseInterceptor[] responseInterceptors) { - super(); - if (requestInterceptors != null) { - final int l = requestInterceptors.length; - this.requestInterceptors = new HttpRequestInterceptor[l]; - System.arraycopy(requestInterceptors, 0, this.requestInterceptors, 0, l); - } else { - this.requestInterceptors = new HttpRequestInterceptor[0]; - } - if (responseInterceptors != null) { - final int l = responseInterceptors.length; - this.responseInterceptors = new HttpResponseInterceptor[l]; - System.arraycopy(responseInterceptors, 0, this.responseInterceptors, 0, l); - } else { - this.responseInterceptors = new HttpResponseInterceptor[0]; - } - } - - /** - * @since 4.3 - */ - public ImmutableHttpProcessor( - final List requestInterceptors, - final List responseInterceptors) { - super(); - if (requestInterceptors != null) { - final int l = requestInterceptors.size(); - this.requestInterceptors = requestInterceptors.toArray(new HttpRequestInterceptor[l]); - } else { - this.requestInterceptors = new HttpRequestInterceptor[0]; - } - if (responseInterceptors != null) { - final int l = responseInterceptors.size(); - this.responseInterceptors = responseInterceptors.toArray(new HttpResponseInterceptor[l]); - } else { - this.responseInterceptors = new HttpResponseInterceptor[0]; - } - } - - /** - * @deprecated (4.3) do not use. - */ - @Deprecated - public ImmutableHttpProcessor( - final HttpRequestInterceptorList requestInterceptors, - final HttpResponseInterceptorList responseInterceptors) { - super(); - if (requestInterceptors != null) { - final int count = requestInterceptors.getRequestInterceptorCount(); - this.requestInterceptors = new HttpRequestInterceptor[count]; - for (int i = 0; i < count; i++) { - this.requestInterceptors[i] = requestInterceptors.getRequestInterceptor(i); - } - } else { - this.requestInterceptors = new HttpRequestInterceptor[0]; - } - if (responseInterceptors != null) { - final int count = responseInterceptors.getResponseInterceptorCount(); - this.responseInterceptors = new HttpResponseInterceptor[count]; - for (int i = 0; i < count; i++) { - this.responseInterceptors[i] = responseInterceptors.getResponseInterceptor(i); - } - } else { - this.responseInterceptors = new HttpResponseInterceptor[0]; - } - } - - public ImmutableHttpProcessor(final HttpRequestInterceptor... requestInterceptors) { - this(requestInterceptors, null); - } - - public ImmutableHttpProcessor(final HttpResponseInterceptor... responseInterceptors) { - this(null, responseInterceptors); - } - - @Override - public void process( - final HttpRequest request, - final HttpContext context) throws IOException, HttpException { - for (final HttpRequestInterceptor requestInterceptor : this.requestInterceptors) { - requestInterceptor.process(request, context); - } - } - - @Override - public void process( - final HttpResponse response, - final HttpContext context) throws IOException, HttpException { - for (final HttpResponseInterceptor responseInterceptor : this.responseInterceptors) { - responseInterceptor.process(response, context); - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/RequestConnControl.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/RequestConnControl.java deleted file mode 100644 index 7f96a49d..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/RequestConnControl.java +++ /dev/null @@ -1,70 +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 com.tracelytics.ext.apache.http.protocol; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpRequestInterceptor; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * RequestConnControl is responsible for adding {@code Connection} header - * to the outgoing requests, which is essential for managing persistence of - * {@code HTTP/1.0} connections. This interceptor is recommended for - * client side protocol processors. - * - * @since 4.0 - */ -@Immutable -public class RequestConnControl implements HttpRequestInterceptor { - - public RequestConnControl() { - super(); - } - - @Override - public void process(final HttpRequest request, final HttpContext context) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - - final String method = request.getRequestLine().getMethod(); - if (method.equalsIgnoreCase("CONNECT")) { - return; - } - - if (!request.containsHeader(HTTP.CONN_DIRECTIVE)) { - // Default policy is to keep connection alive - // whenever possible - request.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE); - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/RequestContent.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/RequestContent.java deleted file mode 100644 index ba045c67..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/RequestContent.java +++ /dev/null @@ -1,128 +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 com.tracelytics.ext.apache.http.protocol; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpEntityEnclosingRequest; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpRequestInterceptor; -import com.tracelytics.ext.apache.http.HttpVersion; -import com.tracelytics.ext.apache.http.ProtocolException; -import com.tracelytics.ext.apache.http.ProtocolVersion; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * RequestContent is the most important interceptor for outgoing requests. - * It is responsible for delimiting content length by adding - * {@code Content-Length} or {@code Transfer-Content} headers based - * on the properties of the enclosed entity and the protocol version. - * This interceptor is required for correct functioning of client side protocol - * processors. - * - * @since 4.0 - */ -@Immutable -public class RequestContent implements HttpRequestInterceptor { - - private final boolean overwrite; - - /** - * Default constructor. The {@code Content-Length} or {@code Transfer-Encoding} - * will cause the interceptor to throw {@link ProtocolException} if already present in the - * response message. - */ - public RequestContent() { - this(false); - } - - /** - * Constructor that can be used to fine-tune behavior of this interceptor. - * - * @param overwrite If set to {@code true} the {@code Content-Length} and - * {@code Transfer-Encoding} headers will be created or updated if already present. - * If set to {@code false} the {@code Content-Length} and - * {@code Transfer-Encoding} headers will cause the interceptor to throw - * {@link ProtocolException} if already present in the response message. - * - * @since 4.2 - */ - public RequestContent(final boolean overwrite) { - super(); - this.overwrite = overwrite; - } - - @Override - public void process(final HttpRequest request, final HttpContext context) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - if (request instanceof HttpEntityEnclosingRequest) { - if (this.overwrite) { - request.removeHeaders(HTTP.TRANSFER_ENCODING); - request.removeHeaders(HTTP.CONTENT_LEN); - } else { - if (request.containsHeader(HTTP.TRANSFER_ENCODING)) { - throw new ProtocolException("Transfer-encoding header already present"); - } - if (request.containsHeader(HTTP.CONTENT_LEN)) { - throw new ProtocolException("Content-Length header already present"); - } - } - final ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); - final HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity(); - if (entity == null) { - request.addHeader(HTTP.CONTENT_LEN, "0"); - return; - } - // Must specify a transfer encoding or a content length - if (entity.isChunked() || entity.getContentLength() < 0) { - if (ver.lessEquals(HttpVersion.HTTP_1_0)) { - throw new ProtocolException( - "Chunked transfer encoding not allowed for " + ver); - } - request.addHeader(HTTP.TRANSFER_ENCODING, HTTP.CHUNK_CODING); - } else { - request.addHeader(HTTP.CONTENT_LEN, Long.toString(entity.getContentLength())); - } - // Specify a content type if known - if (entity.getContentType() != null && !request.containsHeader( - HTTP.CONTENT_TYPE )) { - request.addHeader(entity.getContentType()); - } - // Specify a content encoding if known - if (entity.getContentEncoding() != null && !request.containsHeader( - HTTP.CONTENT_ENCODING)) { - request.addHeader(entity.getContentEncoding()); - } - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/RequestDate.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/RequestDate.java deleted file mode 100644 index 8daaae40..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/RequestDate.java +++ /dev/null @@ -1,66 +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 com.tracelytics.ext.apache.http.protocol; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.HttpEntityEnclosingRequest; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpRequestInterceptor; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * RequestDate interceptor is responsible for adding {@code Date} header - * to the outgoing requests This interceptor is optional for client side - * protocol processors. - * - * @since 4.0 - */ -@ThreadSafe -public class RequestDate implements HttpRequestInterceptor { - - private static final HttpDateGenerator DATE_GENERATOR = new HttpDateGenerator(); - - public RequestDate() { - super(); - } - - @Override - public void process(final HttpRequest request, final HttpContext context) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - if ((request instanceof HttpEntityEnclosingRequest) && - !request.containsHeader(HTTP.DATE_HEADER)) { - final String httpdate = DATE_GENERATOR.getCurrentDate(); - request.setHeader(HTTP.DATE_HEADER, httpdate); - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/RequestExpectContinue.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/RequestExpectContinue.java deleted file mode 100644 index 6d20cbe1..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/RequestExpectContinue.java +++ /dev/null @@ -1,94 +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 com.tracelytics.ext.apache.http.protocol; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpEntityEnclosingRequest; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpRequestInterceptor; -import com.tracelytics.ext.apache.http.HttpVersion; -import com.tracelytics.ext.apache.http.ProtocolVersion; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.params.CoreProtocolPNames; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * RequestExpectContinue is responsible for enabling the 'expect-continue' - * handshake by adding {@code Expect} header. This interceptor is - * recommended for client side protocol processors. - * - * @since 4.0 - */ -@Immutable -@SuppressWarnings("deprecation") -public class RequestExpectContinue implements HttpRequestInterceptor { - - private final boolean activeByDefault; - - /** - * @deprecated (4.3) use {@link com.tracelytics.ext.apache.http.protocol.RequestExpectContinue#RequestExpectContinue(boolean)} - */ - @Deprecated - public RequestExpectContinue() { - this(false); - } - - /** - * @since 4.3 - */ - public RequestExpectContinue(final boolean activeByDefault) { - super(); - this.activeByDefault = activeByDefault; - } - - @Override - public void process(final HttpRequest request, final HttpContext context) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - - if (!request.containsHeader(HTTP.EXPECT_DIRECTIVE)) { - if (request instanceof HttpEntityEnclosingRequest) { - final ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); - final HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity(); - // 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)) { - final boolean active = request.getParams().getBooleanParameter( - CoreProtocolPNames.USE_EXPECT_CONTINUE, this.activeByDefault); - if (active) { - request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE); - } - } - } - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/RequestTargetHost.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/RequestTargetHost.java deleted file mode 100644 index 8ae089f6..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/RequestTargetHost.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 com.tracelytics.ext.apache.http.protocol; - -import java.io.IOException; -import java.net.InetAddress; - -import com.tracelytics.ext.apache.http.HttpConnection; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpHost; -import com.tracelytics.ext.apache.http.HttpInetConnection; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpRequestInterceptor; -import com.tracelytics.ext.apache.http.HttpVersion; -import com.tracelytics.ext.apache.http.ProtocolException; -import com.tracelytics.ext.apache.http.ProtocolVersion; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * RequestTargetHost is responsible for adding {@code Host} header. This - * interceptor is required for client side protocol processors. - * - * @since 4.0 - */ -@Immutable -public class RequestTargetHost implements HttpRequestInterceptor { - - public RequestTargetHost() { - super(); - } - - @Override - public void process(final HttpRequest request, final HttpContext context) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - - final HttpCoreContext corecontext = HttpCoreContext.adapt(context); - - final ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); - final String method = request.getRequestLine().getMethod(); - if (method.equalsIgnoreCase("CONNECT") && ver.lessEquals(HttpVersion.HTTP_1_0)) { - return; - } - - if (!request.containsHeader(HTTP.TARGET_HOST)) { - HttpHost targethost = corecontext.getTargetHost(); - if (targethost == null) { - final HttpConnection conn = corecontext.getConnection(); - if (conn instanceof HttpInetConnection) { - // Populate the context with a default HTTP host based on the - // inet address of the target host - final InetAddress address = ((HttpInetConnection) conn).getRemoteAddress(); - final int port = ((HttpInetConnection) conn).getRemotePort(); - if (address != null) { - targethost = new HttpHost(address.getHostName(), port); - } - } - if (targethost == null) { - if (ver.lessEquals(HttpVersion.HTTP_1_0)) { - return; - } else { - throw new ProtocolException("Target host missing"); - } - } - } - request.addHeader(HTTP.TARGET_HOST, targethost.toHostString()); - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/RequestUserAgent.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/RequestUserAgent.java deleted file mode 100644 index 9980e7ca..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/RequestUserAgent.java +++ /dev/null @@ -1,80 +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 com.tracelytics.ext.apache.http.protocol; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpRequestInterceptor; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.params.CoreProtocolPNames; -import com.tracelytics.ext.apache.http.params.HttpParams; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * RequestUserAgent is responsible for adding {@code User-Agent} header. - * This interceptor is recommended for client side protocol processors. - * - * @since 4.0 - */ -@SuppressWarnings("deprecation") -@Immutable -public class RequestUserAgent implements HttpRequestInterceptor { - - private final String userAgent; - - public RequestUserAgent(final String userAgent) { - super(); - this.userAgent = userAgent; - } - - public RequestUserAgent() { - this(null); - } - - @Override - public void process(final HttpRequest request, final HttpContext context) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - if (!request.containsHeader(HTTP.USER_AGENT)) { - String s = null; - final HttpParams params = request.getParams(); - if (params != null) { - s = (String) params.getParameter(CoreProtocolPNames.USER_AGENT); - } - if (s == null) { - s = this.userAgent; - } - if (s != null) { - request.addHeader(HTTP.USER_AGENT, s); - } - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/ResponseConnControl.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/ResponseConnControl.java deleted file mode 100644 index fce61277..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/ResponseConnControl.java +++ /dev/null @@ -1,106 +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 com.tracelytics.ext.apache.http.protocol; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.Header; -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.HttpResponseInterceptor; -import com.tracelytics.ext.apache.http.HttpStatus; -import com.tracelytics.ext.apache.http.HttpVersion; -import com.tracelytics.ext.apache.http.ProtocolVersion; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * ResponseConnControl is responsible for adding {@code Connection} header - * to the outgoing responses, which is essential for managing persistence of - * {@code HTTP/1.0} connections. This interceptor is recommended for - * server side protocol processors. - * - * @since 4.0 - */ -@Immutable -public class ResponseConnControl implements HttpResponseInterceptor { - - public ResponseConnControl() { - super(); - } - - @Override - public void process(final HttpResponse response, final HttpContext context) - throws HttpException, IOException { - Args.notNull(response, "HTTP response"); - - final HttpCoreContext corecontext = HttpCoreContext.adapt(context); - - // Always drop connection after certain type of responses - final int status = response.getStatusLine().getStatusCode(); - if (status == HttpStatus.SC_BAD_REQUEST || - status == HttpStatus.SC_REQUEST_TIMEOUT || - status == HttpStatus.SC_LENGTH_REQUIRED || - status == HttpStatus.SC_REQUEST_TOO_LONG || - status == HttpStatus.SC_REQUEST_URI_TOO_LONG || - status == HttpStatus.SC_SERVICE_UNAVAILABLE || - status == HttpStatus.SC_NOT_IMPLEMENTED) { - response.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE); - return; - } - final Header explicit = response.getFirstHeader(HTTP.CONN_DIRECTIVE); - if (explicit != null && HTTP.CONN_CLOSE.equalsIgnoreCase(explicit.getValue())) { - // Connection persistence explicitly disabled - return; - } - // Always drop connection for HTTP/1.0 responses and below - // if the content body cannot be correctly delimited - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final ProtocolVersion ver = response.getStatusLine().getProtocolVersion(); - if (entity.getContentLength() < 0 && - (!entity.isChunked() || ver.lessEquals(HttpVersion.HTTP_1_0))) { - response.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE); - return; - } - } - // Drop connection if requested by the client or request was <= 1.0 - final HttpRequest request = corecontext.getRequest(); - if (request != null) { - final Header header = request.getFirstHeader(HTTP.CONN_DIRECTIVE); - if (header != null) { - response.setHeader(HTTP.CONN_DIRECTIVE, header.getValue()); - } else if (request.getProtocolVersion().lessEquals(HttpVersion.HTTP_1_0)) { - response.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE); - } - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/ResponseContent.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/ResponseContent.java deleted file mode 100644 index aba46d88..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/ResponseContent.java +++ /dev/null @@ -1,134 +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 com.tracelytics.ext.apache.http.protocol; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.HttpResponseInterceptor; -import com.tracelytics.ext.apache.http.HttpStatus; -import com.tracelytics.ext.apache.http.HttpVersion; -import com.tracelytics.ext.apache.http.ProtocolException; -import com.tracelytics.ext.apache.http.ProtocolVersion; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * ResponseContent is the most important interceptor for outgoing responses. - * It is responsible for delimiting content length by adding - * {@code Content-Length} or {@code Transfer-Content} headers based - * on the properties of the enclosed entity and the protocol version. - * This interceptor is required for correct functioning of server side protocol - * processors. - * - * @since 4.0 - */ -@Immutable -public class ResponseContent implements HttpResponseInterceptor { - - private final boolean overwrite; - - /** - * Default constructor. The {@code Content-Length} or {@code Transfer-Encoding} - * will cause the interceptor to throw {@link ProtocolException} if already present in the - * response message. - */ - public ResponseContent() { - this(false); - } - - /** - * Constructor that can be used to fine-tune behavior of this interceptor. - * - * @param overwrite If set to {@code true} the {@code Content-Length} and - * {@code Transfer-Encoding} headers will be created or updated if already present. - * If set to {@code false} the {@code Content-Length} and - * {@code Transfer-Encoding} headers will cause the interceptor to throw - * {@link ProtocolException} if already present in the response message. - * - * @since 4.2 - */ - public ResponseContent(final boolean overwrite) { - super(); - this.overwrite = overwrite; - } - - /** - * Processes the response (possibly updating or inserting) Content-Length and Transfer-Encoding headers. - * @param response The HttpResponse to modify. - * @param context Unused. - * @throws ProtocolException If either the Content-Length or Transfer-Encoding headers are found. - * @throws IllegalArgumentException If the response is null. - */ - @Override - public void process(final HttpResponse response, final HttpContext context) - throws HttpException, IOException { - Args.notNull(response, "HTTP response"); - if (this.overwrite) { - response.removeHeaders(HTTP.TRANSFER_ENCODING); - response.removeHeaders(HTTP.CONTENT_LEN); - } else { - if (response.containsHeader(HTTP.TRANSFER_ENCODING)) { - throw new ProtocolException("Transfer-encoding header already present"); - } - if (response.containsHeader(HTTP.CONTENT_LEN)) { - throw new ProtocolException("Content-Length header already present"); - } - } - final ProtocolVersion ver = response.getStatusLine().getProtocolVersion(); - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final long len = entity.getContentLength(); - if (entity.isChunked() && !ver.lessEquals(HttpVersion.HTTP_1_0)) { - response.addHeader(HTTP.TRANSFER_ENCODING, HTTP.CHUNK_CODING); - } else if (len >= 0) { - response.addHeader(HTTP.CONTENT_LEN, Long.toString(entity.getContentLength())); - } - // Specify a content type if known - if (entity.getContentType() != null && !response.containsHeader( - HTTP.CONTENT_TYPE )) { - response.addHeader(entity.getContentType()); - } - // Specify a content encoding if known - if (entity.getContentEncoding() != null && !response.containsHeader( - HTTP.CONTENT_ENCODING)) { - response.addHeader(entity.getContentEncoding()); - } - } else { - final int status = response.getStatusLine().getStatusCode(); - if (status != HttpStatus.SC_NO_CONTENT - && status != HttpStatus.SC_NOT_MODIFIED - && status != HttpStatus.SC_RESET_CONTENT) { - response.addHeader(HTTP.CONTENT_LEN, "0"); - } - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/ResponseDate.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/ResponseDate.java deleted file mode 100644 index 518afcdf..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/ResponseDate.java +++ /dev/null @@ -1,67 +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 com.tracelytics.ext.apache.http.protocol; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.HttpResponseInterceptor; -import com.tracelytics.ext.apache.http.HttpStatus; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * ResponseDate is responsible for adding {@code Date} header to the - * outgoing responses. This interceptor is recommended for server side protocol - * processors. - * - * @since 4.0 - */ -@ThreadSafe -public class ResponseDate implements HttpResponseInterceptor { - - private static final HttpDateGenerator DATE_GENERATOR = new HttpDateGenerator(); - - public ResponseDate() { - super(); - } - - @Override - public void process(final HttpResponse response, final HttpContext context) - throws HttpException, IOException { - Args.notNull(response, "HTTP response"); - final int status = response.getStatusLine().getStatusCode(); - if ((status >= HttpStatus.SC_OK) && - !response.containsHeader(HTTP.DATE_HEADER)) { - final String httpdate = DATE_GENERATOR.getCurrentDate(); - response.setHeader(HTTP.DATE_HEADER, httpdate); - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/ResponseServer.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/ResponseServer.java deleted file mode 100644 index d4453660..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/ResponseServer.java +++ /dev/null @@ -1,72 +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 com.tracelytics.ext.apache.http.protocol; - -import java.io.IOException; - -import com.tracelytics.ext.apache.http.HttpException; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.HttpResponseInterceptor; -import com.tracelytics.ext.apache.http.annotation.Immutable; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * ResponseServer is responsible for adding {@code Server} header. This - * interceptor is recommended for server side protocol processors. - * - * @since 4.0 - */ -@Immutable -public class ResponseServer implements HttpResponseInterceptor { - - private final String originServer; - - /** - * @since 4.3 - */ - public ResponseServer(final String originServer) { - super(); - this.originServer = originServer; - } - - public ResponseServer() { - this(null); - } - - @Override - public void process(final HttpResponse response, final HttpContext context) - throws HttpException, IOException { - Args.notNull(response, "HTTP response"); - if (!response.containsHeader(HTTP.SERVER_HEADER)) { - if (this.originServer != null) { - response.addHeader(HTTP.SERVER_HEADER, this.originServer); - } - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/SyncBasicHttpContext.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/SyncBasicHttpContext.java deleted file mode 100644 index eba0b15a..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/SyncBasicHttpContext.java +++ /dev/null @@ -1,74 +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 com.tracelytics.ext.apache.http.protocol; - -/** - * Thread-safe extension of the {@link BasicHttpContext}. - * - * @since 4.0 - * - * @deprecated (4.2) HttpContext instances may not be shared by multiple threads - */ -@Deprecated -public class SyncBasicHttpContext extends BasicHttpContext { - - public SyncBasicHttpContext(final HttpContext parentContext) { - super(parentContext); - } - - /** - * @since 4.2 - */ - public SyncBasicHttpContext() { - super(); - } - - @Override - public synchronized Object getAttribute(final String id) { - return super.getAttribute(id); - } - - @Override - public synchronized void setAttribute(final String id, final Object obj) { - super.setAttribute(id, obj); - } - - @Override - public synchronized Object removeAttribute(final String id) { - return super.removeAttribute(id); - } - - /** - * @since 4.2 - */ - @Override - public synchronized void clear() { - super.clear(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/UriHttpRequestHandlerMapper.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/UriHttpRequestHandlerMapper.java deleted file mode 100644 index 42808cab..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/UriHttpRequestHandlerMapper.java +++ /dev/null @@ -1,116 +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 com.tracelytics.ext.apache.http.protocol; - -import com.tracelytics.ext.apache.http.HttpRequest; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Maintains a map of HTTP request handlers keyed by a request URI pattern. - *
- * Patterns may have three formats: - *

    - *
  • {@code *}
  • - *
  • {@code *<uri>}
  • - *
  • {@code <uri>*}
  • - *
- *
- * This class can be used to map an instance of - * {@link HttpRequestHandler} matching a particular request URI. Usually the - * mapped request handler will be used to process the request with the - * specified request URI. - * - * @since 4.3 - */ -@ThreadSafe // provided injected dependencies are thread-safe -public class UriHttpRequestHandlerMapper implements HttpRequestHandlerMapper { - - private final UriPatternMatcher matcher; - - protected UriHttpRequestHandlerMapper(final UriPatternMatcher matcher) { - super(); - this.matcher = Args.notNull(matcher, "Pattern matcher"); - } - - public UriHttpRequestHandlerMapper() { - this(new UriPatternMatcher()); - } - - /** - * Registers the given {@link HttpRequestHandler} as a handler for URIs - * matching the given pattern. - * - * @param pattern the pattern to register the handler for. - * @param handler the handler. - */ - public void register(final String pattern, final HttpRequestHandler handler) { - Args.notNull(pattern, "Pattern"); - Args.notNull(handler, "Handler"); - matcher.register(pattern, handler); - } - - /** - * Removes registered handler, if exists, for the given pattern. - * - * @param pattern the pattern to unregister the handler for. - */ - public void unregister(final String pattern) { - matcher.unregister(pattern); - } - - /** - * Extracts request path from the given {@link HttpRequest} - */ - protected String getRequestPath(final HttpRequest request) { - String uriPath = request.getRequestLine().getUri(); - int index = uriPath.indexOf("?"); - if (index != -1) { - uriPath = uriPath.substring(0, index); - } else { - index = uriPath.indexOf("#"); - if (index != -1) { - uriPath = uriPath.substring(0, index); - } - } - return uriPath; - } - - /** - * Looks up a handler matching the given request URI. - * - * @param request the request - * @return handler or {@code null} if no match is found. - */ - @Override - public HttpRequestHandler lookup(final HttpRequest request) { - Args.notNull(request, "HTTP request"); - return matcher.lookup(getRequestPath(request)); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/UriPatternMatcher.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/UriPatternMatcher.java deleted file mode 100644 index 32ce2418..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/UriPatternMatcher.java +++ /dev/null @@ -1,165 +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 com.tracelytics.ext.apache.http.protocol; - -import java.util.HashMap; -import java.util.Map; - -import com.tracelytics.ext.apache.http.annotation.GuardedBy; -import com.tracelytics.ext.apache.http.annotation.ThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Maintains a map of objects keyed by a request URI pattern. - *
- * Patterns may have three formats: - *
    - *
  • {@code *}
  • - *
  • {@code *<uri>}
  • - *
  • {@code <uri>*}
  • - *
- *
- * This class can be used to resolve an object matching a particular request - * URI. - * - * @since 4.0 - */ -@ThreadSafe -public class UriPatternMatcher { - - @GuardedBy("this") - private final Map map; - - public UriPatternMatcher() { - super(); - this.map = new HashMap(); - } - - /** - * Registers the given object for URIs matching the given pattern. - * - * @param pattern the pattern to register the handler for. - * @param obj the object. - */ - public synchronized void register(final String pattern, final T obj) { - Args.notNull(pattern, "URI request pattern"); - this.map.put(pattern, obj); - } - - /** - * Removes registered object, if exists, for the given pattern. - * - * @param pattern the pattern to unregister. - */ - public synchronized void unregister(final String pattern) { - if (pattern == null) { - return; - } - this.map.remove(pattern); - } - - /** - * @deprecated (4.1) do not use - */ - @Deprecated - public synchronized void setHandlers(final Map map) { - Args.notNull(map, "Map of handlers"); - this.map.clear(); - this.map.putAll(map); - } - - /** - * @deprecated (4.1) do not use - */ - @Deprecated - public synchronized void setObjects(final Map map) { - Args.notNull(map, "Map of handlers"); - this.map.clear(); - this.map.putAll(map); - } - - /** - * @deprecated (4.1) do not use - */ - @Deprecated - public synchronized Map getObjects() { - return this.map; - } - - /** - * Looks up an object matching the given request path. - * - * @param path the request path - * @return object or {@code null} if no match is found. - */ - public synchronized T lookup(final String path) { - Args.notNull(path, "Request path"); - // direct match? - T obj = this.map.get(path); - if (obj == null) { - // pattern match? - String bestMatch = null; - for (final String pattern : this.map.keySet()) { - if (matchUriRequestPattern(pattern, path)) { - // we have a match. is it any better? - if (bestMatch == null - || (bestMatch.length() < pattern.length()) - || (bestMatch.length() == pattern.length() && pattern.endsWith("*"))) { - obj = this.map.get(pattern); - bestMatch = pattern; - } - } - } - } - return obj; - } - - /** - * Tests if the given request path matches the given pattern. - * - * @param pattern the pattern - * @param path the request path - * @return {@code true} if the request URI matches the pattern, - * {@code false} otherwise. - */ - protected boolean matchUriRequestPattern(final String pattern, final String path) { - if (pattern.equals("*")) { - return true; - } else { - return - (pattern.endsWith("*") && path.startsWith(pattern.substring(0, pattern.length() - 1))) || - (pattern.startsWith("*") && path.endsWith(pattern.substring(1, pattern.length()))); - } - } - - @Override - public String toString() { - return this.map.toString(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/package-info.java deleted file mode 100644 index f9b2a902..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/protocol/package-info.java +++ /dev/null @@ -1,32 +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 - * . - * - */ - -/** - * Core HTTP protocol execution framework and HTTP protocol handlers - * for synchronous, blocking communication. - */ -package com.tracelytics.ext.apache.http.protocol; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ssl/PrivateKeyDetails.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/ssl/PrivateKeyDetails.java deleted file mode 100644 index 594761d9..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ssl/PrivateKeyDetails.java +++ /dev/null @@ -1,63 +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 com.tracelytics.ext.apache.http.ssl; - -import com.tracelytics.ext.apache.http.util.Args; - -import java.security.cert.X509Certificate; -import java.util.Arrays; - -/** - * Private key details. - * - * @since 4.4 - */ -public final class PrivateKeyDetails { - - private final String type; - private final X509Certificate[] certChain; - - public PrivateKeyDetails(final String type, final X509Certificate[] certChain) { - super(); - this.type = Args.notNull(type, "Private key type"); - this.certChain = certChain; - } - - public String getType() { - return type; - } - - public X509Certificate[] getCertChain() { - return certChain; - } - - @Override - public String toString() { - return type + ':' + Arrays.toString(certChain); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ssl/PrivateKeyStrategy.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/ssl/PrivateKeyStrategy.java deleted file mode 100644 index a481449a..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ssl/PrivateKeyStrategy.java +++ /dev/null @@ -1,48 +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 com.tracelytics.ext.apache.http.ssl; - -import java.net.Socket; -import java.util.Map; - -/** - * A strategy allowing for a choice of an alias during SSL authentication. - * - * @since 4.4 - */ -public interface PrivateKeyStrategy { - - /** - * Determines what key material to use for SSL authentication. - * - * @param aliases available private key material - * @param socket socket used for the connection. Please note this parameter can be {@code null} - * if key material is applicable to any socket. - */ - String chooseAlias(Map aliases, Socket socket); - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ssl/SSLContextBuilder.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/ssl/SSLContextBuilder.java deleted file mode 100644 index cf0c4d24..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ssl/SSLContextBuilder.java +++ /dev/null @@ -1,400 +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 com.tracelytics.ext.apache.http.ssl; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.Socket; -import java.net.URL; -import java.security.KeyManagementException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.Principal; -import java.security.PrivateKey; -import java.security.SecureRandom; -import java.security.UnrecoverableKeyException; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; - -import javax.net.ssl.KeyManager; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLEngine; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.X509ExtendedKeyManager; -import javax.net.ssl.X509TrustManager; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.util.Args; - -/** - * Builder for {@link javax.net.ssl.SSLContext} instances. - *

- * Please note: the default Oracle JSSE implementation of {@link SSLContext#init(KeyManager[], TrustManager[], SecureRandom)} - * accepts multiple key and trust managers, however only only first matching type is ever used. - * See for example: - * - * SSLContext.html#init - * - * - * @since 4.4 - */ -@NotThreadSafe -public class SSLContextBuilder { - - static final String TLS = "TLS"; - - private String protocol; - private final Set keymanagers; - private final Set trustmanagers; - private SecureRandom secureRandom; - - public static SSLContextBuilder create() { - return new SSLContextBuilder(); - } - - public SSLContextBuilder() { - super(); - this.keymanagers = new LinkedHashSet(); - this.trustmanagers = new LinkedHashSet(); - } - - public SSLContextBuilder useProtocol(final String protocol) { - this.protocol = protocol; - return this; - } - - public SSLContextBuilder setSecureRandom(final SecureRandom secureRandom) { - this.secureRandom = secureRandom; - return this; - } - - public SSLContextBuilder loadTrustMaterial( - final KeyStore truststore, - final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException { - final TrustManagerFactory tmfactory = TrustManagerFactory.getInstance( - TrustManagerFactory.getDefaultAlgorithm()); - tmfactory.init(truststore); - final TrustManager[] tms = tmfactory.getTrustManagers(); - if (tms != null) { - if (trustStrategy != null) { - for (int i = 0; i < tms.length; i++) { - final TrustManager tm = tms[i]; - if (tm instanceof X509TrustManager) { - tms[i] = new TrustManagerDelegate( - (X509TrustManager) tm, trustStrategy); - } - } - } - for (final TrustManager tm : tms) { - this.trustmanagers.add(tm); - } - } - return this; - } - - public SSLContextBuilder loadTrustMaterial( - final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException { - return loadTrustMaterial(null, trustStrategy); - } - - public SSLContextBuilder loadTrustMaterial( - final File file, - final char[] storePassword, - final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException { - Args.notNull(file, "Truststore file"); - final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); - final FileInputStream instream = new FileInputStream(file); - try { - trustStore.load(instream, storePassword); - } finally { - instream.close(); - } - return loadTrustMaterial(trustStore, trustStrategy); - } - - public SSLContextBuilder loadTrustMaterial( - final File file, - final char[] storePassword) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException { - return loadTrustMaterial(file, storePassword, null); - } - - public SSLContextBuilder loadTrustMaterial( - final File file) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException { - return loadTrustMaterial(file, null); - } - - public SSLContextBuilder loadTrustMaterial( - final URL url, - final char[] storePassword, - final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException { - Args.notNull(url, "Truststore URL"); - final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); - final InputStream instream = url.openStream(); - try { - trustStore.load(instream, storePassword); - } finally { - instream.close(); - } - return loadTrustMaterial(trustStore, trustStrategy); - } - - public SSLContextBuilder loadTrustMaterial( - final URL url, - final char[] storePassword) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException { - return loadTrustMaterial(url, storePassword, null); - } - - public SSLContextBuilder loadKeyMaterial( - final KeyStore keystore, - final char[] keyPassword, - final PrivateKeyStrategy aliasStrategy) - throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException { - final KeyManagerFactory kmfactory = KeyManagerFactory.getInstance( - KeyManagerFactory.getDefaultAlgorithm()); - kmfactory.init(keystore, keyPassword); - final KeyManager[] kms = kmfactory.getKeyManagers(); - if (kms != null) { - if (aliasStrategy != null) { - for (int i = 0; i < kms.length; i++) { - final KeyManager km = kms[i]; - if (km instanceof X509ExtendedKeyManager) { - kms[i] = new KeyManagerDelegate((X509ExtendedKeyManager) km, aliasStrategy); - } - } - } - for (final KeyManager km : kms) { - keymanagers.add(km); - } - } - return this; - } - - public SSLContextBuilder loadKeyMaterial( - final KeyStore keystore, - final char[] keyPassword) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException { - return loadKeyMaterial(keystore, keyPassword, null); - } - - public SSLContextBuilder loadKeyMaterial( - final File file, - final char[] storePassword, - final char[] keyPassword, - final PrivateKeyStrategy aliasStrategy) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, CertificateException, IOException { - Args.notNull(file, "Keystore file"); - final KeyStore identityStore = KeyStore.getInstance(KeyStore.getDefaultType()); - final FileInputStream instream = new FileInputStream(file); - try { - identityStore.load(instream, storePassword); - } finally { - instream.close(); - } - return loadKeyMaterial(identityStore, keyPassword, aliasStrategy); - } - - public SSLContextBuilder loadKeyMaterial( - final File file, - final char[] storePassword, - final char[] keyPassword) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, CertificateException, IOException { - return loadKeyMaterial(file, storePassword, keyPassword, null); - } - - public SSLContextBuilder loadKeyMaterial( - final URL url, - final char[] storePassword, - final char[] keyPassword, - final PrivateKeyStrategy aliasStrategy) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, CertificateException, IOException { - Args.notNull(url, "Keystore URL"); - final KeyStore identityStore = KeyStore.getInstance(KeyStore.getDefaultType()); - final InputStream instream = url.openStream(); - try { - identityStore.load(instream, storePassword); - } finally { - instream.close(); - } - return loadKeyMaterial(identityStore, keyPassword, aliasStrategy); - } - - public SSLContextBuilder loadKeyMaterial( - final URL url, - final char[] storePassword, - final char[] keyPassword) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, CertificateException, IOException { - return loadKeyMaterial(url, storePassword, keyPassword, null); - } - - protected void initSSLContext( - final SSLContext sslcontext, - final Collection keyManagers, - final Collection trustManagers, - final SecureRandom secureRandom) throws KeyManagementException { - sslcontext.init( - !keyManagers.isEmpty() ? keyManagers.toArray(new KeyManager[keyManagers.size()]) : null, - !trustManagers.isEmpty() ? trustManagers.toArray(new TrustManager[trustManagers.size()]) : null, - secureRandom); - } - - public SSLContext build() throws NoSuchAlgorithmException, KeyManagementException { - final SSLContext sslcontext = SSLContext.getInstance( - this.protocol != null ? this.protocol : TLS); - initSSLContext(sslcontext, keymanagers, trustmanagers, secureRandom); - return sslcontext; - } - - static class TrustManagerDelegate implements X509TrustManager { - - private final X509TrustManager trustManager; - private final TrustStrategy trustStrategy; - - TrustManagerDelegate(final X509TrustManager trustManager, final TrustStrategy trustStrategy) { - super(); - this.trustManager = trustManager; - this.trustStrategy = trustStrategy; - } - - @Override - public void checkClientTrusted( - final X509Certificate[] chain, final String authType) throws CertificateException { - this.trustManager.checkClientTrusted(chain, authType); - } - - @Override - public void checkServerTrusted( - final X509Certificate[] chain, final String authType) throws CertificateException { - if (!this.trustStrategy.isTrusted(chain, authType)) { - this.trustManager.checkServerTrusted(chain, authType); - } - } - - @Override - public X509Certificate[] getAcceptedIssuers() { - return this.trustManager.getAcceptedIssuers(); - } - - } - - static class KeyManagerDelegate extends X509ExtendedKeyManager { - - private final X509ExtendedKeyManager keyManager; - private final PrivateKeyStrategy aliasStrategy; - - KeyManagerDelegate(final X509ExtendedKeyManager keyManager, final PrivateKeyStrategy aliasStrategy) { - super(); - this.keyManager = keyManager; - this.aliasStrategy = aliasStrategy; - } - - @Override - public String[] getClientAliases( - final String keyType, final Principal[] issuers) { - return this.keyManager.getClientAliases(keyType, issuers); - } - - public Map getClientAliasMap( - final String[] keyTypes, final Principal[] issuers) { - final Map validAliases = new HashMap(); - for (final String keyType: keyTypes) { - final String[] aliases = this.keyManager.getClientAliases(keyType, issuers); - if (aliases != null) { - for (final String alias: aliases) { - validAliases.put(alias, - new PrivateKeyDetails(keyType, this.keyManager.getCertificateChain(alias))); - } - } - } - return validAliases; - } - - public Map getServerAliasMap( - final String keyType, final Principal[] issuers) { - final Map validAliases = new HashMap(); - final String[] aliases = this.keyManager.getServerAliases(keyType, issuers); - if (aliases != null) { - for (final String alias: aliases) { - validAliases.put(alias, - new PrivateKeyDetails(keyType, this.keyManager.getCertificateChain(alias))); - } - } - return validAliases; - } - - @Override - public String chooseClientAlias( - final String[] keyTypes, final Principal[] issuers, final Socket socket) { - final Map validAliases = getClientAliasMap(keyTypes, issuers); - return this.aliasStrategy.chooseAlias(validAliases, socket); - } - - @Override - public String[] getServerAliases( - final String keyType, final Principal[] issuers) { - return this.keyManager.getServerAliases(keyType, issuers); - } - - @Override - public String chooseServerAlias( - final String keyType, final Principal[] issuers, final Socket socket) { - final Map validAliases = getServerAliasMap(keyType, issuers); - return this.aliasStrategy.chooseAlias(validAliases, socket); - } - - @Override - public X509Certificate[] getCertificateChain(final String alias) { - return this.keyManager.getCertificateChain(alias); - } - - @Override - public PrivateKey getPrivateKey(final String alias) { - return this.keyManager.getPrivateKey(alias); - } - - @Override - public String chooseEngineClientAlias( - final String[] keyTypes, final Principal[] issuers, final SSLEngine sslEngine) { - final Map validAliases = getClientAliasMap(keyTypes, issuers); - return this.aliasStrategy.chooseAlias(validAliases, null); - } - - @Override - public String chooseEngineServerAlias( - final String keyType, final Principal[] issuers, final SSLEngine sslEngine) { - final Map validAliases = getServerAliasMap(keyType, issuers); - return this.aliasStrategy.chooseAlias(validAliases, null); - } - - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ssl/SSLContexts.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/ssl/SSLContexts.java deleted file mode 100644 index c7aecd2b..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ssl/SSLContexts.java +++ /dev/null @@ -1,90 +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 com.tracelytics.ext.apache.http.ssl; - -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; - -import javax.net.ssl.SSLContext; - -import com.tracelytics.ext.apache.http.annotation.Immutable; - -/** - * {@link javax.net.ssl.SSLContext} factory methods. - * - * @since 4.4 - */ -@Immutable -public class SSLContexts { - - /** - * Creates default factory based on the standard JSSE trust material - * ({@code cacerts} file in the security properties directory). System properties - * are not taken into consideration. - * - * @return the default SSL socket factory - */ - public static SSLContext createDefault() throws SSLInitializationException { - try { - final SSLContext sslcontext = SSLContext.getInstance(SSLContextBuilder.TLS); - sslcontext.init(null, null, null); - return sslcontext; - } catch (final NoSuchAlgorithmException ex) { - throw new SSLInitializationException(ex.getMessage(), ex); - } catch (final KeyManagementException ex) { - throw new SSLInitializationException(ex.getMessage(), ex); - } - } - - /** - * Creates default SSL context based on system properties. This method obtains - * default SSL context by calling {@code SSLContext.getInstance("Default")}. - * Please note that {@code Default} algorithm is supported as of Java 6. - * This method will fall back onto {@link #createDefault()} when - * {@code Default} algorithm is not available. - * - * @return default system SSL context - */ - public static SSLContext createSystemDefault() throws SSLInitializationException { - try { - return SSLContext.getDefault(); - } catch (final NoSuchAlgorithmException ex) { - return createDefault(); - } - } - - /** - * Creates custom SSL context. - * - * @return default system SSL context - */ - public static SSLContextBuilder custom() { - return SSLContextBuilder.create(); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ssl/SSLInitializationException.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/ssl/SSLInitializationException.java deleted file mode 100644 index 5d897def..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ssl/SSLInitializationException.java +++ /dev/null @@ -1,37 +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 com.tracelytics.ext.apache.http.ssl; - -public class SSLInitializationException extends IllegalStateException { - - private static final long serialVersionUID = -8243587425648536702L; - - public SSLInitializationException(final String message, final Throwable cause) { - super(message, cause); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ssl/TrustStrategy.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/ssl/TrustStrategy.java deleted file mode 100644 index 0e94eab6..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ssl/TrustStrategy.java +++ /dev/null @@ -1,57 +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 com.tracelytics.ext.apache.http.ssl; - -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - -/** - * A strategy to establish trustworthiness of certificates without consulting the trust manager - * configured in the actual SSL context. This interface can be used to override the standard - * JSSE certificate verification process. - * - * @since 4.4 - */ -public interface TrustStrategy { - - /** - * Determines whether the certificate chain can be trusted without consulting the trust manager - * configured in the actual SSL context. This method can be used to override the standard JSSE - * certificate verification process. - *

- * Please note that, if this method returns {@code false}, the trust manager configured - * in the actual SSL context can still clear the certificate as trusted. - * - * @param chain the peer certificate chain - * @param authType the authentication type based on the client certificate - * @return {@code true} if the certificate can be trusted without verification by - * the trust manager, {@code false} otherwise. - * @throws CertificateException thrown if the certificate is not trusted or invalid. - */ - boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException; - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ssl/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/ssl/package-info.java deleted file mode 100644 index 4b7883fb..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/ssl/package-info.java +++ /dev/null @@ -1,32 +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 - * . - * - */ - -/** - * Utility classes for trust and key material management - * and TLS/SSL context initialization. - */ -package com.tracelytics.ext.apache.http.ssl; diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/Args.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/Args.java deleted file mode 100644 index 1b428046..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/Args.java +++ /dev/null @@ -1,127 +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 com.tracelytics.ext.apache.http.util; - -import java.util.Collection; - -public class Args { - - public static void check(final boolean expression, final String message) { - if (!expression) { - throw new IllegalArgumentException(message); - } - } - - public static void check(final boolean expression, final String message, final Object... args) { - if (!expression) { - throw new IllegalArgumentException(String.format(message, args)); - } - } - - public static void check(final boolean expression, final String message, final Object arg) { - if (!expression) { - throw new IllegalArgumentException(String.format(message, arg)); - } - } - - public static T notNull(final T argument, final String name) { - if (argument == null) { - throw new IllegalArgumentException(name + " may not be null"); - } - return argument; - } - - public static T notEmpty(final T argument, final String name) { - if (argument == null) { - throw new IllegalArgumentException(name + " may not be null"); - } - if (TextUtils.isEmpty(argument)) { - throw new IllegalArgumentException(name + " may not be empty"); - } - return argument; - } - - public static T notBlank(final T argument, final String name) { - if (argument == null) { - throw new IllegalArgumentException(name + " may not be null"); - } - if (TextUtils.isBlank(argument)) { - throw new IllegalArgumentException(name + " may not be blank"); - } - return argument; - } - - public static T containsNoBlanks(final T argument, final String name) { - if (argument == null) { - throw new IllegalArgumentException(name + " may not be null"); - } - if (TextUtils.containsBlanks(argument)) { - throw new IllegalArgumentException(name + " may not contain blanks"); - } - return argument; - } - - public static > T notEmpty(final T argument, final String name) { - if (argument == null) { - throw new IllegalArgumentException(name + " may not be null"); - } - if (argument.isEmpty()) { - throw new IllegalArgumentException(name + " may not be empty"); - } - return argument; - } - - public static int positive(final int n, final String name) { - if (n <= 0) { - throw new IllegalArgumentException(name + " may not be negative or zero"); - } - return n; - } - - public static long positive(final long n, final String name) { - if (n <= 0) { - throw new IllegalArgumentException(name + " may not be negative or zero"); - } - return n; - } - - public static int notNegative(final int n, final String name) { - if (n < 0) { - throw new IllegalArgumentException(name + " may not be negative"); - } - return n; - } - - public static long notNegative(final long n, final String name) { - if (n < 0) { - throw new IllegalArgumentException(name + " may not be negative"); - } - return n; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/Asserts.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/Asserts.java deleted file mode 100644 index ed75f601..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/Asserts.java +++ /dev/null @@ -1,68 +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 com.tracelytics.ext.apache.http.util; - -public class Asserts { - - public static void check(final boolean expression, final String message) { - if (!expression) { - throw new IllegalStateException(message); - } - } - - public static void check(final boolean expression, final String message, final Object... args) { - if (!expression) { - throw new IllegalStateException(String.format(message, args)); - } - } - - public static void check(final boolean expression, final String message, final Object arg) { - if (!expression) { - throw new IllegalStateException(String.format(message, arg)); - } - } - - public static void notNull(final Object object, final String name) { - if (object == null) { - throw new IllegalStateException(name + " is null"); - } - } - - public static void notEmpty(final CharSequence s, final String name) { - if (TextUtils.isEmpty(s)) { - throw new IllegalStateException(name + " is empty"); - } - } - - public static void notBlank(final CharSequence s, final String name) { - if (TextUtils.isBlank(s)) { - throw new IllegalStateException(name + " is blank"); - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/ByteArrayBuffer.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/ByteArrayBuffer.java deleted file mode 100644 index 76651d13..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/ByteArrayBuffer.java +++ /dev/null @@ -1,347 +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 com.tracelytics.ext.apache.http.util; - -import java.io.Serializable; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; - -/** - * A resizable byte array. - * - * @since 4.0 - */ -@NotThreadSafe -public final class ByteArrayBuffer implements Serializable { - - private static final long serialVersionUID = 4359112959524048036L; - - private byte[] buffer; - private int len; - - /** - * Creates an instance of {@link ByteArrayBuffer} with the given initial - * capacity. - * - * @param capacity the capacity - */ - public ByteArrayBuffer(final int capacity) { - super(); - Args.notNegative(capacity, "Buffer capacity"); - this.buffer = new byte[capacity]; - } - - private void expand(final int newlen) { - final byte newbuffer[] = new byte[Math.max(this.buffer.length << 1, newlen)]; - System.arraycopy(this.buffer, 0, newbuffer, 0, this.len); - this.buffer = newbuffer; - } - - /** - * Appends {@code len} bytes to this buffer from the given source - * array starting at index {@code off}. The capacity of the buffer - * is increased, if necessary, to accommodate all {@code len} bytes. - * - * @param b the bytes to be appended. - * @param off the index of the first byte to append. - * @param len the number of bytes to append. - * @throws IndexOutOfBoundsException if {@code off} if out of - * range, {@code len} is negative, or - * {@code off} + {@code len} is out of range. - */ - public void append(final byte[] b, final int off, final int len) { - if (b == null) { - return; - } - 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); - } - if (len == 0) { - return; - } - final int newlen = this.len + len; - if (newlen > this.buffer.length) { - expand(newlen); - } - System.arraycopy(b, off, this.buffer, this.len, len); - this.len = newlen; - } - - /** - * Appends {@code b} byte to this buffer. The capacity of the buffer - * is increased, if necessary, to accommodate the additional byte. - * - * @param b the byte to be appended. - */ - public void append(final int b) { - final int newlen = this.len + 1; - if (newlen > this.buffer.length) { - expand(newlen); - } - this.buffer[this.len] = (byte)b; - this.len = newlen; - } - - /** - * Appends {@code len} chars to this buffer from the given source - * array starting at index {@code off}. The capacity of the buffer - * is increased if necessary to accommodate all {@code len} chars. - *

- * The chars are converted to bytes using simple cast. - * - * @param b the chars to be appended. - * @param off the index of the first char to append. - * @param len the number of bytes to append. - * @throws IndexOutOfBoundsException if {@code off} if out of - * range, {@code len} is negative, or - * {@code off} + {@code len} is out of range. - */ - public void append(final char[] b, final int off, final int len) { - if (b == null) { - return; - } - 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); - } - if (len == 0) { - return; - } - final int oldlen = this.len; - final int newlen = oldlen + len; - if (newlen > this.buffer.length) { - expand(newlen); - } - for (int i1 = off, i2 = oldlen; i2 < newlen; i1++, i2++) { - this.buffer[i2] = (byte) b[i1]; - } - this.len = newlen; - } - - /** - * Appends {@code len} chars to this buffer from the given source - * char array buffer starting at index {@code off}. The capacity - * of the buffer is increased if necessary to accommodate all - * {@code len} chars. - *

- * The chars are converted to bytes using simple cast. - * - * @param b the chars to be appended. - * @param off the index of the first char to append. - * @param len the number of bytes to append. - * @throws IndexOutOfBoundsException if {@code off} if out of - * range, {@code len} is negative, or - * {@code off} + {@code len} is out of range. - */ - public void append(final CharArrayBuffer b, final int off, final int len) { - if (b == null) { - return; - } - append(b.buffer(), off, len); - } - - /** - * Clears content of the buffer. The underlying byte array is not resized. - */ - public void clear() { - this.len = 0; - } - - /** - * Converts the content of this buffer to an array of bytes. - * - * @return byte array - */ - public byte[] toByteArray() { - final byte[] b = new byte[this.len]; - if (this.len > 0) { - System.arraycopy(this.buffer, 0, b, 0, this.len); - } - return b; - } - - /** - * Returns the {@code byte} value in this buffer at the specified - * index. The index argument must be greater than or equal to - * {@code 0}, and less than the length of this buffer. - * - * @param i the index of the desired byte value. - * @return the byte value at the specified index. - * @throws IndexOutOfBoundsException if {@code index} is - * negative or greater than or equal to {@link #length()}. - */ - public int byteAt(final int i) { - return this.buffer[i]; - } - - /** - * Returns the current capacity. The capacity is the amount of storage - * available for newly appended bytes, beyond which an allocation - * will occur. - * - * @return the current capacity - */ - public int capacity() { - return this.buffer.length; - } - - /** - * Returns the length of the buffer (byte count). - * - * @return the length of the buffer - */ - public int length() { - return this.len; - } - - /** - * Ensures that the capacity is at least equal to the specified minimum. - * If the current capacity is less than the argument, then a new internal - * array is allocated with greater capacity. If the {@code required} - * argument is non-positive, this method takes no action. - * - * @param required the minimum required capacity. - * - * @since 4.1 - */ - public void ensureCapacity(final int required) { - if (required <= 0) { - return; - } - final int available = this.buffer.length - this.len; - if (required > available) { - expand(this.len + required); - } - } - - /** - * Returns reference to the underlying byte array. - * - * @return the byte array. - */ - public byte[] buffer() { - return this.buffer; - } - - /** - * Sets the length of the buffer. The new length value is expected to be - * less than the current capacity and greater than or equal to - * {@code 0}. - * - * @param len the new length - * @throws IndexOutOfBoundsException if the - * {@code len} argument is greater than the current - * capacity of the buffer or less than {@code 0}. - */ - public void setLength(final int len) { - if (len < 0 || len > this.buffer.length) { - throw new IndexOutOfBoundsException("len: "+len+" < 0 or > buffer len: "+this.buffer.length); - } - this.len = len; - } - - /** - * Returns {@code true} if this buffer is empty, that is, its - * {@link #length()} is equal to {@code 0}. - * @return {@code true} if this buffer is empty, {@code false} - * otherwise. - */ - public boolean isEmpty() { - return this.len == 0; - } - - /** - * Returns {@code true} if this buffer is full, that is, its - * {@link #length()} is equal to its {@link #capacity()}. - * @return {@code true} if this buffer is full, {@code false} - * otherwise. - */ - public boolean isFull() { - return this.len == this.buffer.length; - } - - /** - * Returns the index within this buffer of the first occurrence of the - * specified byte, starting the search at the specified - * {@code beginIndex} and finishing at {@code endIndex}. - * If no such byte occurs in this buffer within the specified bounds, - * {@code -1} is returned. - *

- * There is no restriction on the value of {@code beginIndex} and - * {@code endIndex}. If {@code beginIndex} is negative, - * it has the same effect as if it were zero. If {@code endIndex} is - * greater than {@link #length()}, it has the same effect as if it were - * {@link #length()}. If the {@code beginIndex} is greater than - * the {@code endIndex}, {@code -1} is returned. - * - * @param b the byte to search for. - * @param from the index to start the search from. - * @param to the index to finish the search at. - * @return the index of the first occurrence of the byte in the buffer - * within the given bounds, or {@code -1} if the byte does - * not occur. - * - * @since 4.1 - */ - public int indexOf(final byte b, final int from, final int to) { - int beginIndex = from; - if (beginIndex < 0) { - beginIndex = 0; - } - int endIndex = to; - if (endIndex > this.len) { - endIndex = this.len; - } - if (beginIndex > endIndex) { - return -1; - } - for (int i = beginIndex; i < endIndex; i++) { - if (this.buffer[i] == b) { - return i; - } - } - return -1; - } - - /** - * Returns the index within this buffer of the first occurrence of the - * specified byte, starting the search at {@code 0} and finishing - * at {@link #length()}. If no such byte occurs in this buffer within - * those bounds, {@code -1} is returned. - * - * @param b the byte to search for. - * @return the index of the first occurrence of the byte in the - * buffer, or {@code -1} if the byte does not occur. - * - * @since 4.1 - */ - public int indexOf(final byte b) { - return indexOf(b, 0, this.len); - } -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/CharArrayBuffer.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/CharArrayBuffer.java deleted file mode 100644 index 3a811558..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/CharArrayBuffer.java +++ /dev/null @@ -1,492 +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 com.tracelytics.ext.apache.http.util; - -import java.io.Serializable; -import java.nio.CharBuffer; - -import com.tracelytics.ext.apache.http.annotation.NotThreadSafe; -import com.tracelytics.ext.apache.http.protocol.HTTP; - -/** - * A resizable char array. - * - * @since 4.0 - */ -@NotThreadSafe -public final class CharArrayBuffer implements CharSequence, Serializable { - - private static final long serialVersionUID = -6208952725094867135L; - - private char[] buffer; - private int len; - - /** - * Creates an instance of {@link CharArrayBuffer} with the given initial - * capacity. - * - * @param capacity the capacity - */ - public CharArrayBuffer(final int capacity) { - super(); - Args.notNegative(capacity, "Buffer capacity"); - this.buffer = new char[capacity]; - } - - private void expand(final int newlen) { - final char newbuffer[] = new char[Math.max(this.buffer.length << 1, newlen)]; - System.arraycopy(this.buffer, 0, newbuffer, 0, this.len); - this.buffer = newbuffer; - } - - /** - * Appends {@code len} chars to this buffer from the given source - * array starting at index {@code off}. The capacity of the buffer - * is increased, if necessary, to accommodate all {@code len} chars. - * - * @param b the chars to be appended. - * @param off the index of the first char to append. - * @param len the number of chars to append. - * @throws IndexOutOfBoundsException if {@code off} is out of - * range, {@code len} is negative, or - * {@code off} + {@code len} is out of range. - */ - public void append(final char[] b, final int off, final int len) { - if (b == null) { - return; - } - 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); - } - if (len == 0) { - return; - } - final int newlen = this.len + len; - if (newlen > this.buffer.length) { - expand(newlen); - } - System.arraycopy(b, off, this.buffer, this.len, len); - this.len = newlen; - } - - /** - * Appends chars of the given string to this buffer. The capacity of the - * buffer is increased, if necessary, to accommodate all chars. - * - * @param str the string. - */ - public void append(final String str) { - final String s = str != null ? str : "null"; - final int strlen = s.length(); - final int newlen = this.len + strlen; - if (newlen > this.buffer.length) { - expand(newlen); - } - s.getChars(0, strlen, this.buffer, this.len); - this.len = newlen; - } - - /** - * Appends {@code len} chars to this buffer from the given source - * buffer starting at index {@code off}. The capacity of the - * destination buffer is increased, if necessary, to accommodate all - * {@code len} chars. - * - * @param b the source buffer to be appended. - * @param off the index of the first char to append. - * @param len the number of chars to append. - * @throws IndexOutOfBoundsException if {@code off} is out of - * range, {@code len} is negative, or - * {@code off} + {@code len} is out of range. - */ - public void append(final CharArrayBuffer b, final int off, final int len) { - if (b == null) { - return; - } - append(b.buffer, off, len); - } - - /** - * Appends all chars to this buffer from the given source buffer starting - * at index {@code 0}. The capacity of the destination buffer is - * increased, if necessary, to accommodate all {@link #length()} chars. - * - * @param b the source buffer to be appended. - */ - public void append(final CharArrayBuffer b) { - if (b == null) { - return; - } - append(b.buffer,0, b.len); - } - - /** - * Appends {@code ch} char to this buffer. The capacity of the buffer - * is increased, if necessary, to accommodate the additional char. - * - * @param ch the char to be appended. - */ - public void append(final char ch) { - final int newlen = this.len + 1; - if (newlen > this.buffer.length) { - expand(newlen); - } - this.buffer[this.len] = ch; - this.len = newlen; - } - - /** - * Appends {@code len} bytes to this buffer from the given source - * array starting at index {@code off}. The capacity of the buffer - * is increased, if necessary, to accommodate all {@code len} bytes. - *

- * The bytes are converted to chars using simple cast. - * - * @param b the bytes to be appended. - * @param off the index of the first byte to append. - * @param len the number of bytes to append. - * @throws IndexOutOfBoundsException if {@code off} is out of - * range, {@code len} is negative, or - * {@code off} + {@code len} is out of range. - */ - public void append(final byte[] b, final int off, final int len) { - if (b == null) { - return; - } - 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); - } - if (len == 0) { - return; - } - final int oldlen = this.len; - final int newlen = oldlen + len; - if (newlen > this.buffer.length) { - expand(newlen); - } - for (int i1 = off, i2 = oldlen; i2 < newlen; i1++, i2++) { - this.buffer[i2] = (char) (b[i1] & 0xff); - } - this.len = newlen; - } - - /** - * Appends {@code len} bytes to this buffer from the given source - * array starting at index {@code off}. The capacity of the buffer - * is increased, if necessary, to accommodate all {@code len} bytes. - *

- * The bytes are converted to chars using simple cast. - * - * @param b the bytes to be appended. - * @param off the index of the first byte to append. - * @param len the number of bytes to append. - * @throws IndexOutOfBoundsException if {@code off} is out of - * range, {@code len} is negative, or - * {@code off} + {@code len} is out of range. - */ - public void append(final ByteArrayBuffer b, final int off, final int len) { - if (b == null) { - return; - } - append(b.buffer(), off, len); - } - - /** - * Appends chars of the textual representation of the given object to this - * buffer. The capacity of the buffer is increased, if necessary, to - * accommodate all chars. - * - * @param obj the object. - */ - public void append(final Object obj) { - append(String.valueOf(obj)); - } - - /** - * Clears content of the buffer. The underlying char array is not resized. - */ - public void clear() { - this.len = 0; - } - - /** - * Converts the content of this buffer to an array of chars. - * - * @return char array - */ - public char[] toCharArray() { - final char[] b = new char[this.len]; - if (this.len > 0) { - System.arraycopy(this.buffer, 0, b, 0, this.len); - } - return b; - } - - /** - * Returns the {@code char} value in this buffer at the specified - * index. The index argument must be greater than or equal to - * {@code 0}, and less than the length of this buffer. - * - * @param i the index of the desired char value. - * @return the char value at the specified index. - * @throws IndexOutOfBoundsException if {@code index} is - * negative or greater than or equal to {@link #length()}. - */ - public char charAt(final int i) { - return this.buffer[i]; - } - - /** - * Returns reference to the underlying char array. - * - * @return the char array. - */ - public char[] buffer() { - return this.buffer; - } - - /** - * Returns the current capacity. The capacity is the amount of storage - * available for newly appended chars, beyond which an allocation will - * occur. - * - * @return the current capacity - */ - public int capacity() { - return this.buffer.length; - } - - /** - * Returns the length of the buffer (char count). - * - * @return the length of the buffer - */ - public int length() { - return this.len; - } - - /** - * Ensures that the capacity is at least equal to the specified minimum. - * If the current capacity is less than the argument, then a new internal - * array is allocated with greater capacity. If the {@code required} - * argument is non-positive, this method takes no action. - * - * @param required the minimum required capacity. - */ - public void ensureCapacity(final int required) { - if (required <= 0) { - return; - } - final int available = this.buffer.length - this.len; - if (required > available) { - expand(this.len + required); - } - } - - /** - * Sets the length of the buffer. The new length value is expected to be - * less than the current capacity and greater than or equal to - * {@code 0}. - * - * @param len the new length - * @throws IndexOutOfBoundsException if the - * {@code len} argument is greater than the current - * capacity of the buffer or less than {@code 0}. - */ - public void setLength(final int len) { - if (len < 0 || len > this.buffer.length) { - throw new IndexOutOfBoundsException("len: "+len+" < 0 or > buffer len: "+this.buffer.length); - } - this.len = len; - } - - /** - * Returns {@code true} if this buffer is empty, that is, its - * {@link #length()} is equal to {@code 0}. - * @return {@code true} if this buffer is empty, {@code false} - * otherwise. - */ - public boolean isEmpty() { - return this.len == 0; - } - - /** - * Returns {@code true} if this buffer is full, that is, its - * {@link #length()} is equal to its {@link #capacity()}. - * @return {@code true} if this buffer is full, {@code false} - * otherwise. - */ - public boolean isFull() { - return this.len == this.buffer.length; - } - - /** - * Returns the index within this buffer of the first occurrence of the - * specified character, starting the search at the specified - * {@code beginIndex} and finishing at {@code endIndex}. - * If no such character occurs in this buffer within the specified bounds, - * {@code -1} is returned. - *

- * There is no restriction on the value of {@code beginIndex} and - * {@code endIndex}. If {@code beginIndex} is negative, - * it has the same effect as if it were zero. If {@code endIndex} is - * greater than {@link #length()}, it has the same effect as if it were - * {@link #length()}. If the {@code beginIndex} is greater than - * the {@code endIndex}, {@code -1} is returned. - * - * @param ch the char to search for. - * @param from the index to start the search from. - * @param to the index to finish the search at. - * @return the index of the first occurrence of the character in the buffer - * within the given bounds, or {@code -1} if the character does - * not occur. - */ - public int indexOf(final int ch, final int from, final int to) { - int beginIndex = from; - if (beginIndex < 0) { - beginIndex = 0; - } - int endIndex = to; - if (endIndex > this.len) { - endIndex = this.len; - } - if (beginIndex > endIndex) { - return -1; - } - for (int i = beginIndex; i < endIndex; i++) { - if (this.buffer[i] == ch) { - return i; - } - } - return -1; - } - - /** - * Returns the index within this buffer of the first occurrence of the - * specified character, starting the search at {@code 0} and finishing - * at {@link #length()}. If no such character occurs in this buffer within - * those bounds, {@code -1} is returned. - * - * @param ch the char to search for. - * @return the index of the first occurrence of the character in the - * buffer, or {@code -1} if the character does not occur. - */ - public int indexOf(final int ch) { - return indexOf(ch, 0, this.len); - } - - /** - * Returns a substring of this buffer. The substring begins at the specified - * {@code beginIndex} and extends to the character at index - * {@code endIndex - 1}. - * - * @param beginIndex the beginning index, inclusive. - * @param endIndex the ending index, exclusive. - * @return the specified substring. - * @exception StringIndexOutOfBoundsException if the - * {@code beginIndex} is negative, or - * {@code endIndex} is larger than the length of this - * buffer, or {@code beginIndex} is larger than - * {@code endIndex}. - */ - public String substring(final int beginIndex, final int endIndex) { - if (beginIndex < 0) { - throw new IndexOutOfBoundsException("Negative beginIndex: " + beginIndex); - } - if (endIndex > this.len) { - throw new IndexOutOfBoundsException("endIndex: " + endIndex + " > length: " + this.len); - } - if (beginIndex > endIndex) { - throw new IndexOutOfBoundsException("beginIndex: " + beginIndex + " > endIndex: " + endIndex); - } - return new String(this.buffer, beginIndex, endIndex - beginIndex); - } - - /** - * Returns a substring of this buffer with leading and trailing whitespace - * omitted. The substring begins with the first non-whitespace character - * from {@code beginIndex} and extends to the last - * non-whitespace character with the index lesser than - * {@code endIndex}. - * - * @param beginIndex the beginning index, inclusive. - * @param endIndex the ending index, exclusive. - * @return the specified substring. - * @exception IndexOutOfBoundsException if the - * {@code beginIndex} is negative, or - * {@code endIndex} is larger than the length of this - * buffer, or {@code beginIndex} is larger than - * {@code endIndex}. - */ - public String substringTrimmed(final int beginIndex, final int endIndex) { - if (beginIndex < 0) { - throw new IndexOutOfBoundsException("Negative beginIndex: " + beginIndex); - } - if (endIndex > this.len) { - throw new IndexOutOfBoundsException("endIndex: " + endIndex + " > length: " + this.len); - } - if (beginIndex > endIndex) { - throw new IndexOutOfBoundsException("beginIndex: " + beginIndex + " > endIndex: " + endIndex); - } - int beginIndex0 = beginIndex; - int endIndex0 = endIndex; - while (beginIndex0 < endIndex && HTTP.isWhitespace(this.buffer[beginIndex0])) { - beginIndex0++; - } - while (endIndex0 > beginIndex0 && HTTP.isWhitespace(this.buffer[endIndex0 - 1])) { - endIndex0--; - } - return new String(this.buffer, beginIndex0, endIndex0 - beginIndex0); - } - - /** - * {@inheritDoc} - * @since 4.4 - */ - @Override - public CharSequence subSequence(final int beginIndex, final int endIndex) { - if (beginIndex < 0) { - throw new IndexOutOfBoundsException("Negative beginIndex: " + beginIndex); - } - if (endIndex > this.len) { - throw new IndexOutOfBoundsException("endIndex: " + endIndex + " > length: " + this.len); - } - if (beginIndex > endIndex) { - throw new IndexOutOfBoundsException("beginIndex: " + beginIndex + " > endIndex: " + endIndex); - } - return CharBuffer.wrap(this.buffer, beginIndex, endIndex); - } - - @Override - public String toString() { - return new String(this.buffer, 0, this.len); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/CharsetUtils.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/CharsetUtils.java deleted file mode 100644 index a5af103f..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/CharsetUtils.java +++ /dev/null @@ -1,58 +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 com.tracelytics.ext.apache.http.util; - -import java.io.UnsupportedEncodingException; -import java.nio.charset.Charset; -import java.nio.charset.UnsupportedCharsetException; - -public class CharsetUtils { - - public static Charset lookup(final String name) { - if (name == null) { - return null; - } - try { - return Charset.forName(name); - } catch (final UnsupportedCharsetException ex) { - return null; - } - } - - public static Charset get(final String name) throws UnsupportedEncodingException { - if (name == null) { - return null; - } - try { - return Charset.forName(name); - } catch (final UnsupportedCharsetException ex) { - throw new UnsupportedEncodingException(name); - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/EncodingUtils.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/EncodingUtils.java deleted file mode 100644 index 7db43746..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/EncodingUtils.java +++ /dev/null @@ -1,144 +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 com.tracelytics.ext.apache.http.util; - -import java.io.UnsupportedEncodingException; - -import com.tracelytics.ext.apache.http.Consts; - -/** - * The home for utility methods that handle various encoding tasks. - * - * - * @since 4.0 - */ -public final class EncodingUtils { - - /** - * Converts the byte array of HTTP content characters to a string. If - * the specified charset is not supported, default system encoding - * is used. - * - * @param data the byte array to be encoded - * @param offset the index of the first byte to encode - * @param length the number of bytes to encode - * @param charset the desired character encoding - * @return The result of the conversion. - */ - public static String getString( - final byte[] data, - final int offset, - final int length, - final String charset) { - Args.notNull(data, "Input"); - Args.notEmpty(charset, "Charset"); - try { - return new String(data, offset, length, charset); - } catch (final UnsupportedEncodingException e) { - return new String(data, offset, length); - } - } - - - /** - * Converts the byte array of HTTP content characters to a string. If - * the specified charset is not supported, default system encoding - * is used. - * - * @param data the byte array to be encoded - * @param charset the desired character encoding - * @return The result of the conversion. - */ - public static String getString(final byte[] data, final String charset) { - Args.notNull(data, "Input"); - return getString(data, 0, data.length, charset); - } - - /** - * Converts the specified string to a byte array. If the charset is not supported the - * default system charset is used. - * - * @param data the string to be encoded - * @param charset the desired character encoding - * @return The resulting byte array. - */ - public static byte[] getBytes(final String data, final String charset) { - Args.notNull(data, "Input"); - Args.notEmpty(charset, "Charset"); - try { - return data.getBytes(charset); - } catch (final UnsupportedEncodingException e) { - return data.getBytes(); - } - } - - /** - * Converts the specified string to byte array of ASCII characters. - * - * @param data the string to be encoded - * @return The string as a byte array. - */ - public static byte[] getAsciiBytes(final String data) { - Args.notNull(data, "Input"); - return data.getBytes(Consts.ASCII); - } - - /** - * Converts the byte array of ASCII characters to a string. This method is - * to be used when decoding content of HTTP elements (such as response - * headers) - * - * @param data the byte array to be encoded - * @param offset the index of the first byte to encode - * @param length the number of bytes to encode - * @return The string representation of the byte array - */ - public static String getAsciiString(final byte[] data, final int offset, final int length) { - Args.notNull(data, "Input"); - return new String(data, offset, length, Consts.ASCII); - } - - /** - * Converts the byte array of ASCII characters to a string. This method is - * to be used when decoding content of HTTP elements (such as response - * headers) - * - * @param data the byte array to be encoded - * @return The string representation of the byte array - */ - public static String getAsciiString(final byte[] data) { - Args.notNull(data, "Input"); - return getAsciiString(data, 0, data.length); - } - - /** - * This class should not be instantiated. - */ - private EncodingUtils() { - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/EntityUtils.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/EntityUtils.java deleted file mode 100644 index 4880359d..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/EntityUtils.java +++ /dev/null @@ -1,294 +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 com.tracelytics.ext.apache.http.util; - -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.UnsupportedEncodingException; -import java.nio.charset.Charset; -import java.nio.charset.UnsupportedCharsetException; - -import com.tracelytics.ext.apache.http.HeaderElement; -import com.tracelytics.ext.apache.http.HttpEntity; -import com.tracelytics.ext.apache.http.HttpResponse; -import com.tracelytics.ext.apache.http.NameValuePair; -import com.tracelytics.ext.apache.http.ParseException; -import com.tracelytics.ext.apache.http.entity.ContentType; -import com.tracelytics.ext.apache.http.protocol.HTTP; - -/** - * Static helpers for dealing with {@link HttpEntity}s. - * - * @since 4.0 - */ -public final class EntityUtils { - - private EntityUtils() { - } - - /** - * Ensures that the entity content is fully consumed and the content stream, if exists, - * is closed. The process is done, quietly , without throwing any IOException. - * - * @param entity the entity to consume. - * - * - * @since 4.2 - */ - public static void consumeQuietly(final HttpEntity entity) { - try { - consume(entity); - } catch (final IOException ignore) { - } - } - - /** - * Ensures that the entity content is fully consumed and the content stream, if exists, - * is closed. - * - * @param entity the entity to consume. - * @throws IOException if an error occurs reading the input stream - * - * @since 4.1 - */ - public static void consume(final HttpEntity entity) throws IOException { - if (entity == null) { - return; - } - if (entity.isStreaming()) { - final InputStream instream = entity.getContent(); - if (instream != null) { - instream.close(); - } - } - } - - /** - * Updates an entity in a response by first consuming an existing entity, then setting the new one. - * - * @param response the response with an entity to update; must not be null. - * @param entity the entity to set in the response. - * @throws IOException if an error occurs while reading the input stream on the existing - * entity. - * @throws IllegalArgumentException if response is null. - * - * @since 4.3 - */ - public static void updateEntity( - final HttpResponse response, final HttpEntity entity) throws IOException { - Args.notNull(response, "Response"); - consume(response.getEntity()); - response.setEntity(entity); - } - - /** - * Read the contents of an entity and return it as a byte array. - * - * @param entity the entity to read from= - * @return byte array containing the entity content. May be null if - * {@link HttpEntity#getContent()} is null. - * @throws IOException if an error occurs reading the input stream - * @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE - */ - public static byte[] toByteArray(final HttpEntity entity) throws IOException { - Args.notNull(entity, "Entity"); - final InputStream instream = entity.getContent(); - if (instream == null) { - return null; - } - try { - Args.check(entity.getContentLength() <= Integer.MAX_VALUE, - "HTTP entity too large to be buffered in memory"); - int i = (int)entity.getContentLength(); - if (i < 0) { - i = 4096; - } - final ByteArrayBuffer buffer = new ByteArrayBuffer(i); - final byte[] tmp = new byte[4096]; - int l; - while((l = instream.read(tmp)) != -1) { - buffer.append(tmp, 0, l); - } - return buffer.toByteArray(); - } finally { - instream.close(); - } - } - - /** - * Obtains character set of the entity, if known. - * - * @param entity must not be null - * @return the character set, or null if not found - * @throws ParseException if header elements cannot be parsed - * @throws IllegalArgumentException if entity is null - * - * @deprecated (4.1.3) use {@link ContentType#getOrDefault(HttpEntity)} - */ - @Deprecated - public static String getContentCharSet(final HttpEntity entity) throws ParseException { - Args.notNull(entity, "Entity"); - String charset = null; - if (entity.getContentType() != null) { - final HeaderElement values[] = entity.getContentType().getElements(); - if (values.length > 0) { - final NameValuePair param = values[0].getParameterByName("charset"); - if (param != null) { - charset = param.getValue(); - } - } - } - return charset; - } - - /** - * Obtains MIME type of the entity, if known. - * - * @param entity must not be null - * @return the character set, or null if not found - * @throws ParseException if header elements cannot be parsed - * @throws IllegalArgumentException if entity is null - * - * @since 4.1 - * - * @deprecated (4.1.3) use {@link ContentType#getOrDefault(HttpEntity)} - */ - @Deprecated - public static String getContentMimeType(final HttpEntity entity) throws ParseException { - Args.notNull(entity, "Entity"); - String mimeType = null; - if (entity.getContentType() != null) { - final HeaderElement values[] = entity.getContentType().getElements(); - if (values.length > 0) { - mimeType = values[0].getName(); - } - } - return mimeType; - } - - /** - * Get the entity content as a String, using the provided default character set - * if none is found in the entity. - * If defaultCharset is null, the default "ISO-8859-1" is used. - * - * @param entity must not be null - * @param defaultCharset character set to be applied if none found in the entity, - * or if the entity provided charset is invalid or not available. - * @return the entity content as a String. May be null if - * {@link HttpEntity#getContent()} is null. - * @throws ParseException if header elements cannot be parsed - * @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE - * @throws IOException if an error occurs reading the input stream - * @throws UnsupportedCharsetException Thrown when the named entity's charset is not available in - * this instance of the Java virtual machine and no defaultCharset is provided. - */ - public static String toString( - final HttpEntity entity, final Charset defaultCharset) throws IOException, ParseException { - Args.notNull(entity, "Entity"); - final InputStream instream = entity.getContent(); - if (instream == null) { - return null; - } - try { - Args.check(entity.getContentLength() <= Integer.MAX_VALUE, - "HTTP entity too large to be buffered in memory"); - int i = (int)entity.getContentLength(); - if (i < 0) { - i = 4096; - } - Charset charset = null; - try { - final ContentType contentType = ContentType.get(entity); - if (contentType != null) { - charset = contentType.getCharset(); - } - } catch (final UnsupportedCharsetException ex) { - if (defaultCharset == null) { - throw new UnsupportedEncodingException(ex.getMessage()); - } - } - if (charset == null) { - charset = defaultCharset; - } - if (charset == null) { - charset = HTTP.DEF_CONTENT_CHARSET; - } - final Reader reader = new InputStreamReader(instream, charset); - final CharArrayBuffer buffer = new CharArrayBuffer(i); - final char[] tmp = new char[1024]; - int l; - while((l = reader.read(tmp)) != -1) { - buffer.append(tmp, 0, l); - } - return buffer.toString(); - } finally { - instream.close(); - } - } - - /** - * Get the entity content as a String, using the provided default character set - * if none is found in the entity. - * If defaultCharset is null, the default "ISO-8859-1" is used. - * - * @param entity must not be null - * @param defaultCharset character set to be applied if none found in the entity - * @return the entity content as a String. May be null if - * {@link HttpEntity#getContent()} is null. - * @throws ParseException if header elements cannot be parsed - * @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE - * @throws IOException if an error occurs reading the input stream - * @throws UnsupportedCharsetException Thrown when the named charset is not available in - * this instance of the Java virtual machine - */ - public static String toString( - final HttpEntity entity, final String defaultCharset) throws IOException, ParseException { - return toString(entity, defaultCharset != null ? Charset.forName(defaultCharset) : null); - } - - /** - * Read the contents of an entity and return it as a String. - * The content is converted using the character set from the entity (if any), - * failing that, "ISO-8859-1" is used. - * - * @param entity the entity to convert to a string; must not be null - * @return String containing the content. - * @throws ParseException if header elements cannot be parsed - * @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE - * @throws IOException if an error occurs reading the input stream - * @throws UnsupportedCharsetException Thrown when the named charset is not available in - * this instance of the Java virtual machine - */ - public static String toString(final HttpEntity entity) - throws IOException, ParseException { - return toString(entity, (Charset)null); - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/ExceptionUtils.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/ExceptionUtils.java deleted file mode 100644 index 5f0ae96e..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/ExceptionUtils.java +++ /dev/null @@ -1,82 +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 com.tracelytics.ext.apache.http.util; - -import java.lang.reflect.Method; - -/** - * The home for utility methods that handle various exception-related tasks. - * - * - * @since 4.0 - * - * @deprecated (4.2) no longer used - */ -@Deprecated -public final class ExceptionUtils { - - /** A reference to Throwable's initCause method, or null if it's not there in this JVM */ - static private final Method INIT_CAUSE_METHOD = getInitCauseMethod(); - - /** - * Returns a {@code Method} allowing access to - * {@link Throwable#initCause(Throwable) initCause} method of {@link Throwable}, - * or {@code null} if the method - * does not exist. - * - * @return A {@code Method} for {@code Throwable.initCause}, or - * {@code null} if unavailable. - */ - static private Method getInitCauseMethod() { - try { - final Class[] paramsClasses = new Class[] { Throwable.class }; - return Throwable.class.getMethod("initCause", paramsClasses); - } catch (final NoSuchMethodException e) { - return null; - } - } - - /** - * If we're running on JDK 1.4 or later, initialize the cause for the given throwable. - * - * @param throwable The throwable. - * @param cause The cause of the throwable. - */ - public static void initCause(final Throwable throwable, final Throwable cause) { - if (INIT_CAUSE_METHOD != null) { - try { - INIT_CAUSE_METHOD.invoke(throwable, cause); - } catch (final Exception e) { - // Well, with no logging, the only option is to munch the exception - } - } - } - - private ExceptionUtils() { - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/LangUtils.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/LangUtils.java deleted file mode 100644 index 32c45877..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/LangUtils.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 com.tracelytics.ext.apache.http.util; - -/** - * A set of utility methods to help produce consistent - * {@link Object#equals equals} and {@link Object#hashCode hashCode} methods. - * - * - * @since 4.0 - */ -public final class LangUtils { - - public static final int HASH_SEED = 17; - public static final int HASH_OFFSET = 37; - - /** Disabled default constructor. */ - private LangUtils() { - } - - public static int hashCode(final int seed, final int hashcode) { - return seed * HASH_OFFSET + hashcode; - } - - public static int hashCode(final int seed, final boolean b) { - return hashCode(seed, b ? 1 : 0); - } - - public static int hashCode(final int seed, final Object obj) { - return hashCode(seed, obj != null ? obj.hashCode() : 0); - } - - /** - * Check if two objects are equal. - * - * @param obj1 first object to compare, may be {@code null} - * @param obj2 second object to compare, may be {@code null} - * @return {@code true} if the objects are equal or both null - */ - public static boolean equals(final Object obj1, final Object obj2) { - return obj1 == null ? obj2 == null : obj1.equals(obj2); - } - - /** - * Check if two object arrays are equal. - *

    - *
  • If both parameters are null, return {@code true}
  • - *
  • If one parameter is null, return {@code false}
  • - *
  • If the array lengths are different, return {@code false}
  • - *
  • Compare array elements using .equals(); return {@code false} if any comparisons fail.
  • - *
  • Return {@code true}
  • - *
- * - * @param a1 first array to compare, may be {@code null} - * @param a2 second array to compare, may be {@code null} - * @return {@code true} if the arrays are equal or both null - */ - public static boolean equals(final Object[] a1, final Object[] a2) { - if (a1 == null) { - return a2 == null; - } else { - if (a2 != null && a1.length == a2.length) { - for (int i = 0; i < a1.length; i++) { - if (!equals(a1[i], a2[i])) { - return false; - } - } - return true; - } else { - return false; - } - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/NetUtils.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/NetUtils.java deleted file mode 100644 index cb2fc65e..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/NetUtils.java +++ /dev/null @@ -1,54 +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 com.tracelytics.ext.apache.http.util; - -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.SocketAddress; - -/** - * @since 4.3 - */ -public final class NetUtils { - - public static void formatAddress( - final StringBuilder buffer, - final SocketAddress socketAddress) { - Args.notNull(buffer, "Buffer"); - Args.notNull(socketAddress, "Socket address"); - if (socketAddress instanceof InetSocketAddress) { - final InetSocketAddress socketaddr = ((InetSocketAddress) socketAddress); - final InetAddress inetaddr = socketaddr.getAddress(); - buffer.append(inetaddr != null ? inetaddr.getHostAddress() : inetaddr) - .append(':').append(socketaddr.getPort()); - } else { - buffer.append(socketAddress); - } - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/TextUtils.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/TextUtils.java deleted file mode 100644 index b7b0a213..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/TextUtils.java +++ /dev/null @@ -1,75 +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 com.tracelytics.ext.apache.http.util; - -/** - * @since 4.3 - */ -public final class TextUtils { - - /** - * Returns true if the parameter is null or of zero length - */ - public static boolean isEmpty(final CharSequence s) { - if (s == null) { - return true; - } - return s.length() == 0; - } - - /** - * Returns true if the parameter is null or contains only whitespace - */ - public static boolean isBlank(final CharSequence s) { - if (s == null) { - return true; - } - for (int i = 0; i < s.length(); i++) { - if (!Character.isWhitespace(s.charAt(i))) { - return false; - } - } - return true; - } - - /** - * @since 4.4 - */ - public static boolean containsBlanks(final CharSequence s) { - if (s == null) { - return false; - } - for (int i = 0; i < s.length(); i++) { - if (Character.isWhitespace(s.charAt(i))) { - return true; - } - } - return false; - } - -} diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/VersionInfo.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/VersionInfo.java deleted file mode 100644 index 9c0de2c1..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/VersionInfo.java +++ /dev/null @@ -1,326 +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 com.tracelytics.ext.apache.http.util; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -/** - * Provides access to version information for HTTP components. - * Static methods are used to extract version information from property - * files that are automatically packaged with HTTP component release JARs. - *

- * All available version information is provided in strings, where - * the string format is informal and subject to change without notice. - * Version information is provided for debugging output and interpretation - * by humans, not for automated processing in applications. - *

- * - * @since 4.0 - */ -public class VersionInfo { - - /** A string constant for unavailable information. */ - public final static String UNAVAILABLE = "UNAVAILABLE"; - - /** The filename of the version information files. */ - public final static String VERSION_PROPERTY_FILE = "version.properties"; - - // the property names - public final static String PROPERTY_MODULE = "info.module"; - public final static String PROPERTY_RELEASE = "info.release"; - public final static String PROPERTY_TIMESTAMP = "info.timestamp"; - - - /** The package that contains the version information. */ - private final String infoPackage; - - /** The module from the version info. */ - private final String infoModule; - - /** The release from the version info. */ - private final String infoRelease; - - /** The timestamp from the version info. */ - private final String infoTimestamp; - - /** The classloader from which the version info was obtained. */ - private final String infoClassloader; - - - /** - * Instantiates version information. - * - * @param pckg the package - * @param module the module, or {@code null} - * @param release the release, or {@code null} - * @param time the build time, or {@code null} - * @param clsldr the class loader, or {@code null} - */ - protected VersionInfo(final String pckg, final String module, - final String release, final String time, final String clsldr) { - Args.notNull(pckg, "Package identifier"); - infoPackage = pckg; - infoModule = (module != null) ? module : UNAVAILABLE; - infoRelease = (release != null) ? release : UNAVAILABLE; - infoTimestamp = (time != null) ? time : UNAVAILABLE; - infoClassloader = (clsldr != null) ? clsldr : UNAVAILABLE; - } - - - /** - * Obtains the package name. - * The package name identifies the module or informal unit. - * - * @return the package name, never {@code null} - */ - public final String getPackage() { - return infoPackage; - } - - /** - * Obtains the name of the versioned module or informal unit. - * This data is read from the version information for the package. - * - * @return the module name, never {@code null} - */ - public final String getModule() { - return infoModule; - } - - /** - * Obtains the release of the versioned module or informal unit. - * This data is read from the version information for the package. - * - * @return the release version, never {@code null} - */ - public final String getRelease() { - return infoRelease; - } - - /** - * Obtains the timestamp of the versioned module or informal unit. - * This data is read from the version information for the package. - * - * @return the timestamp, never {@code null} - */ - public final String getTimestamp() { - return infoTimestamp; - } - - /** - * Obtains the classloader used to read the version information. - * This is just the {@code toString} output of the classloader, - * since the version information should not keep a reference to - * the classloader itself. That could prevent garbage collection. - * - * @return the classloader description, never {@code null} - */ - public final String getClassloader() { - return infoClassloader; - } - - - /** - * Provides the version information in human-readable format. - * - * @return a string holding this version information - */ - @Override - public String toString() { - final StringBuilder sb = new StringBuilder - (20 + infoPackage.length() + infoModule.length() + - infoRelease.length() + infoTimestamp.length() + - infoClassloader.length()); - - sb.append("VersionInfo(") - .append(infoPackage).append(':').append(infoModule); - - // If version info is missing, a single "UNAVAILABLE" for the module - // is sufficient. Everything else just clutters the output. - if (!UNAVAILABLE.equals(infoRelease)) { - sb.append(':').append(infoRelease); - } - if (!UNAVAILABLE.equals(infoTimestamp)) { - sb.append(':').append(infoTimestamp); - } - - sb.append(')'); - - if (!UNAVAILABLE.equals(infoClassloader)) { - sb.append('@').append(infoClassloader); - } - - return sb.toString(); - } - - - /** - * Loads version information for a list of packages. - * - * @param pckgs the packages for which to load version info - * @param clsldr the classloader to load from, or - * {@code null} for the thread context classloader - * - * @return the version information for all packages found, - * never {@code null} - */ - public static VersionInfo[] loadVersionInfo(final String[] pckgs, - final ClassLoader clsldr) { - Args.notNull(pckgs, "Package identifier array"); - final List vil = new ArrayList(pckgs.length); - for (final String pckg : pckgs) { - final VersionInfo vi = loadVersionInfo(pckg, clsldr); - if (vi != null) { - vil.add(vi); - } - } - - return vil.toArray(new VersionInfo[vil.size()]); - } - - - /** - * Loads version information for a package. - * - * @param pckg the package for which to load version information, - * for example "com.tracelytics.ext.apache.http". - * The package name should NOT end with a dot. - * @param clsldr the classloader to load from, or - * {@code null} for the thread context classloader - * - * @return the version information for the argument package, or - * {@code null} if not available - */ - public static VersionInfo loadVersionInfo(final String pckg, - final ClassLoader clsldr) { - Args.notNull(pckg, "Package identifier"); - final ClassLoader cl = clsldr != null ? clsldr : Thread.currentThread().getContextClassLoader(); - - Properties vip = null; // version info properties, if available - try { - // com.tracelytics.ext.apache.http becomes - // org/apache/http/version.properties - final InputStream is = cl.getResourceAsStream - (pckg.replace('.', '/') + "/" + VERSION_PROPERTY_FILE); - if (is != null) { - try { - final Properties props = new Properties(); - props.load(is); - vip = props; - } finally { - is.close(); - } - } - } catch (final IOException ex) { - // shamelessly munch this exception - } - - VersionInfo result = null; - if (vip != null) { - result = fromMap(pckg, vip, cl); - } - - return result; - } - - - /** - * Instantiates version information from properties. - * - * @param pckg the package for the version information - * @param info the map from string keys to string values, - * for example {@link java.util.Properties} - * @param clsldr the classloader, or {@code null} - * - * @return the version information - */ - protected static VersionInfo fromMap(final String pckg, final Map info, - final ClassLoader clsldr) { - Args.notNull(pckg, "Package identifier"); - String module = null; - String release = null; - String timestamp = null; - - if (info != null) { - module = (String) info.get(PROPERTY_MODULE); - if ((module != null) && (module.length() < 1)) { - module = null; - } - - release = (String) info.get(PROPERTY_RELEASE); - if ((release != null) && ((release.length() < 1) || - (release.equals("${pom.version}")))) { - release = null; - } - - timestamp = (String) info.get(PROPERTY_TIMESTAMP); - if ((timestamp != null) && - ((timestamp.length() < 1) || - (timestamp.equals("${mvn.timestamp}"))) - ) { - timestamp = null; - } - } // if info - - String clsldrstr = null; - if (clsldr != null) { - clsldrstr = clsldr.toString(); - } - - return new VersionInfo(pckg, module, release, timestamp, clsldrstr); - } - - /** - * Sets the user agent to {@code "/ (Java/)"}. - *

- * For example: - *

"Apache-HttpClient/4.3 (Java/1.6.0_35)"
- * - * @param name the component name, like "Apache-HttpClient". - * @param pkg - * the package for which to load version information, for example "com.tracelytics.ext.apache.http". The package name - * should NOT end with a dot. - * @param cls - * the class' class loader to load from, or {@code null} for the thread context class loader - * @since 4.3 - */ - public static String getUserAgent(final String name, final String pkg, final Class cls) { - // determine the release version from packaged version info - final VersionInfo vi = VersionInfo.loadVersionInfo(pkg, cls.getClassLoader()); - final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE; - final String javaVersion = System.getProperty("java.version"); - - return String.format("%s/%s (Java/%s)", name, release, javaVersion); - } - -} // class VersionInfo diff --git a/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/package-info.java b/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/package-info.java deleted file mode 100644 index 0cca9865..00000000 --- a/dependencies/src/main/java/com/tracelytics/ext/apache/http/util/package-info.java +++ /dev/null @@ -1,31 +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 - * . - * - */ - -/** - * Core utility classes. - */ -package com.tracelytics.ext.apache.http.util;